Merge branch 'master' of https://github.com/erlehmann/minetest-delta.git into upstrea...
[oweals/minetest.git] / src / sqlite / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.6.3.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a single 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 62.  The upper bound on 62 is because a 64-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.6.3"
654 #define SQLITE_VERSION_NUMBER 3007006
655 #define SQLITE_SOURCE_ID      "2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e"
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   /* Unknown opcode in sqlite3_file_control() */
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 /* Reserved:                         0x00F00000 */
1030
1031 /*
1032 ** CAPI3REF: Device Characteristics
1033 **
1034 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1035 ** object returns an integer which is a vector of the these
1036 ** bit values expressing I/O characteristics of the mass storage
1037 ** device that holds the file that the [sqlite3_io_methods]
1038 ** refers to.
1039 **
1040 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1041 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1042 ** mean that writes of blocks that are nnn bytes in size and
1043 ** are aligned to an address which is an integer multiple of
1044 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1045 ** that when data is appended to a file, the data is appended
1046 ** first then the size of the file is extended, never the other
1047 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1048 ** information is written to disk in the same order as calls
1049 ** to xWrite().
1050 */
1051 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1052 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1053 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1054 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1055 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1056 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1057 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1058 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1059 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1060 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1061 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1062 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1063
1064 /*
1065 ** CAPI3REF: File Locking Levels
1066 **
1067 ** SQLite uses one of these integer values as the second
1068 ** argument to calls it makes to the xLock() and xUnlock() methods
1069 ** of an [sqlite3_io_methods] object.
1070 */
1071 #define SQLITE_LOCK_NONE          0
1072 #define SQLITE_LOCK_SHARED        1
1073 #define SQLITE_LOCK_RESERVED      2
1074 #define SQLITE_LOCK_PENDING       3
1075 #define SQLITE_LOCK_EXCLUSIVE     4
1076
1077 /*
1078 ** CAPI3REF: Synchronization Type Flags
1079 **
1080 ** When SQLite invokes the xSync() method of an
1081 ** [sqlite3_io_methods] object it uses a combination of
1082 ** these integer values as the second argument.
1083 **
1084 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1085 ** sync operation only needs to flush data to mass storage.  Inode
1086 ** information need not be flushed. If the lower four bits of the flag
1087 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1088 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1089 ** to use Mac OS X style fullsync instead of fsync().
1090 **
1091 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1092 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1093 ** settings.  The [synchronous pragma] determines when calls to the
1094 ** xSync VFS method occur and applies uniformly across all platforms.
1095 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1096 ** energetic or rigorous or forceful the sync operations are and
1097 ** only make a difference on Mac OSX for the default SQLite code.
1098 ** (Third-party VFS implementations might also make the distinction
1099 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1100 ** operating systems natively supported by SQLite, only Mac OSX
1101 ** cares about the difference.)
1102 */
1103 #define SQLITE_SYNC_NORMAL        0x00002
1104 #define SQLITE_SYNC_FULL          0x00003
1105 #define SQLITE_SYNC_DATAONLY      0x00010
1106
1107 /*
1108 ** CAPI3REF: OS Interface Open File Handle
1109 **
1110 ** An [sqlite3_file] object represents an open file in the 
1111 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1112 ** implementations will
1113 ** want to subclass this object by appending additional fields
1114 ** for their own use.  The pMethods entry is a pointer to an
1115 ** [sqlite3_io_methods] object that defines methods for performing
1116 ** I/O operations on the open file.
1117 */
1118 typedef struct sqlite3_file sqlite3_file;
1119 struct sqlite3_file {
1120   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1121 };
1122
1123 /*
1124 ** CAPI3REF: OS Interface File Virtual Methods Object
1125 **
1126 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1127 ** [sqlite3_file] object (or, more commonly, a subclass of the
1128 ** [sqlite3_file] object) with a pointer to an instance of this object.
1129 ** This object defines the methods used to perform various operations
1130 ** against the open file represented by the [sqlite3_file] object.
1131 **
1132 ** If the xOpen method sets the sqlite3_file.pMethods element 
1133 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1134 ** may be invoked even if the xOpen reported that it failed.  The
1135 ** only way to prevent a call to xClose following a failed xOpen
1136 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1137 **
1138 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1139 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1140 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1141 ** flag may be ORed in to indicate that only the data of the file
1142 ** and not its inode needs to be synced.
1143 **
1144 ** The integer values to xLock() and xUnlock() are one of
1145 ** <ul>
1146 ** <li> [SQLITE_LOCK_NONE],
1147 ** <li> [SQLITE_LOCK_SHARED],
1148 ** <li> [SQLITE_LOCK_RESERVED],
1149 ** <li> [SQLITE_LOCK_PENDING], or
1150 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1151 ** </ul>
1152 ** xLock() increases the lock. xUnlock() decreases the lock.
1153 ** The xCheckReservedLock() method checks whether any database connection,
1154 ** either in this process or in some other process, is holding a RESERVED,
1155 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1156 ** if such a lock exists and false otherwise.
1157 **
1158 ** The xFileControl() method is a generic interface that allows custom
1159 ** VFS implementations to directly control an open file using the
1160 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1161 ** integer opcode.  The third argument is a generic pointer intended to
1162 ** point to a structure that may contain arguments or space in which to
1163 ** write return values.  Potential uses for xFileControl() might be
1164 ** functions to enable blocking locks with timeouts, to change the
1165 ** locking strategy (for example to use dot-file locks), to inquire
1166 ** about the status of a lock, or to break stale locks.  The SQLite
1167 ** core reserves all opcodes less than 100 for its own use.
1168 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1169 ** Applications that define a custom xFileControl method should use opcodes
1170 ** greater than 100 to avoid conflicts.  VFS implementations should
1171 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1172 ** recognize.
1173 **
1174 ** The xSectorSize() method returns the sector size of the
1175 ** device that underlies the file.  The sector size is the
1176 ** minimum write that can be performed without disturbing
1177 ** other bytes in the file.  The xDeviceCharacteristics()
1178 ** method returns a bit vector describing behaviors of the
1179 ** underlying device:
1180 **
1181 ** <ul>
1182 ** <li> [SQLITE_IOCAP_ATOMIC]
1183 ** <li> [SQLITE_IOCAP_ATOMIC512]
1184 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1185 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1186 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1187 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1188 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1189 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1190 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1191 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1192 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1193 ** </ul>
1194 **
1195 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1196 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1197 ** mean that writes of blocks that are nnn bytes in size and
1198 ** are aligned to an address which is an integer multiple of
1199 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1200 ** that when data is appended to a file, the data is appended
1201 ** first then the size of the file is extended, never the other
1202 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1203 ** information is written to disk in the same order as calls
1204 ** to xWrite().
1205 **
1206 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1207 ** in the unread portions of the buffer with zeros.  A VFS that
1208 ** fails to zero-fill short reads might seem to work.  However,
1209 ** failure to zero-fill short reads will eventually lead to
1210 ** database corruption.
1211 */
1212 typedef struct sqlite3_io_methods sqlite3_io_methods;
1213 struct sqlite3_io_methods {
1214   int iVersion;
1215   int (*xClose)(sqlite3_file*);
1216   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1217   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1218   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1219   int (*xSync)(sqlite3_file*, int flags);
1220   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1221   int (*xLock)(sqlite3_file*, int);
1222   int (*xUnlock)(sqlite3_file*, int);
1223   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1224   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1225   int (*xSectorSize)(sqlite3_file*);
1226   int (*xDeviceCharacteristics)(sqlite3_file*);
1227   /* Methods above are valid for version 1 */
1228   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1229   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1230   void (*xShmBarrier)(sqlite3_file*);
1231   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1232   /* Methods above are valid for version 2 */
1233   /* Additional methods may be added in future releases */
1234 };
1235
1236 /*
1237 ** CAPI3REF: Standard File Control Opcodes
1238 **
1239 ** These integer constants are opcodes for the xFileControl method
1240 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1241 ** interface.
1242 **
1243 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1244 ** opcode causes the xFileControl method to write the current state of
1245 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1246 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1247 ** into an integer that the pArg argument points to. This capability
1248 ** is used during testing and only needs to be supported when SQLITE_TEST
1249 ** is defined.
1250 **
1251 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1252 ** layer a hint of how large the database file will grow to be during the
1253 ** current transaction.  This hint is not guaranteed to be accurate but it
1254 ** is often close.  The underlying VFS might choose to preallocate database
1255 ** file space based on this hint in order to help writes to the database
1256 ** file run faster.
1257 **
1258 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1259 ** extends and truncates the database file in chunks of a size specified
1260 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1261 ** point to an integer (type int) containing the new chunk-size to use
1262 ** for the nominated database. Allocating database file space in large
1263 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1264 ** improve performance on some systems.
1265 **
1266 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1267 ** to the [sqlite3_file] object associated with a particular database
1268 ** connection.  See the [sqlite3_file_control()] documentation for
1269 ** additional information.
1270 **
1271 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1272 ** SQLite and sent to all VFSes in place of a call to the xSync method
1273 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1274 ** Some specialized VFSes need this signal in order to operate correctly
1275 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1276 ** VFSes do not need this signal and should silently ignore this opcode.
1277 ** Applications should not call [sqlite3_file_control()] with this
1278 ** opcode as doing so may disrupt the operation of the specialized VFSes
1279 ** that do require it.  
1280 */
1281 #define SQLITE_FCNTL_LOCKSTATE        1
1282 #define SQLITE_GET_LOCKPROXYFILE      2
1283 #define SQLITE_SET_LOCKPROXYFILE      3
1284 #define SQLITE_LAST_ERRNO             4
1285 #define SQLITE_FCNTL_SIZE_HINT        5
1286 #define SQLITE_FCNTL_CHUNK_SIZE       6
1287 #define SQLITE_FCNTL_FILE_POINTER     7
1288 #define SQLITE_FCNTL_SYNC_OMITTED     8
1289
1290
1291 /*
1292 ** CAPI3REF: Mutex Handle
1293 **
1294 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1295 ** abstract type for a mutex object.  The SQLite core never looks
1296 ** at the internal representation of an [sqlite3_mutex].  It only
1297 ** deals with pointers to the [sqlite3_mutex] object.
1298 **
1299 ** Mutexes are created using [sqlite3_mutex_alloc()].
1300 */
1301 typedef struct sqlite3_mutex sqlite3_mutex;
1302
1303 /*
1304 ** CAPI3REF: OS Interface Object
1305 **
1306 ** An instance of the sqlite3_vfs object defines the interface between
1307 ** the SQLite core and the underlying operating system.  The "vfs"
1308 ** in the name of the object stands for "virtual file system".
1309 **
1310 ** The value of the iVersion field is initially 1 but may be larger in
1311 ** future versions of SQLite.  Additional fields may be appended to this
1312 ** object when the iVersion value is increased.  Note that the structure
1313 ** of the sqlite3_vfs object changes in the transaction between
1314 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1315 ** modified.
1316 **
1317 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1318 ** structure used by this VFS.  mxPathname is the maximum length of
1319 ** a pathname in this VFS.
1320 **
1321 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1322 ** the pNext pointer.  The [sqlite3_vfs_register()]
1323 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1324 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1325 ** searches the list.  Neither the application code nor the VFS
1326 ** implementation should use the pNext pointer.
1327 **
1328 ** The pNext field is the only field in the sqlite3_vfs
1329 ** structure that SQLite will ever modify.  SQLite will only access
1330 ** or modify this field while holding a particular static mutex.
1331 ** The application should never modify anything within the sqlite3_vfs
1332 ** object once the object has been registered.
1333 **
1334 ** The zName field holds the name of the VFS module.  The name must
1335 ** be unique across all VFS modules.
1336 **
1337 ** ^SQLite guarantees that the zFilename parameter to xOpen
1338 ** is either a NULL pointer or string obtained
1339 ** from xFullPathname() with an optional suffix added.
1340 ** ^If a suffix is added to the zFilename parameter, it will
1341 ** consist of a single "-" character followed by no more than
1342 ** 10 alphanumeric and/or "-" characters.
1343 ** ^SQLite further guarantees that
1344 ** the string will be valid and unchanged until xClose() is
1345 ** called. Because of the previous sentence,
1346 ** the [sqlite3_file] can safely store a pointer to the
1347 ** filename if it needs to remember the filename for some reason.
1348 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1349 ** must invent its own temporary name for the file.  ^Whenever the 
1350 ** xFilename parameter is NULL it will also be the case that the
1351 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1352 **
1353 ** The flags argument to xOpen() includes all bits set in
1354 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1355 ** or [sqlite3_open16()] is used, then flags includes at least
1356 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1357 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1358 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1359 **
1360 ** ^(SQLite will also add one of the following flags to the xOpen()
1361 ** call, depending on the object being opened:
1362 **
1363 ** <ul>
1364 ** <li>  [SQLITE_OPEN_MAIN_DB]
1365 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1366 ** <li>  [SQLITE_OPEN_TEMP_DB]
1367 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1368 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1369 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1370 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1371 ** <li>  [SQLITE_OPEN_WAL]
1372 ** </ul>)^
1373 **
1374 ** The file I/O implementation can use the object type flags to
1375 ** change the way it deals with files.  For example, an application
1376 ** that does not care about crash recovery or rollback might make
1377 ** the open of a journal file a no-op.  Writes to this journal would
1378 ** also be no-ops, and any attempt to read the journal would return
1379 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1380 ** file will be doing page-aligned sector reads and writes in a random
1381 ** order and set up its I/O subsystem accordingly.
1382 **
1383 ** SQLite might also add one of the following flags to the xOpen method:
1384 **
1385 ** <ul>
1386 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1387 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1388 ** </ul>
1389 **
1390 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1391 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1392 ** will be set for TEMP databases and their journals, transient
1393 ** databases, and subjournals.
1394 **
1395 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1396 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1397 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1398 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1399 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1400 ** be created, and that it is an error if it already exists.
1401 ** It is <i>not</i> used to indicate the file should be opened 
1402 ** for exclusive access.
1403 **
1404 ** ^At least szOsFile bytes of memory are allocated by SQLite
1405 ** to hold the  [sqlite3_file] structure passed as the third
1406 ** argument to xOpen.  The xOpen method does not have to
1407 ** allocate the structure; it should just fill it in.  Note that
1408 ** the xOpen method must set the sqlite3_file.pMethods to either
1409 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1410 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1411 ** element will be valid after xOpen returns regardless of the success
1412 ** or failure of the xOpen call.
1413 **
1414 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1415 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1416 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1417 ** to test whether a file is at least readable.   The file can be a
1418 ** directory.
1419 **
1420 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1421 ** output buffer xFullPathname.  The exact size of the output buffer
1422 ** is also passed as a parameter to both  methods. If the output buffer
1423 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1424 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1425 ** to prevent this by setting mxPathname to a sufficiently large value.
1426 **
1427 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1428 ** interfaces are not strictly a part of the filesystem, but they are
1429 ** included in the VFS structure for completeness.
1430 ** The xRandomness() function attempts to return nBytes bytes
1431 ** of good-quality randomness into zOut.  The return value is
1432 ** the actual number of bytes of randomness obtained.
1433 ** The xSleep() method causes the calling thread to sleep for at
1434 ** least the number of microseconds given.  ^The xCurrentTime()
1435 ** method returns a Julian Day Number for the current date and time as
1436 ** a floating point value.
1437 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1438 ** Day Number multipled by 86400000 (the number of milliseconds in 
1439 ** a 24-hour day).  
1440 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1441 ** date and time if that method is available (if iVersion is 2 or 
1442 ** greater and the function pointer is not NULL) and will fall back
1443 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1444 **
1445 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1446 ** are not used by the SQLite core.  These optional interfaces are provided
1447 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1448 ** system calls with functions under its control, a test program can
1449 ** simulate faults and error conditions that would otherwise be difficult
1450 ** or impossible to induce.  The set of system calls that can be overridden
1451 ** varies from one VFS to another, and from one version of the same VFS to the
1452 ** next.  Applications that use these interfaces must be prepared for any
1453 ** or all of these interfaces to be NULL or for their behavior to change
1454 ** from one release to the next.  Applications must not attempt to access
1455 ** any of these methods if the iVersion of the VFS is less than 3.
1456 */
1457 typedef struct sqlite3_vfs sqlite3_vfs;
1458 typedef void (*sqlite3_syscall_ptr)(void);
1459 struct sqlite3_vfs {
1460   int iVersion;            /* Structure version number (currently 3) */
1461   int szOsFile;            /* Size of subclassed sqlite3_file */
1462   int mxPathname;          /* Maximum file pathname length */
1463   sqlite3_vfs *pNext;      /* Next registered VFS */
1464   const char *zName;       /* Name of this virtual file system */
1465   void *pAppData;          /* Pointer to application-specific data */
1466   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1467                int flags, int *pOutFlags);
1468   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1469   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1470   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1471   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1472   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1473   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1474   void (*xDlClose)(sqlite3_vfs*, void*);
1475   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1476   int (*xSleep)(sqlite3_vfs*, int microseconds);
1477   int (*xCurrentTime)(sqlite3_vfs*, double*);
1478   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1479   /*
1480   ** The methods above are in version 1 of the sqlite_vfs object
1481   ** definition.  Those that follow are added in version 2 or later
1482   */
1483   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1484   /*
1485   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1486   ** Those below are for version 3 and greater.
1487   */
1488   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1489   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1490   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1491   /*
1492   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1493   ** New fields may be appended in figure versions.  The iVersion
1494   ** value will increment whenever this happens. 
1495   */
1496 };
1497
1498 /*
1499 ** CAPI3REF: Flags for the xAccess VFS method
1500 **
1501 ** These integer constants can be used as the third parameter to
1502 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1503 ** what kind of permissions the xAccess method is looking for.
1504 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1505 ** simply checks whether the file exists.
1506 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1507 ** checks whether the named directory is both readable and writable
1508 ** (in other words, if files can be added, removed, and renamed within
1509 ** the directory).
1510 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1511 ** [temp_store_directory pragma], though this could change in a future
1512 ** release of SQLite.
1513 ** With SQLITE_ACCESS_READ, the xAccess method
1514 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1515 ** currently unused, though it might be used in a future release of
1516 ** SQLite.
1517 */
1518 #define SQLITE_ACCESS_EXISTS    0
1519 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1520 #define SQLITE_ACCESS_READ      2   /* Unused */
1521
1522 /*
1523 ** CAPI3REF: Flags for the xShmLock VFS method
1524 **
1525 ** These integer constants define the various locking operations
1526 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1527 ** following are the only legal combinations of flags to the
1528 ** xShmLock method:
1529 **
1530 ** <ul>
1531 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1532 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1533 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1534 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1535 ** </ul>
1536 **
1537 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1538 ** was given no the corresponding lock.  
1539 **
1540 ** The xShmLock method can transition between unlocked and SHARED or
1541 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1542 ** and EXCLUSIVE.
1543 */
1544 #define SQLITE_SHM_UNLOCK       1
1545 #define SQLITE_SHM_LOCK         2
1546 #define SQLITE_SHM_SHARED       4
1547 #define SQLITE_SHM_EXCLUSIVE    8
1548
1549 /*
1550 ** CAPI3REF: Maximum xShmLock index
1551 **
1552 ** The xShmLock method on [sqlite3_io_methods] may use values
1553 ** between 0 and this upper bound as its "offset" argument.
1554 ** The SQLite core will never attempt to acquire or release a
1555 ** lock outside of this range
1556 */
1557 #define SQLITE_SHM_NLOCK        8
1558
1559
1560 /*
1561 ** CAPI3REF: Initialize The SQLite Library
1562 **
1563 ** ^The sqlite3_initialize() routine initializes the
1564 ** SQLite library.  ^The sqlite3_shutdown() routine
1565 ** deallocates any resources that were allocated by sqlite3_initialize().
1566 ** These routines are designed to aid in process initialization and
1567 ** shutdown on embedded systems.  Workstation applications using
1568 ** SQLite normally do not need to invoke either of these routines.
1569 **
1570 ** A call to sqlite3_initialize() is an "effective" call if it is
1571 ** the first time sqlite3_initialize() is invoked during the lifetime of
1572 ** the process, or if it is the first time sqlite3_initialize() is invoked
1573 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1574 ** of sqlite3_initialize() does any initialization.  All other calls
1575 ** are harmless no-ops.)^
1576 **
1577 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1578 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1579 ** an effective call to sqlite3_shutdown() does any deinitialization.
1580 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1581 **
1582 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1583 ** is not.  The sqlite3_shutdown() interface must only be called from a
1584 ** single thread.  All open [database connections] must be closed and all
1585 ** other SQLite resources must be deallocated prior to invoking
1586 ** sqlite3_shutdown().
1587 **
1588 ** Among other things, ^sqlite3_initialize() will invoke
1589 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1590 ** will invoke sqlite3_os_end().
1591 **
1592 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1593 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1594 ** the library (perhaps it is unable to allocate a needed resource such
1595 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1596 **
1597 ** ^The sqlite3_initialize() routine is called internally by many other
1598 ** SQLite interfaces so that an application usually does not need to
1599 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1600 ** calls sqlite3_initialize() so the SQLite library will be automatically
1601 ** initialized when [sqlite3_open()] is called if it has not be initialized
1602 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1603 ** compile-time option, then the automatic calls to sqlite3_initialize()
1604 ** are omitted and the application must call sqlite3_initialize() directly
1605 ** prior to using any other SQLite interface.  For maximum portability,
1606 ** it is recommended that applications always invoke sqlite3_initialize()
1607 ** directly prior to using any other SQLite interface.  Future releases
1608 ** of SQLite may require this.  In other words, the behavior exhibited
1609 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1610 ** default behavior in some future release of SQLite.
1611 **
1612 ** The sqlite3_os_init() routine does operating-system specific
1613 ** initialization of the SQLite library.  The sqlite3_os_end()
1614 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1615 ** performed by these routines include allocation or deallocation
1616 ** of static resources, initialization of global variables,
1617 ** setting up a default [sqlite3_vfs] module, or setting up
1618 ** a default configuration using [sqlite3_config()].
1619 **
1620 ** The application should never invoke either sqlite3_os_init()
1621 ** or sqlite3_os_end() directly.  The application should only invoke
1622 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1623 ** interface is called automatically by sqlite3_initialize() and
1624 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1625 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1626 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1627 ** When [custom builds | built for other platforms]
1628 ** (using the [SQLITE_OS_OTHER=1] compile-time
1629 ** option) the application must supply a suitable implementation for
1630 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1631 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1632 ** must return [SQLITE_OK] on success and some other [error code] upon
1633 ** failure.
1634 */
1635 SQLITE_API int sqlite3_initialize(void);
1636 SQLITE_API int sqlite3_shutdown(void);
1637 SQLITE_API int sqlite3_os_init(void);
1638 SQLITE_API int sqlite3_os_end(void);
1639
1640 /*
1641 ** CAPI3REF: Configuring The SQLite Library
1642 **
1643 ** The sqlite3_config() interface is used to make global configuration
1644 ** changes to SQLite in order to tune SQLite to the specific needs of
1645 ** the application.  The default configuration is recommended for most
1646 ** applications and so this routine is usually not necessary.  It is
1647 ** provided to support rare applications with unusual needs.
1648 **
1649 ** The sqlite3_config() interface is not threadsafe.  The application
1650 ** must insure that no other SQLite interfaces are invoked by other
1651 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1652 ** may only be invoked prior to library initialization using
1653 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1654 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1655 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1656 ** Note, however, that ^sqlite3_config() can be called as part of the
1657 ** implementation of an application-defined [sqlite3_os_init()].
1658 **
1659 ** The first argument to sqlite3_config() is an integer
1660 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1661 ** what property of SQLite is to be configured.  Subsequent arguments
1662 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1663 ** in the first argument.
1664 **
1665 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1666 ** ^If the option is unknown or SQLite is unable to set the option
1667 ** then this routine returns a non-zero [error code].
1668 */
1669 SQLITE_API int sqlite3_config(int, ...);
1670
1671 /*
1672 ** CAPI3REF: Configure database connections
1673 **
1674 ** The sqlite3_db_config() interface is used to make configuration
1675 ** changes to a [database connection].  The interface is similar to
1676 ** [sqlite3_config()] except that the changes apply to a single
1677 ** [database connection] (specified in the first argument).
1678 **
1679 ** The second argument to sqlite3_db_config(D,V,...)  is the
1680 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1681 ** that indicates what aspect of the [database connection] is being configured.
1682 ** Subsequent arguments vary depending on the configuration verb.
1683 **
1684 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1685 ** the call is considered successful.
1686 */
1687 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1688
1689 /*
1690 ** CAPI3REF: Memory Allocation Routines
1691 **
1692 ** An instance of this object defines the interface between SQLite
1693 ** and low-level memory allocation routines.
1694 **
1695 ** This object is used in only one place in the SQLite interface.
1696 ** A pointer to an instance of this object is the argument to
1697 ** [sqlite3_config()] when the configuration option is
1698 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1699 ** By creating an instance of this object
1700 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1701 ** during configuration, an application can specify an alternative
1702 ** memory allocation subsystem for SQLite to use for all of its
1703 ** dynamic memory needs.
1704 **
1705 ** Note that SQLite comes with several [built-in memory allocators]
1706 ** that are perfectly adequate for the overwhelming majority of applications
1707 ** and that this object is only useful to a tiny minority of applications
1708 ** with specialized memory allocation requirements.  This object is
1709 ** also used during testing of SQLite in order to specify an alternative
1710 ** memory allocator that simulates memory out-of-memory conditions in
1711 ** order to verify that SQLite recovers gracefully from such
1712 ** conditions.
1713 **
1714 ** The xMalloc and xFree methods must work like the
1715 ** malloc() and free() functions from the standard C library.
1716 ** The xRealloc method must work like realloc() from the standard C library
1717 ** with the exception that if the second argument to xRealloc is zero,
1718 ** xRealloc must be a no-op - it must not perform any allocation or
1719 ** deallocation.  ^SQLite guarantees that the second argument to
1720 ** xRealloc is always a value returned by a prior call to xRoundup.
1721 ** And so in cases where xRoundup always returns a positive number,
1722 ** xRealloc can perform exactly as the standard library realloc() and
1723 ** still be in compliance with this specification.
1724 **
1725 ** xSize should return the allocated size of a memory allocation
1726 ** previously obtained from xMalloc or xRealloc.  The allocated size
1727 ** is always at least as big as the requested size but may be larger.
1728 **
1729 ** The xRoundup method returns what would be the allocated size of
1730 ** a memory allocation given a particular requested size.  Most memory
1731 ** allocators round up memory allocations at least to the next multiple
1732 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1733 ** Every memory allocation request coming in through [sqlite3_malloc()]
1734 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1735 ** that causes the corresponding memory allocation to fail.
1736 **
1737 ** The xInit method initializes the memory allocator.  (For example,
1738 ** it might allocate any require mutexes or initialize internal data
1739 ** structures.  The xShutdown method is invoked (indirectly) by
1740 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1741 ** by xInit.  The pAppData pointer is used as the only parameter to
1742 ** xInit and xShutdown.
1743 **
1744 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1745 ** the xInit method, so the xInit method need not be threadsafe.  The
1746 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1747 ** not need to be threadsafe either.  For all other methods, SQLite
1748 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1749 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1750 ** it is by default) and so the methods are automatically serialized.
1751 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1752 ** methods must be threadsafe or else make their own arrangements for
1753 ** serialization.
1754 **
1755 ** SQLite will never invoke xInit() more than once without an intervening
1756 ** call to xShutdown().
1757 */
1758 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1759 struct sqlite3_mem_methods {
1760   void *(*xMalloc)(int);         /* Memory allocation function */
1761   void (*xFree)(void*);          /* Free a prior allocation */
1762   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1763   int (*xSize)(void*);           /* Return the size of an allocation */
1764   int (*xRoundup)(int);          /* Round up request size to allocation size */
1765   int (*xInit)(void*);           /* Initialize the memory allocator */
1766   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1767   void *pAppData;                /* Argument to xInit() and xShutdown() */
1768 };
1769
1770 /*
1771 ** CAPI3REF: Configuration Options
1772 **
1773 ** These constants are the available integer configuration options that
1774 ** can be passed as the first argument to the [sqlite3_config()] interface.
1775 **
1776 ** New configuration options may be added in future releases of SQLite.
1777 ** Existing configuration options might be discontinued.  Applications
1778 ** should check the return code from [sqlite3_config()] to make sure that
1779 ** the call worked.  The [sqlite3_config()] interface will return a
1780 ** non-zero [error code] if a discontinued or unsupported configuration option
1781 ** is invoked.
1782 **
1783 ** <dl>
1784 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1785 ** <dd>There are no arguments to this option.  ^This option sets the
1786 ** [threading mode] to Single-thread.  In other words, it disables
1787 ** all mutexing and puts SQLite into a mode where it can only be used
1788 ** by a single thread.   ^If SQLite is compiled with
1789 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1790 ** it is not possible to change the [threading mode] from its default
1791 ** value of Single-thread and so [sqlite3_config()] will return 
1792 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1793 ** configuration option.</dd>
1794 **
1795 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1796 ** <dd>There are no arguments to this option.  ^This option sets the
1797 ** [threading mode] to Multi-thread.  In other words, it disables
1798 ** mutexing on [database connection] and [prepared statement] objects.
1799 ** The application is responsible for serializing access to
1800 ** [database connections] and [prepared statements].  But other mutexes
1801 ** are enabled so that SQLite will be safe to use in a multi-threaded
1802 ** environment as long as no two threads attempt to use the same
1803 ** [database connection] at the same time.  ^If SQLite is compiled with
1804 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1805 ** it is not possible to set the Multi-thread [threading mode] and
1806 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1807 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1808 **
1809 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1810 ** <dd>There are no arguments to this option.  ^This option sets the
1811 ** [threading mode] to Serialized. In other words, this option enables
1812 ** all mutexes including the recursive
1813 ** mutexes on [database connection] and [prepared statement] objects.
1814 ** In this mode (which is the default when SQLite is compiled with
1815 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1816 ** to [database connections] and [prepared statements] so that the
1817 ** application is free to use the same [database connection] or the
1818 ** same [prepared statement] in different threads at the same time.
1819 ** ^If SQLite is compiled with
1820 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821 ** it is not possible to set the Serialized [threading mode] and
1822 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1824 **
1825 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1826 ** <dd> ^(This option takes a single argument which is a pointer to an
1827 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1828 ** alternative low-level memory allocation routines to be used in place of
1829 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1830 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1831 ** before the [sqlite3_config()] call returns.</dd>
1832 **
1833 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1834 ** <dd> ^(This option takes a single argument which is a pointer to an
1835 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1836 ** structure is filled with the currently defined memory allocation routines.)^
1837 ** This option can be used to overload the default memory allocation
1838 ** routines with a wrapper that simulations memory allocation failure or
1839 ** tracks memory usage, for example. </dd>
1840 **
1841 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1842 ** <dd> ^This option takes single argument of type int, interpreted as a 
1843 ** boolean, which enables or disables the collection of memory allocation 
1844 ** statistics. ^(When memory allocation statistics are disabled, the 
1845 ** following SQLite interfaces become non-operational:
1846 **   <ul>
1847 **   <li> [sqlite3_memory_used()]
1848 **   <li> [sqlite3_memory_highwater()]
1849 **   <li> [sqlite3_soft_heap_limit64()]
1850 **   <li> [sqlite3_status()]
1851 **   </ul>)^
1852 ** ^Memory allocation statistics are enabled by default unless SQLite is
1853 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1854 ** allocation statistics are disabled by default.
1855 ** </dd>
1856 **
1857 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1858 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1859 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1860 ** aligned memory buffer from which the scratch allocations will be
1861 ** drawn, the size of each scratch allocation (sz),
1862 ** and the maximum number of scratch allocations (N).  The sz
1863 ** argument must be a multiple of 16.
1864 ** The first argument must be a pointer to an 8-byte aligned buffer
1865 ** of at least sz*N bytes of memory.
1866 ** ^SQLite will use no more than two scratch buffers per thread.  So
1867 ** N should be set to twice the expected maximum number of threads.
1868 ** ^SQLite will never require a scratch buffer that is more than 6
1869 ** times the database page size. ^If SQLite needs needs additional
1870 ** scratch memory beyond what is provided by this configuration option, then 
1871 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1872 **
1873 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1874 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1875 ** the database page cache with the default page cache implemenation.  
1876 ** This configuration should not be used if an application-define page
1877 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1878 ** There are three arguments to this option: A pointer to 8-byte aligned
1879 ** memory, the size of each page buffer (sz), and the number of pages (N).
1880 ** The sz argument should be the size of the largest database page
1881 ** (a power of two between 512 and 32768) plus a little extra for each
1882 ** page header.  ^The page header size is 20 to 40 bytes depending on
1883 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1884 ** to make sz a little too large.  The first
1885 ** argument should point to an allocation of at least sz*N bytes of memory.
1886 ** ^SQLite will use the memory provided by the first argument to satisfy its
1887 ** memory needs for the first N pages that it adds to cache.  ^If additional
1888 ** page cache memory is needed beyond what is provided by this option, then
1889 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1890 ** The pointer in the first argument must
1891 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1892 ** will be undefined.</dd>
1893 **
1894 ** <dt>SQLITE_CONFIG_HEAP</dt>
1895 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1896 ** for all of its dynamic memory allocation needs beyond those provided
1897 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1898 ** There are three arguments: An 8-byte aligned pointer to the memory,
1899 ** the number of bytes in the memory buffer, and the minimum allocation size.
1900 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1901 ** to using its default memory allocator (the system malloc() implementation),
1902 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1903 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1904 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1905 ** allocator is engaged to handle all of SQLites memory allocation needs.
1906 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1907 ** boundary or subsequent behavior of SQLite will be undefined.
1908 ** The minimum allocation size is capped at 2^12. Reasonable values
1909 ** for the minimum allocation size are 2^5 through 2^8.</dd>
1910 **
1911 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1912 ** <dd> ^(This option takes a single argument which is a pointer to an
1913 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1914 ** alternative low-level mutex routines to be used in place
1915 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1916 ** content of the [sqlite3_mutex_methods] structure before the call to
1917 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1918 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1919 ** the entire mutexing subsystem is omitted from the build and hence calls to
1920 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1921 ** return [SQLITE_ERROR].</dd>
1922 **
1923 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1924 ** <dd> ^(This option takes a single argument which is a pointer to an
1925 ** instance of the [sqlite3_mutex_methods] structure.  The
1926 ** [sqlite3_mutex_methods]
1927 ** structure is filled with the currently defined mutex routines.)^
1928 ** This option can be used to overload the default mutex allocation
1929 ** routines with a wrapper used to track mutex usage for performance
1930 ** profiling or testing, for example.   ^If SQLite is compiled with
1931 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932 ** the entire mutexing subsystem is omitted from the build and hence calls to
1933 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1934 ** return [SQLITE_ERROR].</dd>
1935 **
1936 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1937 ** <dd> ^(This option takes two arguments that determine the default
1938 ** memory allocation for the lookaside memory allocator on each
1939 ** [database connection].  The first argument is the
1940 ** size of each lookaside buffer slot and the second is the number of
1941 ** slots allocated to each database connection.)^  ^(This option sets the
1942 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1943 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1944 ** configuration on individual connections.)^ </dd>
1945 **
1946 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1947 ** <dd> ^(This option takes a single argument which is a pointer to
1948 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1949 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1950 ** object and uses it for page cache memory allocations.</dd>
1951 **
1952 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1953 ** <dd> ^(This option takes a single argument which is a pointer to an
1954 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1955 ** page cache implementation into that object.)^ </dd>
1956 **
1957 ** <dt>SQLITE_CONFIG_LOG</dt>
1958 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1959 ** function with a call signature of void(*)(void*,int,const char*), 
1960 ** and a pointer to void. ^If the function pointer is not NULL, it is
1961 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1962 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1963 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1964 ** passed through as the first parameter to the application-defined logger
1965 ** function whenever that function is invoked.  ^The second parameter to
1966 ** the logger function is a copy of the first parameter to the corresponding
1967 ** [sqlite3_log()] call and is intended to be a [result code] or an
1968 ** [extended result code].  ^The third parameter passed to the logger is
1969 ** log message after formatting via [sqlite3_snprintf()].
1970 ** The SQLite logging interface is not reentrant; the logger function
1971 ** supplied by the application must not invoke any SQLite interface.
1972 ** In a multi-threaded application, the application-defined logger
1973 ** function must be threadsafe. </dd>
1974 **
1975 ** </dl>
1976 */
1977 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1978 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1979 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1980 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1981 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1982 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1983 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1984 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1985 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1986 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1987 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1988 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1989 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1990 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1991 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1992 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1993
1994 /*
1995 ** CAPI3REF: Database Connection Configuration Options
1996 **
1997 ** These constants are the available integer configuration options that
1998 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1999 **
2000 ** New configuration options may be added in future releases of SQLite.
2001 ** Existing configuration options might be discontinued.  Applications
2002 ** should check the return code from [sqlite3_db_config()] to make sure that
2003 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2004 ** non-zero [error code] if a discontinued or unsupported configuration option
2005 ** is invoked.
2006 **
2007 ** <dl>
2008 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2009 ** <dd> ^This option takes three additional arguments that determine the 
2010 ** [lookaside memory allocator] configuration for the [database connection].
2011 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2012 ** pointer to a memory buffer to use for lookaside memory.
2013 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2014 ** may be NULL in which case SQLite will allocate the
2015 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2016 ** size of each lookaside buffer slot.  ^The third argument is the number of
2017 ** slots.  The size of the buffer in the first argument must be greater than
2018 ** or equal to the product of the second and third arguments.  The buffer
2019 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2020 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2021 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2022 ** configuration for a database connection can only be changed when that
2023 ** connection is not currently using lookaside memory, or in other words
2024 ** when the "current value" returned by
2025 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2026 ** Any attempt to change the lookaside memory configuration when lookaside
2027 ** memory is in use leaves the configuration unchanged and returns 
2028 ** [SQLITE_BUSY].)^</dd>
2029 **
2030 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2031 ** <dd> ^This option is used to enable or disable the enforcement of
2032 ** [foreign key constraints].  There should be two additional arguments.
2033 ** The first argument is an integer which is 0 to disable FK enforcement,
2034 ** positive to enable FK enforcement or negative to leave FK enforcement
2035 ** unchanged.  The second parameter is a pointer to an integer into which
2036 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2037 ** following this call.  The second parameter may be a NULL pointer, in
2038 ** which case the FK enforcement setting is not reported back. </dd>
2039 **
2040 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2041 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2042 ** There should be two additional arguments.
2043 ** The first argument is an integer which is 0 to disable triggers,
2044 ** positive to enable triggers or negative to leave the setting unchanged.
2045 ** The second parameter is a pointer to an integer into which
2046 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2047 ** following this call.  The second parameter may be a NULL pointer, in
2048 ** which case the trigger setting is not reported back. </dd>
2049 **
2050 ** </dl>
2051 */
2052 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2053 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2054 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2055
2056
2057 /*
2058 ** CAPI3REF: Enable Or Disable Extended Result Codes
2059 **
2060 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2061 ** [extended result codes] feature of SQLite. ^The extended result
2062 ** codes are disabled by default for historical compatibility.
2063 */
2064 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2065
2066 /*
2067 ** CAPI3REF: Last Insert Rowid
2068 **
2069 ** ^Each entry in an SQLite table has a unique 64-bit signed
2070 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2071 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2072 ** names are not also used by explicitly declared columns. ^If
2073 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2074 ** is another alias for the rowid.
2075 **
2076 ** ^This routine returns the [rowid] of the most recent
2077 ** successful [INSERT] into the database from the [database connection]
2078 ** in the first argument.  ^If no successful [INSERT]s
2079 ** have ever occurred on that database connection, zero is returned.
2080 **
2081 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2082 ** row is returned by this routine as long as the trigger is running.
2083 ** But once the trigger terminates, the value returned by this routine
2084 ** reverts to the last value inserted before the trigger fired.)^
2085 **
2086 ** ^An [INSERT] that fails due to a constraint violation is not a
2087 ** successful [INSERT] and does not change the value returned by this
2088 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2089 ** and INSERT OR ABORT make no changes to the return value of this
2090 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2091 ** encounters a constraint violation, it does not fail.  The
2092 ** INSERT continues to completion after deleting rows that caused
2093 ** the constraint problem so INSERT OR REPLACE will always change
2094 ** the return value of this interface.)^
2095 **
2096 ** ^For the purposes of this routine, an [INSERT] is considered to
2097 ** be successful even if it is subsequently rolled back.
2098 **
2099 ** This function is accessible to SQL statements via the
2100 ** [last_insert_rowid() SQL function].
2101 **
2102 ** If a separate thread performs a new [INSERT] on the same
2103 ** database connection while the [sqlite3_last_insert_rowid()]
2104 ** function is running and thus changes the last insert [rowid],
2105 ** then the value returned by [sqlite3_last_insert_rowid()] is
2106 ** unpredictable and might not equal either the old or the new
2107 ** last insert [rowid].
2108 */
2109 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2110
2111 /*
2112 ** CAPI3REF: Count The Number Of Rows Modified
2113 **
2114 ** ^This function returns the number of database rows that were changed
2115 ** or inserted or deleted by the most recently completed SQL statement
2116 ** on the [database connection] specified by the first parameter.
2117 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2118 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2119 ** triggers or [foreign key actions] are not counted.)^ Use the
2120 ** [sqlite3_total_changes()] function to find the total number of changes
2121 ** including changes caused by triggers and foreign key actions.
2122 **
2123 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2124 ** are not counted.  Only real table changes are counted.
2125 **
2126 ** ^(A "row change" is a change to a single row of a single table
2127 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2128 ** are changed as side effects of [REPLACE] constraint resolution,
2129 ** rollback, ABORT processing, [DROP TABLE], or by any other
2130 ** mechanisms do not count as direct row changes.)^
2131 **
2132 ** A "trigger context" is a scope of execution that begins and
2133 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2134 ** Most SQL statements are
2135 ** evaluated outside of any trigger.  This is the "top level"
2136 ** trigger context.  If a trigger fires from the top level, a
2137 ** new trigger context is entered for the duration of that one
2138 ** trigger.  Subtriggers create subcontexts for their duration.
2139 **
2140 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2141 ** not create a new trigger context.
2142 **
2143 ** ^This function returns the number of direct row changes in the
2144 ** most recent INSERT, UPDATE, or DELETE statement within the same
2145 ** trigger context.
2146 **
2147 ** ^Thus, when called from the top level, this function returns the
2148 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2149 ** that also occurred at the top level.  ^(Within the body of a trigger,
2150 ** the sqlite3_changes() interface can be called to find the number of
2151 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2152 ** statement within the body of the same trigger.
2153 ** However, the number returned does not include changes
2154 ** caused by subtriggers since those have their own context.)^
2155 **
2156 ** See also the [sqlite3_total_changes()] interface, the
2157 ** [count_changes pragma], and the [changes() SQL function].
2158 **
2159 ** If a separate thread makes changes on the same database connection
2160 ** while [sqlite3_changes()] is running then the value returned
2161 ** is unpredictable and not meaningful.
2162 */
2163 SQLITE_API int sqlite3_changes(sqlite3*);
2164
2165 /*
2166 ** CAPI3REF: Total Number Of Rows Modified
2167 **
2168 ** ^This function returns the number of row changes caused by [INSERT],
2169 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2170 ** ^(The count returned by sqlite3_total_changes() includes all changes
2171 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2172 ** [foreign key actions]. However,
2173 ** the count does not include changes used to implement [REPLACE] constraints,
2174 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2175 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2176 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2177 ** are counted.)^
2178 ** ^The sqlite3_total_changes() function counts the changes as soon as
2179 ** the statement that makes them is completed (when the statement handle
2180 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2181 **
2182 ** See also the [sqlite3_changes()] interface, the
2183 ** [count_changes pragma], and the [total_changes() SQL function].
2184 **
2185 ** If a separate thread makes changes on the same database connection
2186 ** while [sqlite3_total_changes()] is running then the value
2187 ** returned is unpredictable and not meaningful.
2188 */
2189 SQLITE_API int sqlite3_total_changes(sqlite3*);
2190
2191 /*
2192 ** CAPI3REF: Interrupt A Long-Running Query
2193 **
2194 ** ^This function causes any pending database operation to abort and
2195 ** return at its earliest opportunity. This routine is typically
2196 ** called in response to a user action such as pressing "Cancel"
2197 ** or Ctrl-C where the user wants a long query operation to halt
2198 ** immediately.
2199 **
2200 ** ^It is safe to call this routine from a thread different from the
2201 ** thread that is currently running the database operation.  But it
2202 ** is not safe to call this routine with a [database connection] that
2203 ** is closed or might close before sqlite3_interrupt() returns.
2204 **
2205 ** ^If an SQL operation is very nearly finished at the time when
2206 ** sqlite3_interrupt() is called, then it might not have an opportunity
2207 ** to be interrupted and might continue to completion.
2208 **
2209 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2210 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2211 ** that is inside an explicit transaction, then the entire transaction
2212 ** will be rolled back automatically.
2213 **
2214 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2215 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2216 ** that are started after the sqlite3_interrupt() call and before the 
2217 ** running statements reaches zero are interrupted as if they had been
2218 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2219 ** that are started after the running statement count reaches zero are
2220 ** not effected by the sqlite3_interrupt().
2221 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2222 ** SQL statements is a no-op and has no effect on SQL statements
2223 ** that are started after the sqlite3_interrupt() call returns.
2224 **
2225 ** If the database connection closes while [sqlite3_interrupt()]
2226 ** is running then bad things will likely happen.
2227 */
2228 SQLITE_API void sqlite3_interrupt(sqlite3*);
2229
2230 /*
2231 ** CAPI3REF: Determine If An SQL Statement Is Complete
2232 **
2233 ** These routines are useful during command-line input to determine if the
2234 ** currently entered text seems to form a complete SQL statement or
2235 ** if additional input is needed before sending the text into
2236 ** SQLite for parsing.  ^These routines return 1 if the input string
2237 ** appears to be a complete SQL statement.  ^A statement is judged to be
2238 ** complete if it ends with a semicolon token and is not a prefix of a
2239 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2240 ** string literals or quoted identifier names or comments are not
2241 ** independent tokens (they are part of the token in which they are
2242 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2243 ** and comments that follow the final semicolon are ignored.
2244 **
2245 ** ^These routines return 0 if the statement is incomplete.  ^If a
2246 ** memory allocation fails, then SQLITE_NOMEM is returned.
2247 **
2248 ** ^These routines do not parse the SQL statements thus
2249 ** will not detect syntactically incorrect SQL.
2250 **
2251 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2252 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2253 ** automatically by sqlite3_complete16().  If that initialization fails,
2254 ** then the return value from sqlite3_complete16() will be non-zero
2255 ** regardless of whether or not the input SQL is complete.)^
2256 **
2257 ** The input to [sqlite3_complete()] must be a zero-terminated
2258 ** UTF-8 string.
2259 **
2260 ** The input to [sqlite3_complete16()] must be a zero-terminated
2261 ** UTF-16 string in native byte order.
2262 */
2263 SQLITE_API int sqlite3_complete(const char *sql);
2264 SQLITE_API int sqlite3_complete16(const void *sql);
2265
2266 /*
2267 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2268 **
2269 ** ^This routine sets a callback function that might be invoked whenever
2270 ** an attempt is made to open a database table that another thread
2271 ** or process has locked.
2272 **
2273 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2274 ** is returned immediately upon encountering the lock.  ^If the busy callback
2275 ** is not NULL, then the callback might be invoked with two arguments.
2276 **
2277 ** ^The first argument to the busy handler is a copy of the void* pointer which
2278 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2279 ** the busy handler callback is the number of times that the busy handler has
2280 ** been invoked for this locking event.  ^If the
2281 ** busy callback returns 0, then no additional attempts are made to
2282 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2283 ** ^If the callback returns non-zero, then another attempt
2284 ** is made to open the database for reading and the cycle repeats.
2285 **
2286 ** The presence of a busy handler does not guarantee that it will be invoked
2287 ** when there is lock contention. ^If SQLite determines that invoking the busy
2288 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2289 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2290 ** Consider a scenario where one process is holding a read lock that
2291 ** it is trying to promote to a reserved lock and
2292 ** a second process is holding a reserved lock that it is trying
2293 ** to promote to an exclusive lock.  The first process cannot proceed
2294 ** because it is blocked by the second and the second process cannot
2295 ** proceed because it is blocked by the first.  If both processes
2296 ** invoke the busy handlers, neither will make any progress.  Therefore,
2297 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2298 ** will induce the first process to release its read lock and allow
2299 ** the second process to proceed.
2300 **
2301 ** ^The default busy callback is NULL.
2302 **
2303 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2304 ** when SQLite is in the middle of a large transaction where all the
2305 ** changes will not fit into the in-memory cache.  SQLite will
2306 ** already hold a RESERVED lock on the database file, but it needs
2307 ** to promote this lock to EXCLUSIVE so that it can spill cache
2308 ** pages into the database file without harm to concurrent
2309 ** readers.  ^If it is unable to promote the lock, then the in-memory
2310 ** cache will be left in an inconsistent state and so the error
2311 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2312 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2313 ** forces an automatic rollback of the changes.  See the
2314 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2315 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2316 ** this is important.
2317 **
2318 ** ^(There can only be a single busy handler defined for each
2319 ** [database connection].  Setting a new busy handler clears any
2320 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2321 ** will also set or clear the busy handler.
2322 **
2323 ** The busy callback should not take any actions which modify the
2324 ** database connection that invoked the busy handler.  Any such actions
2325 ** result in undefined behavior.
2326 ** 
2327 ** A busy handler must not close the database connection
2328 ** or [prepared statement] that invoked the busy handler.
2329 */
2330 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2331
2332 /*
2333 ** CAPI3REF: Set A Busy Timeout
2334 **
2335 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2336 ** for a specified amount of time when a table is locked.  ^The handler
2337 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2338 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2339 ** the handler returns 0 which causes [sqlite3_step()] to return
2340 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2341 **
2342 ** ^Calling this routine with an argument less than or equal to zero
2343 ** turns off all busy handlers.
2344 **
2345 ** ^(There can only be a single busy handler for a particular
2346 ** [database connection] any any given moment.  If another busy handler
2347 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2348 ** this routine, that other busy handler is cleared.)^
2349 */
2350 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2351
2352 /*
2353 ** CAPI3REF: Convenience Routines For Running Queries
2354 **
2355 ** This is a legacy interface that is preserved for backwards compatibility.
2356 ** Use of this interface is not recommended.
2357 **
2358 ** Definition: A <b>result table</b> is memory data structure created by the
2359 ** [sqlite3_get_table()] interface.  A result table records the
2360 ** complete query results from one or more queries.
2361 **
2362 ** The table conceptually has a number of rows and columns.  But
2363 ** these numbers are not part of the result table itself.  These
2364 ** numbers are obtained separately.  Let N be the number of rows
2365 ** and M be the number of columns.
2366 **
2367 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2368 ** There are (N+1)*M elements in the array.  The first M pointers point
2369 ** to zero-terminated strings that  contain the names of the columns.
2370 ** The remaining entries all point to query results.  NULL values result
2371 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2372 ** string representation as returned by [sqlite3_column_text()].
2373 **
2374 ** A result table might consist of one or more memory allocations.
2375 ** It is not safe to pass a result table directly to [sqlite3_free()].
2376 ** A result table should be deallocated using [sqlite3_free_table()].
2377 **
2378 ** ^(As an example of the result table format, suppose a query result
2379 ** is as follows:
2380 **
2381 ** <blockquote><pre>
2382 **        Name        | Age
2383 **        -----------------------
2384 **        Alice       | 43
2385 **        Bob         | 28
2386 **        Cindy       | 21
2387 ** </pre></blockquote>
2388 **
2389 ** There are two column (M==2) and three rows (N==3).  Thus the
2390 ** result table has 8 entries.  Suppose the result table is stored
2391 ** in an array names azResult.  Then azResult holds this content:
2392 **
2393 ** <blockquote><pre>
2394 **        azResult&#91;0] = "Name";
2395 **        azResult&#91;1] = "Age";
2396 **        azResult&#91;2] = "Alice";
2397 **        azResult&#91;3] = "43";
2398 **        azResult&#91;4] = "Bob";
2399 **        azResult&#91;5] = "28";
2400 **        azResult&#91;6] = "Cindy";
2401 **        azResult&#91;7] = "21";
2402 ** </pre></blockquote>)^
2403 **
2404 ** ^The sqlite3_get_table() function evaluates one or more
2405 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2406 ** string of its 2nd parameter and returns a result table to the
2407 ** pointer given in its 3rd parameter.
2408 **
2409 ** After the application has finished with the result from sqlite3_get_table(),
2410 ** it must pass the result table pointer to sqlite3_free_table() in order to
2411 ** release the memory that was malloced.  Because of the way the
2412 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2413 ** function must not try to call [sqlite3_free()] directly.  Only
2414 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2415 **
2416 ** The sqlite3_get_table() interface is implemented as a wrapper around
2417 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2418 ** to any internal data structures of SQLite.  It uses only the public
2419 ** interface defined here.  As a consequence, errors that occur in the
2420 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2421 ** reflected in subsequent calls to [sqlite3_errcode()] or
2422 ** [sqlite3_errmsg()].
2423 */
2424 SQLITE_API int sqlite3_get_table(
2425   sqlite3 *db,          /* An open database */
2426   const char *zSql,     /* SQL to be evaluated */
2427   char ***pazResult,    /* Results of the query */
2428   int *pnRow,           /* Number of result rows written here */
2429   int *pnColumn,        /* Number of result columns written here */
2430   char **pzErrmsg       /* Error msg written here */
2431 );
2432 SQLITE_API void sqlite3_free_table(char **result);
2433
2434 /*
2435 ** CAPI3REF: Formatted String Printing Functions
2436 **
2437 ** These routines are work-alikes of the "printf()" family of functions
2438 ** from the standard C library.
2439 **
2440 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2441 ** results into memory obtained from [sqlite3_malloc()].
2442 ** The strings returned by these two routines should be
2443 ** released by [sqlite3_free()].  ^Both routines return a
2444 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2445 ** memory to hold the resulting string.
2446 **
2447 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2448 ** the standard C library.  The result is written into the
2449 ** buffer supplied as the second parameter whose size is given by
2450 ** the first parameter. Note that the order of the
2451 ** first two parameters is reversed from snprintf().)^  This is an
2452 ** historical accident that cannot be fixed without breaking
2453 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2454 ** returns a pointer to its buffer instead of the number of
2455 ** characters actually written into the buffer.)^  We admit that
2456 ** the number of characters written would be a more useful return
2457 ** value but we cannot change the implementation of sqlite3_snprintf()
2458 ** now without breaking compatibility.
2459 **
2460 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2461 ** guarantees that the buffer is always zero-terminated.  ^The first
2462 ** parameter "n" is the total size of the buffer, including space for
2463 ** the zero terminator.  So the longest string that can be completely
2464 ** written will be n-1 characters.
2465 **
2466 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2467 **
2468 ** These routines all implement some additional formatting
2469 ** options that are useful for constructing SQL statements.
2470 ** All of the usual printf() formatting options apply.  In addition, there
2471 ** is are "%q", "%Q", and "%z" options.
2472 **
2473 ** ^(The %q option works like %s in that it substitutes a null-terminated
2474 ** string from the argument list.  But %q also doubles every '\'' character.
2475 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2476 ** character it escapes that character and allows it to be inserted into
2477 ** the string.
2478 **
2479 ** For example, assume the string variable zText contains text as follows:
2480 **
2481 ** <blockquote><pre>
2482 **  char *zText = "It's a happy day!";
2483 ** </pre></blockquote>
2484 **
2485 ** One can use this text in an SQL statement as follows:
2486 **
2487 ** <blockquote><pre>
2488 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2489 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2490 **  sqlite3_free(zSQL);
2491 ** </pre></blockquote>
2492 **
2493 ** Because the %q format string is used, the '\'' character in zText
2494 ** is escaped and the SQL generated is as follows:
2495 **
2496 ** <blockquote><pre>
2497 **  INSERT INTO table1 VALUES('It''s a happy day!')
2498 ** </pre></blockquote>
2499 **
2500 ** This is correct.  Had we used %s instead of %q, the generated SQL
2501 ** would have looked like this:
2502 **
2503 ** <blockquote><pre>
2504 **  INSERT INTO table1 VALUES('It's a happy day!');
2505 ** </pre></blockquote>
2506 **
2507 ** This second example is an SQL syntax error.  As a general rule you should
2508 ** always use %q instead of %s when inserting text into a string literal.
2509 **
2510 ** ^(The %Q option works like %q except it also adds single quotes around
2511 ** the outside of the total string.  Additionally, if the parameter in the
2512 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2513 ** single quotes).)^  So, for example, one could say:
2514 **
2515 ** <blockquote><pre>
2516 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2517 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2518 **  sqlite3_free(zSQL);
2519 ** </pre></blockquote>
2520 **
2521 ** The code above will render a correct SQL statement in the zSQL
2522 ** variable even if the zText variable is a NULL pointer.
2523 **
2524 ** ^(The "%z" formatting option works like "%s" but with the
2525 ** addition that after the string has been read and copied into
2526 ** the result, [sqlite3_free()] is called on the input string.)^
2527 */
2528 SQLITE_API char *sqlite3_mprintf(const char*,...);
2529 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2530 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2531 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2532
2533 /*
2534 ** CAPI3REF: Memory Allocation Subsystem
2535 **
2536 ** The SQLite core uses these three routines for all of its own
2537 ** internal memory allocation needs. "Core" in the previous sentence
2538 ** does not include operating-system specific VFS implementation.  The
2539 ** Windows VFS uses native malloc() and free() for some operations.
2540 **
2541 ** ^The sqlite3_malloc() routine returns a pointer to a block
2542 ** of memory at least N bytes in length, where N is the parameter.
2543 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2544 ** memory, it returns a NULL pointer.  ^If the parameter N to
2545 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2546 ** a NULL pointer.
2547 **
2548 ** ^Calling sqlite3_free() with a pointer previously returned
2549 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2550 ** that it might be reused.  ^The sqlite3_free() routine is
2551 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2552 ** to sqlite3_free() is harmless.  After being freed, memory
2553 ** should neither be read nor written.  Even reading previously freed
2554 ** memory might result in a segmentation fault or other severe error.
2555 ** Memory corruption, a segmentation fault, or other severe error
2556 ** might result if sqlite3_free() is called with a non-NULL pointer that
2557 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2558 **
2559 ** ^(The sqlite3_realloc() interface attempts to resize a
2560 ** prior memory allocation to be at least N bytes, where N is the
2561 ** second parameter.  The memory allocation to be resized is the first
2562 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2563 ** is a NULL pointer then its behavior is identical to calling
2564 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2565 ** ^If the second parameter to sqlite3_realloc() is zero or
2566 ** negative then the behavior is exactly the same as calling
2567 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2568 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2569 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2570 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2571 ** of the prior allocation are copied into the beginning of buffer returned
2572 ** by sqlite3_realloc() and the prior allocation is freed.
2573 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2574 ** is not freed.
2575 **
2576 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2577 ** is always aligned to at least an 8 byte boundary, or to a
2578 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2579 ** option is used.
2580 **
2581 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2582 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2583 ** implementation of these routines to be omitted.  That capability
2584 ** is no longer provided.  Only built-in memory allocators can be used.
2585 **
2586 ** The Windows OS interface layer calls
2587 ** the system malloc() and free() directly when converting
2588 ** filenames between the UTF-8 encoding used by SQLite
2589 ** and whatever filename encoding is used by the particular Windows
2590 ** installation.  Memory allocation errors are detected, but
2591 ** they are reported back as [SQLITE_CANTOPEN] or
2592 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2593 **
2594 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2595 ** must be either NULL or else pointers obtained from a prior
2596 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2597 ** not yet been released.
2598 **
2599 ** The application must not read or write any part of
2600 ** a block of memory after it has been released using
2601 ** [sqlite3_free()] or [sqlite3_realloc()].
2602 */
2603 SQLITE_API void *sqlite3_malloc(int);
2604 SQLITE_API void *sqlite3_realloc(void*, int);
2605 SQLITE_API void sqlite3_free(void*);
2606
2607 /*
2608 ** CAPI3REF: Memory Allocator Statistics
2609 **
2610 ** SQLite provides these two interfaces for reporting on the status
2611 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2612 ** routines, which form the built-in memory allocation subsystem.
2613 **
2614 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2615 ** of memory currently outstanding (malloced but not freed).
2616 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2617 ** value of [sqlite3_memory_used()] since the high-water mark
2618 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2619 ** [sqlite3_memory_highwater()] include any overhead
2620 ** added by SQLite in its implementation of [sqlite3_malloc()],
2621 ** but not overhead added by the any underlying system library
2622 ** routines that [sqlite3_malloc()] may call.
2623 **
2624 ** ^The memory high-water mark is reset to the current value of
2625 ** [sqlite3_memory_used()] if and only if the parameter to
2626 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2627 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2628 ** prior to the reset.
2629 */
2630 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2631 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2632
2633 /*
2634 ** CAPI3REF: Pseudo-Random Number Generator
2635 **
2636 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2637 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2638 ** already uses the largest possible [ROWID].  The PRNG is also used for
2639 ** the build-in random() and randomblob() SQL functions.  This interface allows
2640 ** applications to access the same PRNG for other purposes.
2641 **
2642 ** ^A call to this routine stores N bytes of randomness into buffer P.
2643 **
2644 ** ^The first time this routine is invoked (either internally or by
2645 ** the application) the PRNG is seeded using randomness obtained
2646 ** from the xRandomness method of the default [sqlite3_vfs] object.
2647 ** ^On all subsequent invocations, the pseudo-randomness is generated
2648 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2649 ** method.
2650 */
2651 SQLITE_API void sqlite3_randomness(int N, void *P);
2652
2653 /*
2654 ** CAPI3REF: Compile-Time Authorization Callbacks
2655 **
2656 ** ^This routine registers an authorizer callback with a particular
2657 ** [database connection], supplied in the first argument.
2658 ** ^The authorizer callback is invoked as SQL statements are being compiled
2659 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2660 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2661 ** points during the compilation process, as logic is being created
2662 ** to perform various actions, the authorizer callback is invoked to
2663 ** see if those actions are allowed.  ^The authorizer callback should
2664 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2665 ** specific action but allow the SQL statement to continue to be
2666 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2667 ** rejected with an error.  ^If the authorizer callback returns
2668 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2669 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2670 ** the authorizer will fail with an error message.
2671 **
2672 ** When the callback returns [SQLITE_OK], that means the operation
2673 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2674 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2675 ** authorizer will fail with an error message explaining that
2676 ** access is denied. 
2677 **
2678 ** ^The first parameter to the authorizer callback is a copy of the third
2679 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2680 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2681 ** the particular action to be authorized. ^The third through sixth parameters
2682 ** to the callback are zero-terminated strings that contain additional
2683 ** details about the action to be authorized.
2684 **
2685 ** ^If the action code is [SQLITE_READ]
2686 ** and the callback returns [SQLITE_IGNORE] then the
2687 ** [prepared statement] statement is constructed to substitute
2688 ** a NULL value in place of the table column that would have
2689 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2690 ** return can be used to deny an untrusted user access to individual
2691 ** columns of a table.
2692 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2693 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2694 ** [truncate optimization] is disabled and all rows are deleted individually.
2695 **
2696 ** An authorizer is used when [sqlite3_prepare | preparing]
2697 ** SQL statements from an untrusted source, to ensure that the SQL statements
2698 ** do not try to access data they are not allowed to see, or that they do not
2699 ** try to execute malicious statements that damage the database.  For
2700 ** example, an application may allow a user to enter arbitrary
2701 ** SQL queries for evaluation by a database.  But the application does
2702 ** not want the user to be able to make arbitrary changes to the
2703 ** database.  An authorizer could then be put in place while the
2704 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2705 ** disallows everything except [SELECT] statements.
2706 **
2707 ** Applications that need to process SQL from untrusted sources
2708 ** might also consider lowering resource limits using [sqlite3_limit()]
2709 ** and limiting database size using the [max_page_count] [PRAGMA]
2710 ** in addition to using an authorizer.
2711 **
2712 ** ^(Only a single authorizer can be in place on a database connection
2713 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2714 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2715 ** The authorizer is disabled by default.
2716 **
2717 ** The authorizer callback must not do anything that will modify
2718 ** the database connection that invoked the authorizer callback.
2719 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2720 ** database connections for the meaning of "modify" in this paragraph.
2721 **
2722 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2723 ** statement might be re-prepared during [sqlite3_step()] due to a 
2724 ** schema change.  Hence, the application should ensure that the
2725 ** correct authorizer callback remains in place during the [sqlite3_step()].
2726 **
2727 ** ^Note that the authorizer callback is invoked only during
2728 ** [sqlite3_prepare()] or its variants.  Authorization is not
2729 ** performed during statement evaluation in [sqlite3_step()], unless
2730 ** as stated in the previous paragraph, sqlite3_step() invokes
2731 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2732 */
2733 SQLITE_API int sqlite3_set_authorizer(
2734   sqlite3*,
2735   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2736   void *pUserData
2737 );
2738
2739 /*
2740 ** CAPI3REF: Authorizer Return Codes
2741 **
2742 ** The [sqlite3_set_authorizer | authorizer callback function] must
2743 ** return either [SQLITE_OK] or one of these two constants in order
2744 ** to signal SQLite whether or not the action is permitted.  See the
2745 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2746 ** information.
2747 */
2748 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2749 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2750
2751 /*
2752 ** CAPI3REF: Authorizer Action Codes
2753 **
2754 ** The [sqlite3_set_authorizer()] interface registers a callback function
2755 ** that is invoked to authorize certain SQL statement actions.  The
2756 ** second parameter to the callback is an integer code that specifies
2757 ** what action is being authorized.  These are the integer action codes that
2758 ** the authorizer callback may be passed.
2759 **
2760 ** These action code values signify what kind of operation is to be
2761 ** authorized.  The 3rd and 4th parameters to the authorization
2762 ** callback function will be parameters or NULL depending on which of these
2763 ** codes is used as the second parameter.  ^(The 5th parameter to the
2764 ** authorizer callback is the name of the database ("main", "temp",
2765 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2766 ** is the name of the inner-most trigger or view that is responsible for
2767 ** the access attempt or NULL if this access attempt is directly from
2768 ** top-level SQL code.
2769 */
2770 /******************************************* 3rd ************ 4th ***********/
2771 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2772 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2773 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2774 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2775 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2776 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2777 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2778 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2779 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2780 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2781 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2782 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2783 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2784 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2785 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2786 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2787 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2788 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2789 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2790 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2791 #define SQLITE_SELECT               21   /* NULL            NULL            */
2792 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2793 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2794 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2795 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2796 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2797 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2798 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2799 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2800 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2801 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2802 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2803 #define SQLITE_COPY                  0   /* No longer used */
2804
2805 /*
2806 ** CAPI3REF: Tracing And Profiling Functions
2807 **
2808 ** These routines register callback functions that can be used for
2809 ** tracing and profiling the execution of SQL statements.
2810 **
2811 ** ^The callback function registered by sqlite3_trace() is invoked at
2812 ** various times when an SQL statement is being run by [sqlite3_step()].
2813 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2814 ** SQL statement text as the statement first begins executing.
2815 ** ^(Additional sqlite3_trace() callbacks might occur
2816 ** as each triggered subprogram is entered.  The callbacks for triggers
2817 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2818 **
2819 ** ^The callback function registered by sqlite3_profile() is invoked
2820 ** as each SQL statement finishes.  ^The profile callback contains
2821 ** the original statement text and an estimate of wall-clock time
2822 ** of how long that statement took to run.  ^The profile callback
2823 ** time is in units of nanoseconds, however the current implementation
2824 ** is only capable of millisecond resolution so the six least significant
2825 ** digits in the time are meaningless.  Future versions of SQLite
2826 ** might provide greater resolution on the profiler callback.  The
2827 ** sqlite3_profile() function is considered experimental and is
2828 ** subject to change in future versions of SQLite.
2829 */
2830 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2831 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2832    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2833
2834 /*
2835 ** CAPI3REF: Query Progress Callbacks
2836 **
2837 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2838 ** function X to be invoked periodically during long running calls to
2839 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2840 ** database connection D.  An example use for this
2841 ** interface is to keep a GUI updated during a large query.
2842 **
2843 ** ^The parameter P is passed through as the only parameter to the 
2844 ** callback function X.  ^The parameter N is the number of 
2845 ** [virtual machine instructions] that are evaluated between successive
2846 ** invocations of the callback X.
2847 **
2848 ** ^Only a single progress handler may be defined at one time per
2849 ** [database connection]; setting a new progress handler cancels the
2850 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2851 ** ^The progress handler is also disabled by setting N to a value less
2852 ** than 1.
2853 **
2854 ** ^If the progress callback returns non-zero, the operation is
2855 ** interrupted.  This feature can be used to implement a
2856 ** "Cancel" button on a GUI progress dialog box.
2857 **
2858 ** The progress handler callback must not do anything that will modify
2859 ** the database connection that invoked the progress handler.
2860 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2861 ** database connections for the meaning of "modify" in this paragraph.
2862 **
2863 */
2864 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2865
2866 /*
2867 ** CAPI3REF: Opening A New Database Connection
2868 **
2869 ** ^These routines open an SQLite database file whose name is given by the
2870 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2871 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2872 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2873 ** returned in *ppDb, even if an error occurs.  The only exception is that
2874 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2875 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2876 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2877 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2878 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2879 ** an English language description of the error following a failure of any
2880 ** of the sqlite3_open() routines.
2881 **
2882 ** ^The default encoding for the database will be UTF-8 if
2883 ** sqlite3_open() or sqlite3_open_v2() is called and
2884 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2885 **
2886 ** Whether or not an error occurs when it is opened, resources
2887 ** associated with the [database connection] handle should be released by
2888 ** passing it to [sqlite3_close()] when it is no longer required.
2889 **
2890 ** The sqlite3_open_v2() interface works like sqlite3_open()
2891 ** except that it accepts two additional parameters for additional control
2892 ** over the new database connection.  ^(The flags parameter to
2893 ** sqlite3_open_v2() can take one of
2894 ** the following three values, optionally combined with the 
2895 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2896 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2897 **
2898 ** <dl>
2899 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2900 ** <dd>The database is opened in read-only mode.  If the database does not
2901 ** already exist, an error is returned.</dd>)^
2902 **
2903 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2904 ** <dd>The database is opened for reading and writing if possible, or reading
2905 ** only if the file is write protected by the operating system.  In either
2906 ** case the database must already exist, otherwise an error is returned.</dd>)^
2907 **
2908 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2909 ** <dd>The database is opened for reading and writing, and is created if
2910 ** it does not already exist. This is the behavior that is always used for
2911 ** sqlite3_open() and sqlite3_open16().</dd>)^
2912 ** </dl>
2913 **
2914 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2915 ** combinations shown above or one of the combinations shown above combined
2916 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2917 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2918 ** then the behavior is undefined.
2919 **
2920 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2921 ** opens in the multi-thread [threading mode] as long as the single-thread
2922 ** mode has not been set at compile-time or start-time.  ^If the
2923 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2924 ** in the serialized [threading mode] unless single-thread was
2925 ** previously selected at compile-time or start-time.
2926 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2927 ** eligible to use [shared cache mode], regardless of whether or not shared
2928 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2929 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2930 ** participate in [shared cache mode] even if it is enabled.
2931 **
2932 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2933 ** is created for the connection.  ^This in-memory database will vanish when
2934 ** the database connection is closed.  Future versions of SQLite might
2935 ** make use of additional special filenames that begin with the ":" character.
2936 ** It is recommended that when a database filename actually does begin with
2937 ** a ":" character you should prefix the filename with a pathname such as
2938 ** "./" to avoid ambiguity.
2939 **
2940 ** ^If the filename is an empty string, then a private, temporary
2941 ** on-disk database will be created.  ^This private database will be
2942 ** automatically deleted as soon as the database connection is closed.
2943 **
2944 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2945 ** [sqlite3_vfs] object that defines the operating system interface that
2946 ** the new database connection should use.  ^If the fourth parameter is
2947 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2948 **
2949 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2950 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2951 ** codepage is currently defined.  Filenames containing international
2952 ** characters must be converted to UTF-8 prior to passing them into
2953 ** sqlite3_open() or sqlite3_open_v2().
2954 */
2955 SQLITE_API int sqlite3_open(
2956   const char *filename,   /* Database filename (UTF-8) */
2957   sqlite3 **ppDb          /* OUT: SQLite db handle */
2958 );
2959 SQLITE_API int sqlite3_open16(
2960   const void *filename,   /* Database filename (UTF-16) */
2961   sqlite3 **ppDb          /* OUT: SQLite db handle */
2962 );
2963 SQLITE_API int sqlite3_open_v2(
2964   const char *filename,   /* Database filename (UTF-8) */
2965   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2966   int flags,              /* Flags */
2967   const char *zVfs        /* Name of VFS module to use */
2968 );
2969
2970 /*
2971 ** CAPI3REF: Error Codes And Messages
2972 **
2973 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2974 ** [extended result code] for the most recent failed sqlite3_* API call
2975 ** associated with a [database connection]. If a prior API call failed
2976 ** but the most recent API call succeeded, the return value from
2977 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2978 ** interface is the same except that it always returns the 
2979 ** [extended result code] even when extended result codes are
2980 ** disabled.
2981 **
2982 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2983 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2984 ** ^(Memory to hold the error message string is managed internally.
2985 ** The application does not need to worry about freeing the result.
2986 ** However, the error string might be overwritten or deallocated by
2987 ** subsequent calls to other SQLite interface functions.)^
2988 **
2989 ** When the serialized [threading mode] is in use, it might be the
2990 ** case that a second error occurs on a separate thread in between
2991 ** the time of the first error and the call to these interfaces.
2992 ** When that happens, the second error will be reported since these
2993 ** interfaces always report the most recent result.  To avoid
2994 ** this, each thread can obtain exclusive use of the [database connection] D
2995 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2996 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2997 ** all calls to the interfaces listed here are completed.
2998 **
2999 ** If an interface fails with SQLITE_MISUSE, that means the interface
3000 ** was invoked incorrectly by the application.  In that case, the
3001 ** error code and message may or may not be set.
3002 */
3003 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3004 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3005 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3006 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3007
3008 /*
3009 ** CAPI3REF: SQL Statement Object
3010 ** KEYWORDS: {prepared statement} {prepared statements}
3011 **
3012 ** An instance of this object represents a single SQL statement.
3013 ** This object is variously known as a "prepared statement" or a
3014 ** "compiled SQL statement" or simply as a "statement".
3015 **
3016 ** The life of a statement object goes something like this:
3017 **
3018 ** <ol>
3019 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3020 **      function.
3021 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3022 **      interfaces.
3023 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3024 ** <li> Reset the statement using [sqlite3_reset()] then go back
3025 **      to step 2.  Do this zero or more times.
3026 ** <li> Destroy the object using [sqlite3_finalize()].
3027 ** </ol>
3028 **
3029 ** Refer to documentation on individual methods above for additional
3030 ** information.
3031 */
3032 typedef struct sqlite3_stmt sqlite3_stmt;
3033
3034 /*
3035 ** CAPI3REF: Run-time Limits
3036 **
3037 ** ^(This interface allows the size of various constructs to be limited
3038 ** on a connection by connection basis.  The first parameter is the
3039 ** [database connection] whose limit is to be set or queried.  The
3040 ** second parameter is one of the [limit categories] that define a
3041 ** class of constructs to be size limited.  The third parameter is the
3042 ** new limit for that construct.)^
3043 **
3044 ** ^If the new limit is a negative number, the limit is unchanged.
3045 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3046 ** [limits | hard upper bound]
3047 ** set at compile-time by a C preprocessor macro called
3048 ** [limits | SQLITE_MAX_<i>NAME</i>].
3049 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3050 ** ^Attempts to increase a limit above its hard upper bound are
3051 ** silently truncated to the hard upper bound.
3052 **
3053 ** ^Regardless of whether or not the limit was changed, the 
3054 ** [sqlite3_limit()] interface returns the prior value of the limit.
3055 ** ^Hence, to find the current value of a limit without changing it,
3056 ** simply invoke this interface with the third parameter set to -1.
3057 **
3058 ** Run-time limits are intended for use in applications that manage
3059 ** both their own internal database and also databases that are controlled
3060 ** by untrusted external sources.  An example application might be a
3061 ** web browser that has its own databases for storing history and
3062 ** separate databases controlled by JavaScript applications downloaded
3063 ** off the Internet.  The internal databases can be given the
3064 ** large, default limits.  Databases managed by external sources can
3065 ** be given much smaller limits designed to prevent a denial of service
3066 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3067 ** interface to further control untrusted SQL.  The size of the database
3068 ** created by an untrusted script can be contained using the
3069 ** [max_page_count] [PRAGMA].
3070 **
3071 ** New run-time limit categories may be added in future releases.
3072 */
3073 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3074
3075 /*
3076 ** CAPI3REF: Run-Time Limit Categories
3077 ** KEYWORDS: {limit category} {*limit categories}
3078 **
3079 ** These constants define various performance limits
3080 ** that can be lowered at run-time using [sqlite3_limit()].
3081 ** The synopsis of the meanings of the various limits is shown below.
3082 ** Additional information is available at [limits | Limits in SQLite].
3083 **
3084 ** <dl>
3085 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3086 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3087 **
3088 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3089 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3090 **
3091 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3092 ** <dd>The maximum number of columns in a table definition or in the
3093 ** result set of a [SELECT] or the maximum number of columns in an index
3094 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3095 **
3096 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3097 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3098 **
3099 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3100 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3101 **
3102 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3103 ** <dd>The maximum number of instructions in a virtual machine program
3104 ** used to implement an SQL statement.  This limit is not currently
3105 ** enforced, though that might be added in some future release of
3106 ** SQLite.</dd>)^
3107 **
3108 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3109 ** <dd>The maximum number of arguments on a function.</dd>)^
3110 **
3111 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3112 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3113 **
3114 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3115 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3116 ** [GLOB] operators.</dd>)^
3117 **
3118 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3119 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3120 **
3121 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3122 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3123 ** </dl>
3124 */
3125 #define SQLITE_LIMIT_LENGTH                    0
3126 #define SQLITE_LIMIT_SQL_LENGTH                1
3127 #define SQLITE_LIMIT_COLUMN                    2
3128 #define SQLITE_LIMIT_EXPR_DEPTH                3
3129 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3130 #define SQLITE_LIMIT_VDBE_OP                   5
3131 #define SQLITE_LIMIT_FUNCTION_ARG              6
3132 #define SQLITE_LIMIT_ATTACHED                  7
3133 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3134 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3135 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3136
3137 /*
3138 ** CAPI3REF: Compiling An SQL Statement
3139 ** KEYWORDS: {SQL statement compiler}
3140 **
3141 ** To execute an SQL query, it must first be compiled into a byte-code
3142 ** program using one of these routines.
3143 **
3144 ** The first argument, "db", is a [database connection] obtained from a
3145 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3146 ** [sqlite3_open16()].  The database connection must not have been closed.
3147 **
3148 ** The second argument, "zSql", is the statement to be compiled, encoded
3149 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3150 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3151 ** use UTF-16.
3152 **
3153 ** ^If the nByte argument is less than zero, then zSql is read up to the
3154 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3155 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3156 ** zSql string ends at either the first '\000' or '\u0000' character or
3157 ** the nByte-th byte, whichever comes first. If the caller knows
3158 ** that the supplied string is nul-terminated, then there is a small
3159 ** performance advantage to be gained by passing an nByte parameter that
3160 ** is equal to the number of bytes in the input string <i>including</i>
3161 ** the nul-terminator bytes.
3162 **
3163 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3164 ** past the end of the first SQL statement in zSql.  These routines only
3165 ** compile the first statement in zSql, so *pzTail is left pointing to
3166 ** what remains uncompiled.
3167 **
3168 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3169 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3170 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3171 ** string or a comment) then *ppStmt is set to NULL.
3172 ** The calling procedure is responsible for deleting the compiled
3173 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3174 ** ppStmt may not be NULL.
3175 **
3176 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3177 ** otherwise an [error code] is returned.
3178 **
3179 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3180 ** recommended for all new programs. The two older interfaces are retained
3181 ** for backwards compatibility, but their use is discouraged.
3182 ** ^In the "v2" interfaces, the prepared statement
3183 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3184 ** original SQL text. This causes the [sqlite3_step()] interface to
3185 ** behave differently in three ways:
3186 **
3187 ** <ol>
3188 ** <li>
3189 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3190 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3191 ** statement and try to run it again.
3192 ** </li>
3193 **
3194 ** <li>
3195 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3196 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3197 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3198 ** and the application would have to make a second call to [sqlite3_reset()]
3199 ** in order to find the underlying cause of the problem. With the "v2" prepare
3200 ** interfaces, the underlying reason for the error is returned immediately.
3201 ** </li>
3202 **
3203 ** <li>
3204 ** ^If the specific value bound to [parameter | host parameter] in the 
3205 ** WHERE clause might influence the choice of query plan for a statement,
3206 ** then the statement will be automatically recompiled, as if there had been 
3207 ** a schema change, on the first  [sqlite3_step()] call following any change
3208 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3209 ** ^The specific value of WHERE-clause [parameter] might influence the 
3210 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3211 ** or [GLOB] operator or if the parameter is compared to an indexed column
3212 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3213 ** the 
3214 ** </li>
3215 ** </ol>
3216 */
3217 SQLITE_API int sqlite3_prepare(
3218   sqlite3 *db,            /* Database handle */
3219   const char *zSql,       /* SQL statement, UTF-8 encoded */
3220   int nByte,              /* Maximum length of zSql in bytes. */
3221   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3222   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3223 );
3224 SQLITE_API int sqlite3_prepare_v2(
3225   sqlite3 *db,            /* Database handle */
3226   const char *zSql,       /* SQL statement, UTF-8 encoded */
3227   int nByte,              /* Maximum length of zSql in bytes. */
3228   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3229   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3230 );
3231 SQLITE_API int sqlite3_prepare16(
3232   sqlite3 *db,            /* Database handle */
3233   const void *zSql,       /* SQL statement, UTF-16 encoded */
3234   int nByte,              /* Maximum length of zSql in bytes. */
3235   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3236   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3237 );
3238 SQLITE_API int sqlite3_prepare16_v2(
3239   sqlite3 *db,            /* Database handle */
3240   const void *zSql,       /* SQL statement, UTF-16 encoded */
3241   int nByte,              /* Maximum length of zSql in bytes. */
3242   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3243   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3244 );
3245
3246 /*
3247 ** CAPI3REF: Retrieving Statement SQL
3248 **
3249 ** ^This interface can be used to retrieve a saved copy of the original
3250 ** SQL text used to create a [prepared statement] if that statement was
3251 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3252 */
3253 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3254
3255 /*
3256 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3257 **
3258 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3259 ** and only if the [prepared statement] X makes no direct changes to
3260 ** the content of the database file.
3261 **
3262 ** Note that [application-defined SQL functions] or
3263 ** [virtual tables] might change the database indirectly as a side effect.  
3264 ** ^(For example, if an application defines a function "eval()" that 
3265 ** calls [sqlite3_exec()], then the following SQL statement would
3266 ** change the database file through side-effects:
3267 **
3268 ** <blockquote><pre>
3269 **    SELECT eval('DELETE FROM t1') FROM t2;
3270 ** </pre></blockquote>
3271 **
3272 ** But because the [SELECT] statement does not change the database file
3273 ** directly, sqlite3_stmt_readonly() would still return true.)^
3274 **
3275 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3276 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3277 ** since the statements themselves do not actually modify the database but
3278 ** rather they control the timing of when other statements modify the 
3279 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3280 ** sqlite3_stmt_readonly() to return true since, while those statements
3281 ** change the configuration of a database connection, they do not make 
3282 ** changes to the content of the database files on disk.
3283 */
3284 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3285
3286 /*
3287 ** CAPI3REF: Dynamically Typed Value Object
3288 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3289 **
3290 ** SQLite uses the sqlite3_value object to represent all values
3291 ** that can be stored in a database table. SQLite uses dynamic typing
3292 ** for the values it stores.  ^Values stored in sqlite3_value objects
3293 ** can be integers, floating point values, strings, BLOBs, or NULL.
3294 **
3295 ** An sqlite3_value object may be either "protected" or "unprotected".
3296 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3297 ** will accept either a protected or an unprotected sqlite3_value.
3298 ** Every interface that accepts sqlite3_value arguments specifies
3299 ** whether or not it requires a protected sqlite3_value.
3300 **
3301 ** The terms "protected" and "unprotected" refer to whether or not
3302 ** a mutex is held.  An internal mutex is held for a protected
3303 ** sqlite3_value object but no mutex is held for an unprotected
3304 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3305 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3306 ** or if SQLite is run in one of reduced mutex modes 
3307 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3308 ** then there is no distinction between protected and unprotected
3309 ** sqlite3_value objects and they can be used interchangeably.  However,
3310 ** for maximum code portability it is recommended that applications
3311 ** still make the distinction between protected and unprotected
3312 ** sqlite3_value objects even when not strictly required.
3313 **
3314 ** ^The sqlite3_value objects that are passed as parameters into the
3315 ** implementation of [application-defined SQL functions] are protected.
3316 ** ^The sqlite3_value object returned by
3317 ** [sqlite3_column_value()] is unprotected.
3318 ** Unprotected sqlite3_value objects may only be used with
3319 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3320 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3321 ** interfaces require protected sqlite3_value objects.
3322 */
3323 typedef struct Mem sqlite3_value;
3324
3325 /*
3326 ** CAPI3REF: SQL Function Context Object
3327 **
3328 ** The context in which an SQL function executes is stored in an
3329 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3330 ** is always first parameter to [application-defined SQL functions].
3331 ** The application-defined SQL function implementation will pass this
3332 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3333 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3334 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3335 ** and/or [sqlite3_set_auxdata()].
3336 */
3337 typedef struct sqlite3_context sqlite3_context;
3338
3339 /*
3340 ** CAPI3REF: Binding Values To Prepared Statements
3341 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3342 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3343 **
3344 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3345 ** literals may be replaced by a [parameter] that matches one of following
3346 ** templates:
3347 **
3348 ** <ul>
3349 ** <li>  ?
3350 ** <li>  ?NNN
3351 ** <li>  :VVV
3352 ** <li>  @VVV
3353 ** <li>  $VVV
3354 ** </ul>
3355 **
3356 ** In the templates above, NNN represents an integer literal,
3357 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3358 ** parameters (also called "host parameter names" or "SQL parameters")
3359 ** can be set using the sqlite3_bind_*() routines defined here.
3360 **
3361 ** ^The first argument to the sqlite3_bind_*() routines is always
3362 ** a pointer to the [sqlite3_stmt] object returned from
3363 ** [sqlite3_prepare_v2()] or its variants.
3364 **
3365 ** ^The second argument is the index of the SQL parameter to be set.
3366 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3367 ** SQL parameter is used more than once, second and subsequent
3368 ** occurrences have the same index as the first occurrence.
3369 ** ^The index for named parameters can be looked up using the
3370 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3371 ** for "?NNN" parameters is the value of NNN.
3372 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3373 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3374 **
3375 ** ^The third argument is the value to bind to the parameter.
3376 **
3377 ** ^(In those routines that have a fourth argument, its value is the
3378 ** number of bytes in the parameter.  To be clear: the value is the
3379 ** number of <u>bytes</u> in the value, not the number of characters.)^
3380 ** ^If the fourth parameter is negative, the length of the string is
3381 ** the number of bytes up to the first zero terminator.
3382 **
3383 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3384 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3385 ** string after SQLite has finished with it.  ^The destructor is called
3386 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3387 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3388 ** ^If the fifth argument is
3389 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3390 ** information is in static, unmanaged space and does not need to be freed.
3391 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3392 ** SQLite makes its own private copy of the data immediately, before
3393 ** the sqlite3_bind_*() routine returns.
3394 **
3395 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3396 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3397 ** (just an integer to hold its size) while it is being processed.
3398 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3399 ** content is later written using
3400 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3401 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3402 **
3403 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3404 ** for the [prepared statement] or with a prepared statement for which
3405 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3406 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3407 ** routine is passed a [prepared statement] that has been finalized, the
3408 ** result is undefined and probably harmful.
3409 **
3410 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3411 ** ^Unbound parameters are interpreted as NULL.
3412 **
3413 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3414 ** [error code] if anything goes wrong.
3415 ** ^[SQLITE_RANGE] is returned if the parameter
3416 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3417 **
3418 ** See also: [sqlite3_bind_parameter_count()],
3419 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3420 */
3421 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3422 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3423 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3424 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3425 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3426 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3427 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3428 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3429 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3430
3431 /*
3432 ** CAPI3REF: Number Of SQL Parameters
3433 **
3434 ** ^This routine can be used to find the number of [SQL parameters]
3435 ** in a [prepared statement].  SQL parameters are tokens of the
3436 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3437 ** placeholders for values that are [sqlite3_bind_blob | bound]
3438 ** to the parameters at a later time.
3439 **
3440 ** ^(This routine actually returns the index of the largest (rightmost)
3441 ** parameter. For all forms except ?NNN, this will correspond to the
3442 ** number of unique parameters.  If parameters of the ?NNN form are used,
3443 ** there may be gaps in the list.)^
3444 **
3445 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3446 ** [sqlite3_bind_parameter_name()], and
3447 ** [sqlite3_bind_parameter_index()].
3448 */
3449 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3450
3451 /*
3452 ** CAPI3REF: Name Of A Host Parameter
3453 **
3454 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3455 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3456 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3457 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3458 ** respectively.
3459 ** In other words, the initial ":" or "$" or "@" or "?"
3460 ** is included as part of the name.)^
3461 ** ^Parameters of the form "?" without a following integer have no name
3462 ** and are referred to as "nameless" or "anonymous parameters".
3463 **
3464 ** ^The first host parameter has an index of 1, not 0.
3465 **
3466 ** ^If the value N is out of range or if the N-th parameter is
3467 ** nameless, then NULL is returned.  ^The returned string is
3468 ** always in UTF-8 encoding even if the named parameter was
3469 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3470 ** [sqlite3_prepare16_v2()].
3471 **
3472 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3473 ** [sqlite3_bind_parameter_count()], and
3474 ** [sqlite3_bind_parameter_index()].
3475 */
3476 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3477
3478 /*
3479 ** CAPI3REF: Index Of A Parameter With A Given Name
3480 **
3481 ** ^Return the index of an SQL parameter given its name.  ^The
3482 ** index value returned is suitable for use as the second
3483 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3484 ** is returned if no matching parameter is found.  ^The parameter
3485 ** name must be given in UTF-8 even if the original statement
3486 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3487 **
3488 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3489 ** [sqlite3_bind_parameter_count()], and
3490 ** [sqlite3_bind_parameter_index()].
3491 */
3492 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3493
3494 /*
3495 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3496 **
3497 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3498 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3499 ** ^Use this routine to reset all host parameters to NULL.
3500 */
3501 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3502
3503 /*
3504 ** CAPI3REF: Number Of Columns In A Result Set
3505 **
3506 ** ^Return the number of columns in the result set returned by the
3507 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3508 ** statement that does not return data (for example an [UPDATE]).
3509 **
3510 ** See also: [sqlite3_data_count()]
3511 */
3512 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3513
3514 /*
3515 ** CAPI3REF: Column Names In A Result Set
3516 **
3517 ** ^These routines return the name assigned to a particular column
3518 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3519 ** interface returns a pointer to a zero-terminated UTF-8 string
3520 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3521 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3522 ** that implements the [SELECT] statement. ^The second parameter is the
3523 ** column number.  ^The leftmost column is number 0.
3524 **
3525 ** ^The returned string pointer is valid until either the [prepared statement]
3526 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3527 ** reprepared by the first call to [sqlite3_step()] for a particular run
3528 ** or until the next call to
3529 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3530 **
3531 ** ^If sqlite3_malloc() fails during the processing of either routine
3532 ** (for example during a conversion from UTF-8 to UTF-16) then a
3533 ** NULL pointer is returned.
3534 **
3535 ** ^The name of a result column is the value of the "AS" clause for
3536 ** that column, if there is an AS clause.  If there is no AS clause
3537 ** then the name of the column is unspecified and may change from
3538 ** one release of SQLite to the next.
3539 */
3540 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3541 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3542
3543 /*
3544 ** CAPI3REF: Source Of Data In A Query Result
3545 **
3546 ** ^These routines provide a means to determine the database, table, and
3547 ** table column that is the origin of a particular result column in
3548 ** [SELECT] statement.
3549 ** ^The name of the database or table or column can be returned as
3550 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3551 ** the database name, the _table_ routines return the table name, and
3552 ** the origin_ routines return the column name.
3553 ** ^The returned string is valid until the [prepared statement] is destroyed
3554 ** using [sqlite3_finalize()] or until the statement is automatically
3555 ** reprepared by the first call to [sqlite3_step()] for a particular run
3556 ** or until the same information is requested
3557 ** again in a different encoding.
3558 **
3559 ** ^The names returned are the original un-aliased names of the
3560 ** database, table, and column.
3561 **
3562 ** ^The first argument to these interfaces is a [prepared statement].
3563 ** ^These functions return information about the Nth result column returned by
3564 ** the statement, where N is the second function argument.
3565 ** ^The left-most column is column 0 for these routines.
3566 **
3567 ** ^If the Nth column returned by the statement is an expression or
3568 ** subquery and is not a column value, then all of these functions return
3569 ** NULL.  ^These routine might also return NULL if a memory allocation error
3570 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3571 ** or column that query result column was extracted from.
3572 **
3573 ** ^As with all other SQLite APIs, those whose names end with "16" return
3574 ** UTF-16 encoded strings and the other functions return UTF-8.
3575 **
3576 ** ^These APIs are only available if the library was compiled with the
3577 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3578 **
3579 ** If two or more threads call one or more of these routines against the same
3580 ** prepared statement and column at the same time then the results are
3581 ** undefined.
3582 **
3583 ** If two or more threads call one or more
3584 ** [sqlite3_column_database_name | column metadata interfaces]
3585 ** for the same [prepared statement] and result column
3586 ** at the same time then the results are undefined.
3587 */
3588 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3589 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3590 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3591 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3592 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3593 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3594
3595 /*
3596 ** CAPI3REF: Declared Datatype Of A Query Result
3597 **
3598 ** ^(The first parameter is a [prepared statement].
3599 ** If this statement is a [SELECT] statement and the Nth column of the
3600 ** returned result set of that [SELECT] is a table column (not an
3601 ** expression or subquery) then the declared type of the table
3602 ** column is returned.)^  ^If the Nth column of the result set is an
3603 ** expression or subquery, then a NULL pointer is returned.
3604 ** ^The returned string is always UTF-8 encoded.
3605 **
3606 ** ^(For example, given the database schema:
3607 **
3608 ** CREATE TABLE t1(c1 VARIANT);
3609 **
3610 ** and the following statement to be compiled:
3611 **
3612 ** SELECT c1 + 1, c1 FROM t1;
3613 **
3614 ** this routine would return the string "VARIANT" for the second result
3615 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3616 **
3617 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3618 ** is declared to contain a particular type does not mean that the
3619 ** data stored in that column is of the declared type.  SQLite is
3620 ** strongly typed, but the typing is dynamic not static.  ^Type
3621 ** is associated with individual values, not with the containers
3622 ** used to hold those values.
3623 */
3624 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3625 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3626
3627 /*
3628 ** CAPI3REF: Evaluate An SQL Statement
3629 **
3630 ** After a [prepared statement] has been prepared using either
3631 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3632 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3633 ** must be called one or more times to evaluate the statement.
3634 **
3635 ** The details of the behavior of the sqlite3_step() interface depend
3636 ** on whether the statement was prepared using the newer "v2" interface
3637 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3638 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3639 ** new "v2" interface is recommended for new applications but the legacy
3640 ** interface will continue to be supported.
3641 **
3642 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3643 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3644 ** ^With the "v2" interface, any of the other [result codes] or
3645 ** [extended result codes] might be returned as well.
3646 **
3647 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3648 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3649 ** or occurs outside of an explicit transaction, then you can retry the
3650 ** statement.  If the statement is not a [COMMIT] and occurs within a
3651 ** explicit transaction then you should rollback the transaction before
3652 ** continuing.
3653 **
3654 ** ^[SQLITE_DONE] means that the statement has finished executing
3655 ** successfully.  sqlite3_step() should not be called again on this virtual
3656 ** machine without first calling [sqlite3_reset()] to reset the virtual
3657 ** machine back to its initial state.
3658 **
3659 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3660 ** is returned each time a new row of data is ready for processing by the
3661 ** caller. The values may be accessed using the [column access functions].
3662 ** sqlite3_step() is called again to retrieve the next row of data.
3663 **
3664 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3665 ** violation) has occurred.  sqlite3_step() should not be called again on
3666 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3667 ** ^With the legacy interface, a more specific error code (for example,
3668 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3669 ** can be obtained by calling [sqlite3_reset()] on the
3670 ** [prepared statement].  ^In the "v2" interface,
3671 ** the more specific error code is returned directly by sqlite3_step().
3672 **
3673 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3674 ** Perhaps it was called on a [prepared statement] that has
3675 ** already been [sqlite3_finalize | finalized] or on one that had
3676 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3677 ** be the case that the same database connection is being used by two or
3678 ** more threads at the same moment in time.
3679 **
3680 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3681 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3682 ** other than [SQLITE_ROW] before any subsequent invocation of
3683 ** sqlite3_step().  Failure to reset the prepared statement using 
3684 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3685 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3686 ** calling [sqlite3_reset()] automatically in this circumstance rather
3687 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3688 ** break because any application that ever receives an SQLITE_MISUSE error
3689 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3690 ** can be used to restore the legacy behavior.
3691 **
3692 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3693 ** API always returns a generic error code, [SQLITE_ERROR], following any
3694 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3695 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3696 ** specific [error codes] that better describes the error.
3697 ** We admit that this is a goofy design.  The problem has been fixed
3698 ** with the "v2" interface.  If you prepare all of your SQL statements
3699 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3700 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3701 ** then the more specific [error codes] are returned directly
3702 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3703 */
3704 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3705
3706 /*
3707 ** CAPI3REF: Number of columns in a result set
3708 **
3709 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3710 ** current row of the result set of [prepared statement] P.
3711 ** ^If prepared statement P does not have results ready to return
3712 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3713 ** interfaces) then sqlite3_data_count(P) returns 0.
3714 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3715 **
3716 ** See also: [sqlite3_column_count()]
3717 */
3718 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3719
3720 /*
3721 ** CAPI3REF: Fundamental Datatypes
3722 ** KEYWORDS: SQLITE_TEXT
3723 **
3724 ** ^(Every value in SQLite has one of five fundamental datatypes:
3725 **
3726 ** <ul>
3727 ** <li> 64-bit signed integer
3728 ** <li> 64-bit IEEE floating point number
3729 ** <li> string
3730 ** <li> BLOB
3731 ** <li> NULL
3732 ** </ul>)^
3733 **
3734 ** These constants are codes for each of those types.
3735 **
3736 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3737 ** for a completely different meaning.  Software that links against both
3738 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3739 ** SQLITE_TEXT.
3740 */
3741 #define SQLITE_INTEGER  1
3742 #define SQLITE_FLOAT    2
3743 #define SQLITE_BLOB     4
3744 #define SQLITE_NULL     5
3745 #ifdef SQLITE_TEXT
3746 # undef SQLITE_TEXT
3747 #else
3748 # define SQLITE_TEXT     3
3749 #endif
3750 #define SQLITE3_TEXT     3
3751
3752 /*
3753 ** CAPI3REF: Result Values From A Query
3754 ** KEYWORDS: {column access functions}
3755 **
3756 ** These routines form the "result set" interface.
3757 **
3758 ** ^These routines return information about a single column of the current
3759 ** result row of a query.  ^In every case the first argument is a pointer
3760 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3761 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3762 ** and the second argument is the index of the column for which information
3763 ** should be returned. ^The leftmost column of the result set has the index 0.
3764 ** ^The number of columns in the result can be determined using
3765 ** [sqlite3_column_count()].
3766 **
3767 ** If the SQL statement does not currently point to a valid row, or if the
3768 ** column index is out of range, the result is undefined.
3769 ** These routines may only be called when the most recent call to
3770 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3771 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3772 ** If any of these routines are called after [sqlite3_reset()] or
3773 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3774 ** something other than [SQLITE_ROW], the results are undefined.
3775 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3776 ** are called from a different thread while any of these routines
3777 ** are pending, then the results are undefined.
3778 **
3779 ** ^The sqlite3_column_type() routine returns the
3780 ** [SQLITE_INTEGER | datatype code] for the initial data type
3781 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3782 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3783 ** returned by sqlite3_column_type() is only meaningful if no type
3784 ** conversions have occurred as described below.  After a type conversion,
3785 ** the value returned by sqlite3_column_type() is undefined.  Future
3786 ** versions of SQLite may change the behavior of sqlite3_column_type()
3787 ** following a type conversion.
3788 **
3789 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3790 ** routine returns the number of bytes in that BLOB or string.
3791 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3792 ** the string to UTF-8 and then returns the number of bytes.
3793 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3794 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3795 ** the number of bytes in that string.
3796 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3797 **
3798 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3799 ** routine returns the number of bytes in that BLOB or string.
3800 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3801 ** the string to UTF-16 and then returns the number of bytes.
3802 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3803 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3804 ** the number of bytes in that string.
3805 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3806 **
3807 ** ^The values returned by [sqlite3_column_bytes()] and 
3808 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3809 ** of the string.  ^For clarity: the values returned by
3810 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3811 ** bytes in the string, not the number of characters.
3812 **
3813 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3814 ** even empty strings, are always zero terminated.  ^The return
3815 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3816 **
3817 ** ^The object returned by [sqlite3_column_value()] is an
3818 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3819 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3820 ** If the [unprotected sqlite3_value] object returned by
3821 ** [sqlite3_column_value()] is used in any other way, including calls
3822 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3823 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3824 **
3825 ** These routines attempt to convert the value where appropriate.  ^For
3826 ** example, if the internal representation is FLOAT and a text result
3827 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3828 ** conversion automatically.  ^(The following table details the conversions
3829 ** that are applied:
3830 **
3831 ** <blockquote>
3832 ** <table border="1">
3833 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3834 **
3835 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3836 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3837 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3838 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3839 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3840 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3841 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3842 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3843 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3844 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3845 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3846 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3847 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3848 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3849 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3850 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3851 ** </table>
3852 ** </blockquote>)^
3853 **
3854 ** The table above makes reference to standard C library functions atoi()
3855 ** and atof().  SQLite does not really use these functions.  It has its
3856 ** own equivalent internal routines.  The atoi() and atof() names are
3857 ** used in the table for brevity and because they are familiar to most
3858 ** C programmers.
3859 **
3860 ** Note that when type conversions occur, pointers returned by prior
3861 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3862 ** sqlite3_column_text16() may be invalidated.
3863 ** Type conversions and pointer invalidations might occur
3864 ** in the following cases:
3865 **
3866 ** <ul>
3867 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3868 **      sqlite3_column_text16() is called.  A zero-terminator might
3869 **      need to be added to the string.</li>
3870 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3871 **      sqlite3_column_text16() is called.  The content must be converted
3872 **      to UTF-16.</li>
3873 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3874 **      sqlite3_column_text() is called.  The content must be converted
3875 **      to UTF-8.</li>
3876 ** </ul>
3877 **
3878 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3879 ** not invalidate a prior pointer, though of course the content of the buffer
3880 ** that the prior pointer references will have been modified.  Other kinds
3881 ** of conversion are done in place when it is possible, but sometimes they
3882 ** are not possible and in those cases prior pointers are invalidated.
3883 **
3884 ** The safest and easiest to remember policy is to invoke these routines
3885 ** in one of the following ways:
3886 **
3887 ** <ul>
3888 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3889 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3890 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3891 ** </ul>
3892 **
3893 ** In other words, you should call sqlite3_column_text(),
3894 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3895 ** into the desired format, then invoke sqlite3_column_bytes() or
3896 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3897 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3898 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3899 ** with calls to sqlite3_column_bytes().
3900 **
3901 ** ^The pointers returned are valid until a type conversion occurs as
3902 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3903 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3904 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3905 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3906 ** [sqlite3_free()].
3907 **
3908 ** ^(If a memory allocation error occurs during the evaluation of any
3909 ** of these routines, a default value is returned.  The default value
3910 ** is either the integer 0, the floating point number 0.0, or a NULL
3911 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3912 ** [SQLITE_NOMEM].)^
3913 */
3914 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3915 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3916 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3917 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3918 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3919 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3920 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3921 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3922 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3923 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3924
3925 /*
3926 ** CAPI3REF: Destroy A Prepared Statement Object
3927 **
3928 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3929 ** ^If the most recent evaluation of the statement encountered no errors or
3930 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3931 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3932 ** sqlite3_finalize(S) returns the appropriate [error code] or
3933 ** [extended error code].
3934 **
3935 ** ^The sqlite3_finalize(S) routine can be called at any point during
3936 ** the life cycle of [prepared statement] S:
3937 ** before statement S is ever evaluated, after
3938 ** one or more calls to [sqlite3_reset()], or after any call
3939 ** to [sqlite3_step()] regardless of whether or not the statement has
3940 ** completed execution.
3941 **
3942 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3943 **
3944 ** The application must finalize every [prepared statement] in order to avoid
3945 ** resource leaks.  It is a grievous error for the application to try to use
3946 ** a prepared statement after it has been finalized.  Any use of a prepared
3947 ** statement after it has been finalized can result in undefined and
3948 ** undesirable behavior such as segfaults and heap corruption.
3949 */
3950 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3951
3952 /*
3953 ** CAPI3REF: Reset A Prepared Statement Object
3954 **
3955 ** The sqlite3_reset() function is called to reset a [prepared statement]
3956 ** object back to its initial state, ready to be re-executed.
3957 ** ^Any SQL statement variables that had values bound to them using
3958 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3959 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3960 **
3961 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3962 ** back to the beginning of its program.
3963 **
3964 ** ^If the most recent call to [sqlite3_step(S)] for the
3965 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3966 ** or if [sqlite3_step(S)] has never before been called on S,
3967 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3968 **
3969 ** ^If the most recent call to [sqlite3_step(S)] for the
3970 ** [prepared statement] S indicated an error, then
3971 ** [sqlite3_reset(S)] returns an appropriate [error code].
3972 **
3973 ** ^The [sqlite3_reset(S)] interface does not change the values
3974 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3975 */
3976 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3977
3978 /*
3979 ** CAPI3REF: Create Or Redefine SQL Functions
3980 ** KEYWORDS: {function creation routines}
3981 ** KEYWORDS: {application-defined SQL function}
3982 ** KEYWORDS: {application-defined SQL functions}
3983 **
3984 ** ^These functions (collectively known as "function creation routines")
3985 ** are used to add SQL functions or aggregates or to redefine the behavior
3986 ** of existing SQL functions or aggregates.  The only differences between
3987 ** these routines are the text encoding expected for
3988 ** the second parameter (the name of the function being created)
3989 ** and the presence or absence of a destructor callback for
3990 ** the application data pointer.
3991 **
3992 ** ^The first parameter is the [database connection] to which the SQL
3993 ** function is to be added.  ^If an application uses more than one database
3994 ** connection then application-defined SQL functions must be added
3995 ** to each database connection separately.
3996 **
3997 ** ^The second parameter is the name of the SQL function to be created or
3998 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3999 ** representation, exclusive of the zero-terminator.  ^Note that the name
4000 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4001 ** ^Any attempt to create a function with a longer name
4002 ** will result in [SQLITE_MISUSE] being returned.
4003 **
4004 ** ^The third parameter (nArg)
4005 ** is the number of arguments that the SQL function or
4006 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4007 ** aggregate may take any number of arguments between 0 and the limit
4008 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4009 ** parameter is less than -1 or greater than 127 then the behavior is
4010 ** undefined.
4011 **
4012 ** ^The fourth parameter, eTextRep, specifies what
4013 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4014 ** its parameters.  Every SQL function implementation must be able to work
4015 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4016 ** more efficient with one encoding than another.  ^An application may
4017 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4018 ** times with the same function but with different values of eTextRep.
4019 ** ^When multiple implementations of the same function are available, SQLite
4020 ** will pick the one that involves the least amount of data conversion.
4021 ** If there is only a single implementation which does not care what text
4022 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4023 **
4024 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4025 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4026 **
4027 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4028 ** pointers to C-language functions that implement the SQL function or
4029 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4030 ** callback only; NULL pointers must be passed as the xStep and xFinal
4031 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4032 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4033 ** SQL function or aggregate, pass NULL pointers for all three function
4034 ** callbacks.
4035 **
4036 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4037 ** then it is destructor for the application data pointer. 
4038 ** The destructor is invoked when the function is deleted, either by being
4039 ** overloaded or when the database connection closes.)^
4040 ** ^The destructor is also invoked if the call to
4041 ** sqlite3_create_function_v2() fails.
4042 ** ^When the destructor callback of the tenth parameter is invoked, it
4043 ** is passed a single argument which is a copy of the application data 
4044 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4045 **
4046 ** ^It is permitted to register multiple implementations of the same
4047 ** functions with the same name but with either differing numbers of
4048 ** arguments or differing preferred text encodings.  ^SQLite will use
4049 ** the implementation that most closely matches the way in which the
4050 ** SQL function is used.  ^A function implementation with a non-negative
4051 ** nArg parameter is a better match than a function implementation with
4052 ** a negative nArg.  ^A function where the preferred text encoding
4053 ** matches the database encoding is a better
4054 ** match than a function where the encoding is different.  
4055 ** ^A function where the encoding difference is between UTF16le and UTF16be
4056 ** is a closer match than a function where the encoding difference is
4057 ** between UTF8 and UTF16.
4058 **
4059 ** ^Built-in functions may be overloaded by new application-defined functions.
4060 **
4061 ** ^An application-defined function is permitted to call other
4062 ** SQLite interfaces.  However, such calls must not
4063 ** close the database connection nor finalize or reset the prepared
4064 ** statement in which the function is running.
4065 */
4066 SQLITE_API int sqlite3_create_function(
4067   sqlite3 *db,
4068   const char *zFunctionName,
4069   int nArg,
4070   int eTextRep,
4071   void *pApp,
4072   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4073   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4074   void (*xFinal)(sqlite3_context*)
4075 );
4076 SQLITE_API int sqlite3_create_function16(
4077   sqlite3 *db,
4078   const void *zFunctionName,
4079   int nArg,
4080   int eTextRep,
4081   void *pApp,
4082   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4083   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4084   void (*xFinal)(sqlite3_context*)
4085 );
4086 SQLITE_API int sqlite3_create_function_v2(
4087   sqlite3 *db,
4088   const char *zFunctionName,
4089   int nArg,
4090   int eTextRep,
4091   void *pApp,
4092   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4093   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4094   void (*xFinal)(sqlite3_context*),
4095   void(*xDestroy)(void*)
4096 );
4097
4098 /*
4099 ** CAPI3REF: Text Encodings
4100 **
4101 ** These constant define integer codes that represent the various
4102 ** text encodings supported by SQLite.
4103 */
4104 #define SQLITE_UTF8           1
4105 #define SQLITE_UTF16LE        2
4106 #define SQLITE_UTF16BE        3
4107 #define SQLITE_UTF16          4    /* Use native byte order */
4108 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4109 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4110
4111 /*
4112 ** CAPI3REF: Deprecated Functions
4113 ** DEPRECATED
4114 **
4115 ** These functions are [deprecated].  In order to maintain
4116 ** backwards compatibility with older code, these functions continue 
4117 ** to be supported.  However, new applications should avoid
4118 ** the use of these functions.  To help encourage people to avoid
4119 ** using these functions, we are not going to tell you what they do.
4120 */
4121 #ifndef SQLITE_OMIT_DEPRECATED
4122 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4123 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4124 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4125 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4126 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4127 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4128 #endif
4129
4130 /*
4131 ** CAPI3REF: Obtaining SQL Function Parameter Values
4132 **
4133 ** The C-language implementation of SQL functions and aggregates uses
4134 ** this set of interface routines to access the parameter values on
4135 ** the function or aggregate.
4136 **
4137 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4138 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4139 ** define callbacks that implement the SQL functions and aggregates.
4140 ** The 3rd parameter to these callbacks is an array of pointers to
4141 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4142 ** each parameter to the SQL function.  These routines are used to
4143 ** extract values from the [sqlite3_value] objects.
4144 **
4145 ** These routines work only with [protected sqlite3_value] objects.
4146 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4147 ** object results in undefined behavior.
4148 **
4149 ** ^These routines work just like the corresponding [column access functions]
4150 ** except that  these routines take a single [protected sqlite3_value] object
4151 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4152 **
4153 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4154 ** in the native byte-order of the host machine.  ^The
4155 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4156 ** extract UTF-16 strings as big-endian and little-endian respectively.
4157 **
4158 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4159 ** numeric affinity to the value.  This means that an attempt is
4160 ** made to convert the value to an integer or floating point.  If
4161 ** such a conversion is possible without loss of information (in other
4162 ** words, if the value is a string that looks like a number)
4163 ** then the conversion is performed.  Otherwise no conversion occurs.
4164 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4165 **
4166 ** Please pay particular attention to the fact that the pointer returned
4167 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4168 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4169 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4170 ** or [sqlite3_value_text16()].
4171 **
4172 ** These routines must be called from the same thread as
4173 ** the SQL function that supplied the [sqlite3_value*] parameters.
4174 */
4175 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4176 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4177 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4178 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4179 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4180 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4181 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4182 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4183 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4184 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4185 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4186 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4187
4188 /*
4189 ** CAPI3REF: Obtain Aggregate Function Context
4190 **
4191 ** Implementations of aggregate SQL functions use this
4192 ** routine to allocate memory for storing their state.
4193 **
4194 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4195 ** for a particular aggregate function, SQLite
4196 ** allocates N of memory, zeroes out that memory, and returns a pointer
4197 ** to the new memory. ^On second and subsequent calls to
4198 ** sqlite3_aggregate_context() for the same aggregate function instance,
4199 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4200 ** called once for each invocation of the xStep callback and then one
4201 ** last time when the xFinal callback is invoked.  ^(When no rows match
4202 ** an aggregate query, the xStep() callback of the aggregate function
4203 ** implementation is never called and xFinal() is called exactly once.
4204 ** In those cases, sqlite3_aggregate_context() might be called for the
4205 ** first time from within xFinal().)^
4206 **
4207 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4208 ** less than or equal to zero or if a memory allocate error occurs.
4209 **
4210 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4211 ** determined by the N parameter on first successful call.  Changing the
4212 ** value of N in subsequent call to sqlite3_aggregate_context() within
4213 ** the same aggregate function instance will not resize the memory
4214 ** allocation.)^
4215 **
4216 ** ^SQLite automatically frees the memory allocated by 
4217 ** sqlite3_aggregate_context() when the aggregate query concludes.
4218 **
4219 ** The first parameter must be a copy of the
4220 ** [sqlite3_context | SQL function context] that is the first parameter
4221 ** to the xStep or xFinal callback routine that implements the aggregate
4222 ** function.
4223 **
4224 ** This routine must be called from the same thread in which
4225 ** the aggregate SQL function is running.
4226 */
4227 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4228
4229 /*
4230 ** CAPI3REF: User Data For Functions
4231 **
4232 ** ^The sqlite3_user_data() interface returns a copy of
4233 ** the pointer that was the pUserData parameter (the 5th parameter)
4234 ** of the [sqlite3_create_function()]
4235 ** and [sqlite3_create_function16()] routines that originally
4236 ** registered the application defined function.
4237 **
4238 ** This routine must be called from the same thread in which
4239 ** the application-defined function is running.
4240 */
4241 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4242
4243 /*
4244 ** CAPI3REF: Database Connection For Functions
4245 **
4246 ** ^The sqlite3_context_db_handle() interface returns a copy of
4247 ** the pointer to the [database connection] (the 1st parameter)
4248 ** of the [sqlite3_create_function()]
4249 ** and [sqlite3_create_function16()] routines that originally
4250 ** registered the application defined function.
4251 */
4252 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4253
4254 /*
4255 ** CAPI3REF: Function Auxiliary Data
4256 **
4257 ** The following two functions may be used by scalar SQL functions to
4258 ** associate metadata with argument values. If the same value is passed to
4259 ** multiple invocations of the same SQL function during query execution, under
4260 ** some circumstances the associated metadata may be preserved. This may
4261 ** be used, for example, to add a regular-expression matching scalar
4262 ** function. The compiled version of the regular expression is stored as
4263 ** metadata associated with the SQL value passed as the regular expression
4264 ** pattern.  The compiled regular expression can be reused on multiple
4265 ** invocations of the same function so that the original pattern string
4266 ** does not need to be recompiled on each invocation.
4267 **
4268 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4269 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4270 ** value to the application-defined function. ^If no metadata has been ever
4271 ** been set for the Nth argument of the function, or if the corresponding
4272 ** function parameter has changed since the meta-data was set,
4273 ** then sqlite3_get_auxdata() returns a NULL pointer.
4274 **
4275 ** ^The sqlite3_set_auxdata() interface saves the metadata
4276 ** pointed to by its 3rd parameter as the metadata for the N-th
4277 ** argument of the application-defined function.  Subsequent
4278 ** calls to sqlite3_get_auxdata() might return this data, if it has
4279 ** not been destroyed.
4280 ** ^If it is not NULL, SQLite will invoke the destructor
4281 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4282 ** the metadata when the corresponding function parameter changes
4283 ** or when the SQL statement completes, whichever comes first.
4284 **
4285 ** SQLite is free to call the destructor and drop metadata on any
4286 ** parameter of any function at any time.  ^The only guarantee is that
4287 ** the destructor will be called before the metadata is dropped.
4288 **
4289 ** ^(In practice, metadata is preserved between function calls for
4290 ** expressions that are constant at compile time. This includes literal
4291 ** values and [parameters].)^
4292 **
4293 ** These routines must be called from the same thread in which
4294 ** the SQL function is running.
4295 */
4296 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4297 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4298
4299
4300 /*
4301 ** CAPI3REF: Constants Defining Special Destructor Behavior
4302 **
4303 ** These are special values for the destructor that is passed in as the
4304 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4305 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4306 ** and will never change.  It does not need to be destroyed.  ^The
4307 ** SQLITE_TRANSIENT value means that the content will likely change in
4308 ** the near future and that SQLite should make its own private copy of
4309 ** the content before returning.
4310 **
4311 ** The typedef is necessary to work around problems in certain
4312 ** C++ compilers.  See ticket #2191.
4313 */
4314 typedef void (*sqlite3_destructor_type)(void*);
4315 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4316 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4317
4318 /*
4319 ** CAPI3REF: Setting The Result Of An SQL Function
4320 **
4321 ** These routines are used by the xFunc or xFinal callbacks that
4322 ** implement SQL functions and aggregates.  See
4323 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4324 ** for additional information.
4325 **
4326 ** These functions work very much like the [parameter binding] family of
4327 ** functions used to bind values to host parameters in prepared statements.
4328 ** Refer to the [SQL parameter] documentation for additional information.
4329 **
4330 ** ^The sqlite3_result_blob() interface sets the result from
4331 ** an application-defined function to be the BLOB whose content is pointed
4332 ** to by the second parameter and which is N bytes long where N is the
4333 ** third parameter.
4334 **
4335 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4336 ** the application-defined function to be a BLOB containing all zero
4337 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4338 **
4339 ** ^The sqlite3_result_double() interface sets the result from
4340 ** an application-defined function to be a floating point value specified
4341 ** by its 2nd argument.
4342 **
4343 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4344 ** cause the implemented SQL function to throw an exception.
4345 ** ^SQLite uses the string pointed to by the
4346 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4347 ** as the text of an error message.  ^SQLite interprets the error
4348 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4349 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4350 ** byte order.  ^If the third parameter to sqlite3_result_error()
4351 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4352 ** message all text up through the first zero character.
4353 ** ^If the third parameter to sqlite3_result_error() or
4354 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4355 ** bytes (not characters) from the 2nd parameter as the error message.
4356 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4357 ** routines make a private copy of the error message text before
4358 ** they return.  Hence, the calling function can deallocate or
4359 ** modify the text after they return without harm.
4360 ** ^The sqlite3_result_error_code() function changes the error code
4361 ** returned by SQLite as a result of an error in a function.  ^By default,
4362 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4363 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4364 **
4365 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4366 ** indicating that a string or BLOB is too long to represent.
4367 **
4368 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4369 ** indicating that a memory allocation failed.
4370 **
4371 ** ^The sqlite3_result_int() interface sets the return value
4372 ** of the application-defined function to be the 32-bit signed integer
4373 ** value given in the 2nd argument.
4374 ** ^The sqlite3_result_int64() interface sets the return value
4375 ** of the application-defined function to be the 64-bit signed integer
4376 ** value given in the 2nd argument.
4377 **
4378 ** ^The sqlite3_result_null() interface sets the return value
4379 ** of the application-defined function to be NULL.
4380 **
4381 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4382 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4383 ** set the return value of the application-defined function to be
4384 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4385 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4386 ** ^SQLite takes the text result from the application from
4387 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4388 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4389 ** is negative, then SQLite takes result text from the 2nd parameter
4390 ** through the first zero character.
4391 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4392 ** is non-negative, then as many bytes (not characters) of the text
4393 ** pointed to by the 2nd parameter are taken as the application-defined
4394 ** function result.
4395 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4396 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4397 ** function as the destructor on the text or BLOB result when it has
4398 ** finished using that result.
4399 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4400 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4401 ** assumes that the text or BLOB result is in constant space and does not
4402 ** copy the content of the parameter nor call a destructor on the content
4403 ** when it has finished using that result.
4404 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4405 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4406 ** then SQLite makes a copy of the result into space obtained from
4407 ** from [sqlite3_malloc()] before it returns.
4408 **
4409 ** ^The sqlite3_result_value() interface sets the result of
4410 ** the application-defined function to be a copy the
4411 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4412 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4413 ** so that the [sqlite3_value] specified in the parameter may change or
4414 ** be deallocated after sqlite3_result_value() returns without harm.
4415 ** ^A [protected sqlite3_value] object may always be used where an
4416 ** [unprotected sqlite3_value] object is required, so either
4417 ** kind of [sqlite3_value] object can be used with this interface.
4418 **
4419 ** If these routines are called from within the different thread
4420 ** than the one containing the application-defined function that received
4421 ** the [sqlite3_context] pointer, the results are undefined.
4422 */
4423 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4424 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4425 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4426 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4427 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4428 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4429 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4430 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4431 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4432 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4433 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4434 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4435 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4436 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4437 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4438 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4439
4440 /*
4441 ** CAPI3REF: Define New Collating Sequences
4442 **
4443 ** ^These functions add, remove, or modify a [collation] associated
4444 ** with the [database connection] specified as the first argument.
4445 **
4446 ** ^The name of the collation is a UTF-8 string
4447 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4448 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4449 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4450 ** considered to be the same name.
4451 **
4452 ** ^(The third argument (eTextRep) must be one of the constants:
4453 ** <ul>
4454 ** <li> [SQLITE_UTF8],
4455 ** <li> [SQLITE_UTF16LE],
4456 ** <li> [SQLITE_UTF16BE],
4457 ** <li> [SQLITE_UTF16], or
4458 ** <li> [SQLITE_UTF16_ALIGNED].
4459 ** </ul>)^
4460 ** ^The eTextRep argument determines the encoding of strings passed
4461 ** to the collating function callback, xCallback.
4462 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4463 ** force strings to be UTF16 with native byte order.
4464 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4465 ** on an even byte address.
4466 **
4467 ** ^The fourth argument, pArg, is an application data pointer that is passed
4468 ** through as the first argument to the collating function callback.
4469 **
4470 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4471 ** ^Multiple collating functions can be registered using the same name but
4472 ** with different eTextRep parameters and SQLite will use whichever
4473 ** function requires the least amount of data transformation.
4474 ** ^If the xCallback argument is NULL then the collating function is
4475 ** deleted.  ^When all collating functions having the same name are deleted,
4476 ** that collation is no longer usable.
4477 **
4478 ** ^The collating function callback is invoked with a copy of the pArg 
4479 ** application data pointer and with two strings in the encoding specified
4480 ** by the eTextRep argument.  The collating function must return an
4481 ** integer that is negative, zero, or positive
4482 ** if the first string is less than, equal to, or greater than the second,
4483 ** respectively.  A collating function must always return the same answer
4484 ** given the same inputs.  If two or more collating functions are registered
4485 ** to the same collation name (using different eTextRep values) then all
4486 ** must give an equivalent answer when invoked with equivalent strings.
4487 ** The collating function must obey the following properties for all
4488 ** strings A, B, and C:
4489 **
4490 ** <ol>
4491 ** <li> If A==B then B==A.
4492 ** <li> If A==B and B==C then A==C.
4493 ** <li> If A&lt;B THEN B&gt;A.
4494 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4495 ** </ol>
4496 **
4497 ** If a collating function fails any of the above constraints and that
4498 ** collating function is  registered and used, then the behavior of SQLite
4499 ** is undefined.
4500 **
4501 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4502 ** with the addition that the xDestroy callback is invoked on pArg when
4503 ** the collating function is deleted.
4504 ** ^Collating functions are deleted when they are overridden by later
4505 ** calls to the collation creation functions or when the
4506 ** [database connection] is closed using [sqlite3_close()].
4507 **
4508 ** ^The xDestroy callback is <u>not</u> called if the 
4509 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4510 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4511 ** check the return code and dispose of the application data pointer
4512 ** themselves rather than expecting SQLite to deal with it for them.
4513 ** This is different from every other SQLite interface.  The inconsistency 
4514 ** is unfortunate but cannot be changed without breaking backwards 
4515 ** compatibility.
4516 **
4517 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4518 */
4519 SQLITE_API int sqlite3_create_collation(
4520   sqlite3*, 
4521   const char *zName, 
4522   int eTextRep, 
4523   void *pArg,
4524   int(*xCompare)(void*,int,const void*,int,const void*)
4525 );
4526 SQLITE_API int sqlite3_create_collation_v2(
4527   sqlite3*, 
4528   const char *zName, 
4529   int eTextRep, 
4530   void *pArg,
4531   int(*xCompare)(void*,int,const void*,int,const void*),
4532   void(*xDestroy)(void*)
4533 );
4534 SQLITE_API int sqlite3_create_collation16(
4535   sqlite3*, 
4536   const void *zName,
4537   int eTextRep, 
4538   void *pArg,
4539   int(*xCompare)(void*,int,const void*,int,const void*)
4540 );
4541
4542 /*
4543 ** CAPI3REF: Collation Needed Callbacks
4544 **
4545 ** ^To avoid having to register all collation sequences before a database
4546 ** can be used, a single callback function may be registered with the
4547 ** [database connection] to be invoked whenever an undefined collation
4548 ** sequence is required.
4549 **
4550 ** ^If the function is registered using the sqlite3_collation_needed() API,
4551 ** then it is passed the names of undefined collation sequences as strings
4552 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4553 ** the names are passed as UTF-16 in machine native byte order.
4554 ** ^A call to either function replaces the existing collation-needed callback.
4555 **
4556 ** ^(When the callback is invoked, the first argument passed is a copy
4557 ** of the second argument to sqlite3_collation_needed() or
4558 ** sqlite3_collation_needed16().  The second argument is the database
4559 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4560 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4561 ** sequence function required.  The fourth parameter is the name of the
4562 ** required collation sequence.)^
4563 **
4564 ** The callback function should register the desired collation using
4565 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4566 ** [sqlite3_create_collation_v2()].
4567 */
4568 SQLITE_API int sqlite3_collation_needed(
4569   sqlite3*, 
4570   void*, 
4571   void(*)(void*,sqlite3*,int eTextRep,const char*)
4572 );
4573 SQLITE_API int sqlite3_collation_needed16(
4574   sqlite3*, 
4575   void*,
4576   void(*)(void*,sqlite3*,int eTextRep,const void*)
4577 );
4578
4579 #ifdef SQLITE_HAS_CODEC
4580 /*
4581 ** Specify the key for an encrypted database.  This routine should be
4582 ** called right after sqlite3_open().
4583 **
4584 ** The code to implement this API is not available in the public release
4585 ** of SQLite.
4586 */
4587 SQLITE_API int sqlite3_key(
4588   sqlite3 *db,                   /* Database to be rekeyed */
4589   const void *pKey, int nKey     /* The key */
4590 );
4591
4592 /*
4593 ** Change the key on an open database.  If the current database is not
4594 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4595 ** database is decrypted.
4596 **
4597 ** The code to implement this API is not available in the public release
4598 ** of SQLite.
4599 */
4600 SQLITE_API int sqlite3_rekey(
4601   sqlite3 *db,                   /* Database to be rekeyed */
4602   const void *pKey, int nKey     /* The new key */
4603 );
4604
4605 /*
4606 ** Specify the activation key for a SEE database.  Unless 
4607 ** activated, none of the SEE routines will work.
4608 */
4609 SQLITE_API void sqlite3_activate_see(
4610   const char *zPassPhrase        /* Activation phrase */
4611 );
4612 #endif
4613
4614 #ifdef SQLITE_ENABLE_CEROD
4615 /*
4616 ** Specify the activation key for a CEROD database.  Unless 
4617 ** activated, none of the CEROD routines will work.
4618 */
4619 SQLITE_API void sqlite3_activate_cerod(
4620   const char *zPassPhrase        /* Activation phrase */
4621 );
4622 #endif
4623
4624 /*
4625 ** CAPI3REF: Suspend Execution For A Short Time
4626 **
4627 ** The sqlite3_sleep() function causes the current thread to suspend execution
4628 ** for at least a number of milliseconds specified in its parameter.
4629 **
4630 ** If the operating system does not support sleep requests with
4631 ** millisecond time resolution, then the time will be rounded up to
4632 ** the nearest second. The number of milliseconds of sleep actually
4633 ** requested from the operating system is returned.
4634 **
4635 ** ^SQLite implements this interface by calling the xSleep()
4636 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4637 ** of the default VFS is not implemented correctly, or not implemented at
4638 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4639 ** in the previous paragraphs.
4640 */
4641 SQLITE_API int sqlite3_sleep(int);
4642
4643 /*
4644 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4645 **
4646 ** ^(If this global variable is made to point to a string which is
4647 ** the name of a folder (a.k.a. directory), then all temporary files
4648 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4649 ** will be placed in that directory.)^  ^If this variable
4650 ** is a NULL pointer, then SQLite performs a search for an appropriate
4651 ** temporary file directory.
4652 **
4653 ** It is not safe to read or modify this variable in more than one
4654 ** thread at a time.  It is not safe to read or modify this variable
4655 ** if a [database connection] is being used at the same time in a separate
4656 ** thread.
4657 ** It is intended that this variable be set once
4658 ** as part of process initialization and before any SQLite interface
4659 ** routines have been called and that this variable remain unchanged
4660 ** thereafter.
4661 **
4662 ** ^The [temp_store_directory pragma] may modify this variable and cause
4663 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4664 ** the [temp_store_directory pragma] always assumes that any string
4665 ** that this variable points to is held in memory obtained from 
4666 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4667 ** using [sqlite3_free].
4668 ** Hence, if this variable is modified directly, either it should be
4669 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4670 ** or else the use of the [temp_store_directory pragma] should be avoided.
4671 */
4672 SQLITE_API char *sqlite3_temp_directory;
4673
4674 /*
4675 ** CAPI3REF: Test For Auto-Commit Mode
4676 ** KEYWORDS: {autocommit mode}
4677 **
4678 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4679 ** zero if the given database connection is or is not in autocommit mode,
4680 ** respectively.  ^Autocommit mode is on by default.
4681 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4682 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4683 **
4684 ** If certain kinds of errors occur on a statement within a multi-statement
4685 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4686 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4687 ** transaction might be rolled back automatically.  The only way to
4688 ** find out whether SQLite automatically rolled back the transaction after
4689 ** an error is to use this function.
4690 **
4691 ** If another thread changes the autocommit status of the database
4692 ** connection while this routine is running, then the return value
4693 ** is undefined.
4694 */
4695 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4696
4697 /*
4698 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4699 **
4700 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4701 ** to which a [prepared statement] belongs.  ^The [database connection]
4702 ** returned by sqlite3_db_handle is the same [database connection]
4703 ** that was the first argument
4704 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4705 ** create the statement in the first place.
4706 */
4707 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4708
4709 /*
4710 ** CAPI3REF: Find the next prepared statement
4711 **
4712 ** ^This interface returns a pointer to the next [prepared statement] after
4713 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4714 ** then this interface returns a pointer to the first prepared statement
4715 ** associated with the database connection pDb.  ^If no prepared statement
4716 ** satisfies the conditions of this routine, it returns NULL.
4717 **
4718 ** The [database connection] pointer D in a call to
4719 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4720 ** connection and in particular must not be a NULL pointer.
4721 */
4722 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4723
4724 /*
4725 ** CAPI3REF: Commit And Rollback Notification Callbacks
4726 **
4727 ** ^The sqlite3_commit_hook() interface registers a callback
4728 ** function to be invoked whenever a transaction is [COMMIT | committed].
4729 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4730 ** for the same database connection is overridden.
4731 ** ^The sqlite3_rollback_hook() interface registers a callback
4732 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4733 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4734 ** for the same database connection is overridden.
4735 ** ^The pArg argument is passed through to the callback.
4736 ** ^If the callback on a commit hook function returns non-zero,
4737 ** then the commit is converted into a rollback.
4738 **
4739 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4740 ** return the P argument from the previous call of the same function
4741 ** on the same [database connection] D, or NULL for
4742 ** the first call for each function on D.
4743 **
4744 ** The callback implementation must not do anything that will modify
4745 ** the database connection that invoked the callback.  Any actions
4746 ** to modify the database connection must be deferred until after the
4747 ** completion of the [sqlite3_step()] call that triggered the commit
4748 ** or rollback hook in the first place.
4749 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4750 ** database connections for the meaning of "modify" in this paragraph.
4751 **
4752 ** ^Registering a NULL function disables the callback.
4753 **
4754 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4755 ** operation is allowed to continue normally.  ^If the commit hook
4756 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4757 ** ^The rollback hook is invoked on a rollback that results from a commit
4758 ** hook returning non-zero, just as it would be with any other rollback.
4759 **
4760 ** ^For the purposes of this API, a transaction is said to have been
4761 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4762 ** an error or constraint causes an implicit rollback to occur.
4763 ** ^The rollback callback is not invoked if a transaction is
4764 ** automatically rolled back because the database connection is closed.
4765 **
4766 ** See also the [sqlite3_update_hook()] interface.
4767 */
4768 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4769 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4770
4771 /*
4772 ** CAPI3REF: Data Change Notification Callbacks
4773 **
4774 ** ^The sqlite3_update_hook() interface registers a callback function
4775 ** with the [database connection] identified by the first argument
4776 ** to be invoked whenever a row is updated, inserted or deleted.
4777 ** ^Any callback set by a previous call to this function
4778 ** for the same database connection is overridden.
4779 **
4780 ** ^The second argument is a pointer to the function to invoke when a
4781 ** row is updated, inserted or deleted.
4782 ** ^The first argument to the callback is a copy of the third argument
4783 ** to sqlite3_update_hook().
4784 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4785 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4786 ** to be invoked.
4787 ** ^The third and fourth arguments to the callback contain pointers to the
4788 ** database and table name containing the affected row.
4789 ** ^The final callback parameter is the [rowid] of the row.
4790 ** ^In the case of an update, this is the [rowid] after the update takes place.
4791 **
4792 ** ^(The update hook is not invoked when internal system tables are
4793 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4794 **
4795 ** ^In the current implementation, the update hook
4796 ** is not invoked when duplication rows are deleted because of an
4797 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4798 ** invoked when rows are deleted using the [truncate optimization].
4799 ** The exceptions defined in this paragraph might change in a future
4800 ** release of SQLite.
4801 **
4802 ** The update hook implementation must not do anything that will modify
4803 ** the database connection that invoked the update hook.  Any actions
4804 ** to modify the database connection must be deferred until after the
4805 ** completion of the [sqlite3_step()] call that triggered the update hook.
4806 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4807 ** database connections for the meaning of "modify" in this paragraph.
4808 **
4809 ** ^The sqlite3_update_hook(D,C,P) function
4810 ** returns the P argument from the previous call
4811 ** on the same [database connection] D, or NULL for
4812 ** the first call on D.
4813 **
4814 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4815 ** interfaces.
4816 */
4817 SQLITE_API void *sqlite3_update_hook(
4818   sqlite3*, 
4819   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4820   void*
4821 );
4822
4823 /*
4824 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4825 ** KEYWORDS: {shared cache}
4826 **
4827 ** ^(This routine enables or disables the sharing of the database cache
4828 ** and schema data structures between [database connection | connections]
4829 ** to the same database. Sharing is enabled if the argument is true
4830 ** and disabled if the argument is false.)^
4831 **
4832 ** ^Cache sharing is enabled and disabled for an entire process.
4833 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4834 ** sharing was enabled or disabled for each thread separately.
4835 **
4836 ** ^(The cache sharing mode set by this interface effects all subsequent
4837 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4838 ** Existing database connections continue use the sharing mode
4839 ** that was in effect at the time they were opened.)^
4840 **
4841 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4842 ** successfully.  An [error code] is returned otherwise.)^
4843 **
4844 ** ^Shared cache is disabled by default. But this might change in
4845 ** future releases of SQLite.  Applications that care about shared
4846 ** cache setting should set it explicitly.
4847 **
4848 ** See Also:  [SQLite Shared-Cache Mode]
4849 */
4850 SQLITE_API int sqlite3_enable_shared_cache(int);
4851
4852 /*
4853 ** CAPI3REF: Attempt To Free Heap Memory
4854 **
4855 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4856 ** of heap memory by deallocating non-essential memory allocations
4857 ** held by the database library.   Memory used to cache database
4858 ** pages to improve performance is an example of non-essential memory.
4859 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4860 ** which might be more or less than the amount requested.
4861 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4862 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4863 */
4864 SQLITE_API int sqlite3_release_memory(int);
4865
4866 /*
4867 ** CAPI3REF: Impose A Limit On Heap Size
4868 **
4869 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4870 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4871 ** ^SQLite strives to keep heap memory utilization below the soft heap
4872 ** limit by reducing the number of pages held in the page cache
4873 ** as heap memory usages approaches the limit.
4874 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4875 ** below the limit, it will exceed the limit rather than generate
4876 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
4877 ** is advisory only.
4878 **
4879 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4880 ** the soft heap limit prior to the call.  ^If the argument N is negative
4881 ** then no change is made to the soft heap limit.  Hence, the current
4882 ** size of the soft heap limit can be determined by invoking
4883 ** sqlite3_soft_heap_limit64() with a negative argument.
4884 **
4885 ** ^If the argument N is zero then the soft heap limit is disabled.
4886 **
4887 ** ^(The soft heap limit is not enforced in the current implementation
4888 ** if one or more of following conditions are true:
4889 **
4890 ** <ul>
4891 ** <li> The soft heap limit is set to zero.
4892 ** <li> Memory accounting is disabled using a combination of the
4893 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4894 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4895 ** <li> An alternative page cache implementation is specified using
4896 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4897 ** <li> The page cache allocates from its own memory pool supplied
4898 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4899 **      from the heap.
4900 ** </ul>)^
4901 **
4902 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4903 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4904 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4905 ** the soft heap limit is enforced on every memory allocation.  Without
4906 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4907 ** when memory is allocated by the page cache.  Testing suggests that because
4908 ** the page cache is the predominate memory user in SQLite, most
4909 ** applications will achieve adequate soft heap limit enforcement without
4910 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4911 **
4912 ** The circumstances under which SQLite will enforce the soft heap limit may
4913 ** changes in future releases of SQLite.
4914 */
4915 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4916
4917 /*
4918 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4919 ** DEPRECATED
4920 **
4921 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4922 ** interface.  This routine is provided for historical compatibility
4923 ** only.  All new applications should use the
4924 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4925 */
4926 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4927
4928
4929 /*
4930 ** CAPI3REF: Extract Metadata About A Column Of A Table
4931 **
4932 ** ^This routine returns metadata about a specific column of a specific
4933 ** database table accessible using the [database connection] handle
4934 ** passed as the first function argument.
4935 **
4936 ** ^The column is identified by the second, third and fourth parameters to
4937 ** this function. ^The second parameter is either the name of the database
4938 ** (i.e. "main", "temp", or an attached database) containing the specified
4939 ** table or NULL. ^If it is NULL, then all attached databases are searched
4940 ** for the table using the same algorithm used by the database engine to
4941 ** resolve unqualified table references.
4942 **
4943 ** ^The third and fourth parameters to this function are the table and column
4944 ** name of the desired column, respectively. Neither of these parameters
4945 ** may be NULL.
4946 **
4947 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4948 ** and subsequent parameters to this function. ^Any of these arguments may be
4949 ** NULL, in which case the corresponding element of metadata is omitted.
4950 **
4951 ** ^(<blockquote>
4952 ** <table border="1">
4953 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4954 **
4955 ** <tr><td> 5th <td> const char* <td> Data type
4956 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4957 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4958 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4959 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4960 ** </table>
4961 ** </blockquote>)^
4962 **
4963 ** ^The memory pointed to by the character pointers returned for the
4964 ** declaration type and collation sequence is valid only until the next
4965 ** call to any SQLite API function.
4966 **
4967 ** ^If the specified table is actually a view, an [error code] is returned.
4968 **
4969 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4970 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4971 ** parameters are set for the explicitly declared column. ^(If there is no
4972 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4973 ** parameters are set as follows:
4974 **
4975 ** <pre>
4976 **     data type: "INTEGER"
4977 **     collation sequence: "BINARY"
4978 **     not null: 0
4979 **     primary key: 1
4980 **     auto increment: 0
4981 ** </pre>)^
4982 **
4983 ** ^(This function may load one or more schemas from database files. If an
4984 ** error occurs during this process, or if the requested table or column
4985 ** cannot be found, an [error code] is returned and an error message left
4986 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4987 **
4988 ** ^This API is only available if the library was compiled with the
4989 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4990 */
4991 SQLITE_API int sqlite3_table_column_metadata(
4992   sqlite3 *db,                /* Connection handle */
4993   const char *zDbName,        /* Database name or NULL */
4994   const char *zTableName,     /* Table name */
4995   const char *zColumnName,    /* Column name */
4996   char const **pzDataType,    /* OUTPUT: Declared data type */
4997   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4998   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4999   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5000   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5001 );
5002
5003 /*
5004 ** CAPI3REF: Load An Extension
5005 **
5006 ** ^This interface loads an SQLite extension library from the named file.
5007 **
5008 ** ^The sqlite3_load_extension() interface attempts to load an
5009 ** SQLite extension library contained in the file zFile.
5010 **
5011 ** ^The entry point is zProc.
5012 ** ^zProc may be 0, in which case the name of the entry point
5013 ** defaults to "sqlite3_extension_init".
5014 ** ^The sqlite3_load_extension() interface returns
5015 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5016 ** ^If an error occurs and pzErrMsg is not 0, then the
5017 ** [sqlite3_load_extension()] interface shall attempt to
5018 ** fill *pzErrMsg with error message text stored in memory
5019 ** obtained from [sqlite3_malloc()]. The calling function
5020 ** should free this memory by calling [sqlite3_free()].
5021 **
5022 ** ^Extension loading must be enabled using
5023 ** [sqlite3_enable_load_extension()] prior to calling this API,
5024 ** otherwise an error will be returned.
5025 **
5026 ** See also the [load_extension() SQL function].
5027 */
5028 SQLITE_API int sqlite3_load_extension(
5029   sqlite3 *db,          /* Load the extension into this database connection */
5030   const char *zFile,    /* Name of the shared library containing extension */
5031   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5032   char **pzErrMsg       /* Put error message here if not 0 */
5033 );
5034
5035 /*
5036 ** CAPI3REF: Enable Or Disable Extension Loading
5037 **
5038 ** ^So as not to open security holes in older applications that are
5039 ** unprepared to deal with extension loading, and as a means of disabling
5040 ** extension loading while evaluating user-entered SQL, the following API
5041 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5042 **
5043 ** ^Extension loading is off by default. See ticket #1863.
5044 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5045 ** to turn extension loading on and call it with onoff==0 to turn
5046 ** it back off again.
5047 */
5048 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5049
5050 /*
5051 ** CAPI3REF: Automatically Load Statically Linked Extensions
5052 **
5053 ** ^This interface causes the xEntryPoint() function to be invoked for
5054 ** each new [database connection] that is created.  The idea here is that
5055 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5056 ** that is to be automatically loaded into all new database connections.
5057 **
5058 ** ^(Even though the function prototype shows that xEntryPoint() takes
5059 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5060 ** arguments and expects and integer result as if the signature of the
5061 ** entry point where as follows:
5062 **
5063 ** <blockquote><pre>
5064 ** &nbsp;  int xEntryPoint(
5065 ** &nbsp;    sqlite3 *db,
5066 ** &nbsp;    const char **pzErrMsg,
5067 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5068 ** &nbsp;  );
5069 ** </pre></blockquote>)^
5070 **
5071 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5072 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5073 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5074 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5075 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5076 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5077 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5078 **
5079 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5080 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5081 ** will be called more than once for each database connection that is opened.
5082 **
5083 ** See also: [sqlite3_reset_auto_extension()].
5084 */
5085 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5086
5087 /*
5088 ** CAPI3REF: Reset Automatic Extension Loading
5089 **
5090 ** ^This interface disables all automatic extensions previously
5091 ** registered using [sqlite3_auto_extension()].
5092 */
5093 SQLITE_API void sqlite3_reset_auto_extension(void);
5094
5095 /*
5096 ** The interface to the virtual-table mechanism is currently considered
5097 ** to be experimental.  The interface might change in incompatible ways.
5098 ** If this is a problem for you, do not use the interface at this time.
5099 **
5100 ** When the virtual-table mechanism stabilizes, we will declare the
5101 ** interface fixed, support it indefinitely, and remove this comment.
5102 */
5103
5104 /*
5105 ** Structures used by the virtual table interface
5106 */
5107 typedef struct sqlite3_vtab sqlite3_vtab;
5108 typedef struct sqlite3_index_info sqlite3_index_info;
5109 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5110 typedef struct sqlite3_module sqlite3_module;
5111
5112 /*
5113 ** CAPI3REF: Virtual Table Object
5114 ** KEYWORDS: sqlite3_module {virtual table module}
5115 **
5116 ** This structure, sometimes called a "virtual table module", 
5117 ** defines the implementation of a [virtual tables].  
5118 ** This structure consists mostly of methods for the module.
5119 **
5120 ** ^A virtual table module is created by filling in a persistent
5121 ** instance of this structure and passing a pointer to that instance
5122 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5123 ** ^The registration remains valid until it is replaced by a different
5124 ** module or until the [database connection] closes.  The content
5125 ** of this structure must not change while it is registered with
5126 ** any database connection.
5127 */
5128 struct sqlite3_module {
5129   int iVersion;
5130   int (*xCreate)(sqlite3*, void *pAux,
5131                int argc, const char *const*argv,
5132                sqlite3_vtab **ppVTab, char**);
5133   int (*xConnect)(sqlite3*, void *pAux,
5134                int argc, const char *const*argv,
5135                sqlite3_vtab **ppVTab, char**);
5136   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5137   int (*xDisconnect)(sqlite3_vtab *pVTab);
5138   int (*xDestroy)(sqlite3_vtab *pVTab);
5139   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5140   int (*xClose)(sqlite3_vtab_cursor*);
5141   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5142                 int argc, sqlite3_value **argv);
5143   int (*xNext)(sqlite3_vtab_cursor*);
5144   int (*xEof)(sqlite3_vtab_cursor*);
5145   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5146   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5147   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5148   int (*xBegin)(sqlite3_vtab *pVTab);
5149   int (*xSync)(sqlite3_vtab *pVTab);
5150   int (*xCommit)(sqlite3_vtab *pVTab);
5151   int (*xRollback)(sqlite3_vtab *pVTab);
5152   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5153                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5154                        void **ppArg);
5155   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5156 };
5157
5158 /*
5159 ** CAPI3REF: Virtual Table Indexing Information
5160 ** KEYWORDS: sqlite3_index_info
5161 **
5162 ** The sqlite3_index_info structure and its substructures is used as part
5163 ** of the [virtual table] interface to
5164 ** pass information into and receive the reply from the [xBestIndex]
5165 ** method of a [virtual table module].  The fields under **Inputs** are the
5166 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5167 ** results into the **Outputs** fields.
5168 **
5169 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5170 **
5171 ** <blockquote>column OP expr</blockquote>
5172 **
5173 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5174 ** stored in aConstraint[].op using one of the
5175 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5176 ** ^(The index of the column is stored in
5177 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5178 ** expr on the right-hand side can be evaluated (and thus the constraint
5179 ** is usable) and false if it cannot.)^
5180 **
5181 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5182 ** and makes other simplifications to the WHERE clause in an attempt to
5183 ** get as many WHERE clause terms into the form shown above as possible.
5184 ** ^The aConstraint[] array only reports WHERE clause terms that are
5185 ** relevant to the particular virtual table being queried.
5186 **
5187 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5188 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5189 **
5190 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5191 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5192 ** the right-hand side of the corresponding aConstraint[] is evaluated
5193 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5194 ** is true, then the constraint is assumed to be fully handled by the
5195 ** virtual table and is not checked again by SQLite.)^
5196 **
5197 ** ^The idxNum and idxPtr values are recorded and passed into the
5198 ** [xFilter] method.
5199 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5200 ** needToFreeIdxPtr is true.
5201 **
5202 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5203 ** the correct order to satisfy the ORDER BY clause so that no separate
5204 ** sorting step is required.
5205 **
5206 ** ^The estimatedCost value is an estimate of the cost of doing the
5207 ** particular lookup.  A full scan of a table with N entries should have
5208 ** a cost of N.  A binary search of a table of N entries should have a
5209 ** cost of approximately log(N).
5210 */
5211 struct sqlite3_index_info {
5212   /* Inputs */
5213   int nConstraint;           /* Number of entries in aConstraint */
5214   struct sqlite3_index_constraint {
5215      int iColumn;              /* Column on left-hand side of constraint */
5216      unsigned char op;         /* Constraint operator */
5217      unsigned char usable;     /* True if this constraint is usable */
5218      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5219   } *aConstraint;            /* Table of WHERE clause constraints */
5220   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5221   struct sqlite3_index_orderby {
5222      int iColumn;              /* Column number */
5223      unsigned char desc;       /* True for DESC.  False for ASC. */
5224   } *aOrderBy;               /* The ORDER BY clause */
5225   /* Outputs */
5226   struct sqlite3_index_constraint_usage {
5227     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5228     unsigned char omit;      /* Do not code a test for this constraint */
5229   } *aConstraintUsage;
5230   int idxNum;                /* Number used to identify the index */
5231   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5232   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5233   int orderByConsumed;       /* True if output is already ordered */
5234   double estimatedCost;      /* Estimated cost of using this index */
5235 };
5236
5237 /*
5238 ** CAPI3REF: Virtual Table Constraint Operator Codes
5239 **
5240 ** These macros defined the allowed values for the
5241 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5242 ** an operator that is part of a constraint term in the wHERE clause of
5243 ** a query that uses a [virtual table].
5244 */
5245 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5246 #define SQLITE_INDEX_CONSTRAINT_GT    4
5247 #define SQLITE_INDEX_CONSTRAINT_LE    8
5248 #define SQLITE_INDEX_CONSTRAINT_LT    16
5249 #define SQLITE_INDEX_CONSTRAINT_GE    32
5250 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5251
5252 /*
5253 ** CAPI3REF: Register A Virtual Table Implementation
5254 **
5255 ** ^These routines are used to register a new [virtual table module] name.
5256 ** ^Module names must be registered before
5257 ** creating a new [virtual table] using the module and before using a
5258 ** preexisting [virtual table] for the module.
5259 **
5260 ** ^The module name is registered on the [database connection] specified
5261 ** by the first parameter.  ^The name of the module is given by the 
5262 ** second parameter.  ^The third parameter is a pointer to
5263 ** the implementation of the [virtual table module].   ^The fourth
5264 ** parameter is an arbitrary client data pointer that is passed through
5265 ** into the [xCreate] and [xConnect] methods of the virtual table module
5266 ** when a new virtual table is be being created or reinitialized.
5267 **
5268 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5269 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5270 ** invoke the destructor function (if it is not NULL) when SQLite
5271 ** no longer needs the pClientData pointer.  ^The destructor will also
5272 ** be invoked if the call to sqlite3_create_module_v2() fails.
5273 ** ^The sqlite3_create_module()
5274 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5275 ** destructor.
5276 */
5277 SQLITE_API int sqlite3_create_module(
5278   sqlite3 *db,               /* SQLite connection to register module with */
5279   const char *zName,         /* Name of the module */
5280   const sqlite3_module *p,   /* Methods for the module */
5281   void *pClientData          /* Client data for xCreate/xConnect */
5282 );
5283 SQLITE_API int sqlite3_create_module_v2(
5284   sqlite3 *db,               /* SQLite connection to register module with */
5285   const char *zName,         /* Name of the module */
5286   const sqlite3_module *p,   /* Methods for the module */
5287   void *pClientData,         /* Client data for xCreate/xConnect */
5288   void(*xDestroy)(void*)     /* Module destructor function */
5289 );
5290
5291 /*
5292 ** CAPI3REF: Virtual Table Instance Object
5293 ** KEYWORDS: sqlite3_vtab
5294 **
5295 ** Every [virtual table module] implementation uses a subclass
5296 ** of this object to describe a particular instance
5297 ** of the [virtual table].  Each subclass will
5298 ** be tailored to the specific needs of the module implementation.
5299 ** The purpose of this superclass is to define certain fields that are
5300 ** common to all module implementations.
5301 **
5302 ** ^Virtual tables methods can set an error message by assigning a
5303 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5304 ** take care that any prior string is freed by a call to [sqlite3_free()]
5305 ** prior to assigning a new string to zErrMsg.  ^After the error message
5306 ** is delivered up to the client application, the string will be automatically
5307 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5308 */
5309 struct sqlite3_vtab {
5310   const sqlite3_module *pModule;  /* The module for this virtual table */
5311   int nRef;                       /* NO LONGER USED */
5312   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5313   /* Virtual table implementations will typically add additional fields */
5314 };
5315
5316 /*
5317 ** CAPI3REF: Virtual Table Cursor Object
5318 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5319 **
5320 ** Every [virtual table module] implementation uses a subclass of the
5321 ** following structure to describe cursors that point into the
5322 ** [virtual table] and are used
5323 ** to loop through the virtual table.  Cursors are created using the
5324 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5325 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5326 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5327 ** of the module.  Each module implementation will define
5328 ** the content of a cursor structure to suit its own needs.
5329 **
5330 ** This superclass exists in order to define fields of the cursor that
5331 ** are common to all implementations.
5332 */
5333 struct sqlite3_vtab_cursor {
5334   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5335   /* Virtual table implementations will typically add additional fields */
5336 };
5337
5338 /*
5339 ** CAPI3REF: Declare The Schema Of A Virtual Table
5340 **
5341 ** ^The [xCreate] and [xConnect] methods of a
5342 ** [virtual table module] call this interface
5343 ** to declare the format (the names and datatypes of the columns) of
5344 ** the virtual tables they implement.
5345 */
5346 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5347
5348 /*
5349 ** CAPI3REF: Overload A Function For A Virtual Table
5350 **
5351 ** ^(Virtual tables can provide alternative implementations of functions
5352 ** using the [xFindFunction] method of the [virtual table module].  
5353 ** But global versions of those functions
5354 ** must exist in order to be overloaded.)^
5355 **
5356 ** ^(This API makes sure a global version of a function with a particular
5357 ** name and number of parameters exists.  If no such function exists
5358 ** before this API is called, a new function is created.)^  ^The implementation
5359 ** of the new function always causes an exception to be thrown.  So
5360 ** the new function is not good for anything by itself.  Its only
5361 ** purpose is to be a placeholder function that can be overloaded
5362 ** by a [virtual table].
5363 */
5364 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5365
5366 /*
5367 ** The interface to the virtual-table mechanism defined above (back up
5368 ** to a comment remarkably similar to this one) is currently considered
5369 ** to be experimental.  The interface might change in incompatible ways.
5370 ** If this is a problem for you, do not use the interface at this time.
5371 **
5372 ** When the virtual-table mechanism stabilizes, we will declare the
5373 ** interface fixed, support it indefinitely, and remove this comment.
5374 */
5375
5376 /*
5377 ** CAPI3REF: A Handle To An Open BLOB
5378 ** KEYWORDS: {BLOB handle} {BLOB handles}
5379 **
5380 ** An instance of this object represents an open BLOB on which
5381 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5382 ** ^Objects of this type are created by [sqlite3_blob_open()]
5383 ** and destroyed by [sqlite3_blob_close()].
5384 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5385 ** can be used to read or write small subsections of the BLOB.
5386 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5387 */
5388 typedef struct sqlite3_blob sqlite3_blob;
5389
5390 /*
5391 ** CAPI3REF: Open A BLOB For Incremental I/O
5392 **
5393 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5394 ** in row iRow, column zColumn, table zTable in database zDb;
5395 ** in other words, the same BLOB that would be selected by:
5396 **
5397 ** <pre>
5398 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5399 ** </pre>)^
5400 **
5401 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5402 ** and write access. ^If it is zero, the BLOB is opened for read access.
5403 ** ^It is not possible to open a column that is part of an index or primary 
5404 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5405 ** not possible to open a column that is part of a [child key] for writing.
5406 **
5407 ** ^Note that the database name is not the filename that contains
5408 ** the database but rather the symbolic name of the database that
5409 ** appears after the AS keyword when the database is connected using [ATTACH].
5410 ** ^For the main database file, the database name is "main".
5411 ** ^For TEMP tables, the database name is "temp".
5412 **
5413 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5414 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5415 ** to be a null pointer.)^
5416 ** ^This function sets the [database connection] error code and message
5417 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5418 ** functions. ^Note that the *ppBlob variable is always initialized in a
5419 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5420 ** regardless of the success or failure of this routine.
5421 **
5422 ** ^(If the row that a BLOB handle points to is modified by an
5423 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5424 ** then the BLOB handle is marked as "expired".
5425 ** This is true if any column of the row is changed, even a column
5426 ** other than the one the BLOB handle is open on.)^
5427 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5428 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5429 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5430 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5431 ** commit if the transaction continues to completion.)^
5432 **
5433 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5434 ** the opened blob.  ^The size of a blob may not be changed by this
5435 ** interface.  Use the [UPDATE] SQL command to change the size of a
5436 ** blob.
5437 **
5438 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5439 ** and the built-in [zeroblob] SQL function can be used, if desired,
5440 ** to create an empty, zero-filled blob in which to read or write using
5441 ** this interface.
5442 **
5443 ** To avoid a resource leak, every open [BLOB handle] should eventually
5444 ** be released by a call to [sqlite3_blob_close()].
5445 */
5446 SQLITE_API int sqlite3_blob_open(
5447   sqlite3*,
5448   const char *zDb,
5449   const char *zTable,
5450   const char *zColumn,
5451   sqlite3_int64 iRow,
5452   int flags,
5453   sqlite3_blob **ppBlob
5454 );
5455
5456 /*
5457 ** CAPI3REF: Move a BLOB Handle to a New Row
5458 **
5459 ** ^This function is used to move an existing blob handle so that it points
5460 ** to a different row of the same database table. ^The new row is identified
5461 ** by the rowid value passed as the second argument. Only the row can be
5462 ** changed. ^The database, table and column on which the blob handle is open
5463 ** remain the same. Moving an existing blob handle to a new row can be
5464 ** faster than closing the existing handle and opening a new one.
5465 **
5466 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5467 ** it must exist and there must be either a blob or text value stored in
5468 ** the nominated column.)^ ^If the new row is not present in the table, or if
5469 ** it does not contain a blob or text value, or if another error occurs, an
5470 ** SQLite error code is returned and the blob handle is considered aborted.
5471 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5472 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5473 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5474 ** always returns zero.
5475 **
5476 ** ^This function sets the database handle error code and message.
5477 */
5478 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5479
5480 /*
5481 ** CAPI3REF: Close A BLOB Handle
5482 **
5483 ** ^Closes an open [BLOB handle].
5484 **
5485 ** ^Closing a BLOB shall cause the current transaction to commit
5486 ** if there are no other BLOBs, no pending prepared statements, and the
5487 ** database connection is in [autocommit mode].
5488 ** ^If any writes were made to the BLOB, they might be held in cache
5489 ** until the close operation if they will fit.
5490 **
5491 ** ^(Closing the BLOB often forces the changes
5492 ** out to disk and so if any I/O errors occur, they will likely occur
5493 ** at the time when the BLOB is closed.  Any errors that occur during
5494 ** closing are reported as a non-zero return value.)^
5495 **
5496 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5497 ** an error code, the BLOB is still closed.)^
5498 **
5499 ** ^Calling this routine with a null pointer (such as would be returned
5500 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5501 */
5502 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5503
5504 /*
5505 ** CAPI3REF: Return The Size Of An Open BLOB
5506 **
5507 ** ^Returns the size in bytes of the BLOB accessible via the 
5508 ** successfully opened [BLOB handle] in its only argument.  ^The
5509 ** incremental blob I/O routines can only read or overwriting existing
5510 ** blob content; they cannot change the size of a blob.
5511 **
5512 ** This routine only works on a [BLOB handle] which has been created
5513 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5514 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5515 ** to this routine results in undefined and probably undesirable behavior.
5516 */
5517 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5518
5519 /*
5520 ** CAPI3REF: Read Data From A BLOB Incrementally
5521 **
5522 ** ^(This function is used to read data from an open [BLOB handle] into a
5523 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5524 ** from the open BLOB, starting at offset iOffset.)^
5525 **
5526 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5527 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5528 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5529 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5530 ** can be determined using the [sqlite3_blob_bytes()] interface.
5531 **
5532 ** ^An attempt to read from an expired [BLOB handle] fails with an
5533 ** error code of [SQLITE_ABORT].
5534 **
5535 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5536 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5537 **
5538 ** This routine only works on a [BLOB handle] which has been created
5539 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5540 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5541 ** to this routine results in undefined and probably undesirable behavior.
5542 **
5543 ** See also: [sqlite3_blob_write()].
5544 */
5545 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5546
5547 /*
5548 ** CAPI3REF: Write Data Into A BLOB Incrementally
5549 **
5550 ** ^This function is used to write data into an open [BLOB handle] from a
5551 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5552 ** into the open BLOB, starting at offset iOffset.
5553 **
5554 ** ^If the [BLOB handle] passed as the first argument was not opened for
5555 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5556 ** this function returns [SQLITE_READONLY].
5557 **
5558 ** ^This function may only modify the contents of the BLOB; it is
5559 ** not possible to increase the size of a BLOB using this API.
5560 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5561 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5562 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5563 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5564 ** can be determined using the [sqlite3_blob_bytes()] interface.
5565 **
5566 ** ^An attempt to write to an expired [BLOB handle] fails with an
5567 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5568 ** before the [BLOB handle] expired are not rolled back by the
5569 ** expiration of the handle, though of course those changes might
5570 ** have been overwritten by the statement that expired the BLOB handle
5571 ** or by other independent statements.
5572 **
5573 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5574 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5575 **
5576 ** This routine only works on a [BLOB handle] which has been created
5577 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5578 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5579 ** to this routine results in undefined and probably undesirable behavior.
5580 **
5581 ** See also: [sqlite3_blob_read()].
5582 */
5583 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5584
5585 /*
5586 ** CAPI3REF: Virtual File System Objects
5587 **
5588 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5589 ** that SQLite uses to interact
5590 ** with the underlying operating system.  Most SQLite builds come with a
5591 ** single default VFS that is appropriate for the host computer.
5592 ** New VFSes can be registered and existing VFSes can be unregistered.
5593 ** The following interfaces are provided.
5594 **
5595 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5596 ** ^Names are case sensitive.
5597 ** ^Names are zero-terminated UTF-8 strings.
5598 ** ^If there is no match, a NULL pointer is returned.
5599 ** ^If zVfsName is NULL then the default VFS is returned.
5600 **
5601 ** ^New VFSes are registered with sqlite3_vfs_register().
5602 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5603 ** ^The same VFS can be registered multiple times without injury.
5604 ** ^To make an existing VFS into the default VFS, register it again
5605 ** with the makeDflt flag set.  If two different VFSes with the
5606 ** same name are registered, the behavior is undefined.  If a
5607 ** VFS is registered with a name that is NULL or an empty string,
5608 ** then the behavior is undefined.
5609 **
5610 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5611 ** ^(If the default VFS is unregistered, another VFS is chosen as
5612 ** the default.  The choice for the new VFS is arbitrary.)^
5613 */
5614 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5615 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5616 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5617
5618 /*
5619 ** CAPI3REF: Mutexes
5620 **
5621 ** The SQLite core uses these routines for thread
5622 ** synchronization. Though they are intended for internal
5623 ** use by SQLite, code that links against SQLite is
5624 ** permitted to use any of these routines.
5625 **
5626 ** The SQLite source code contains multiple implementations
5627 ** of these mutex routines.  An appropriate implementation
5628 ** is selected automatically at compile-time.  ^(The following
5629 ** implementations are available in the SQLite core:
5630 **
5631 ** <ul>
5632 ** <li>   SQLITE_MUTEX_OS2
5633 ** <li>   SQLITE_MUTEX_PTHREAD
5634 ** <li>   SQLITE_MUTEX_W32
5635 ** <li>   SQLITE_MUTEX_NOOP
5636 ** </ul>)^
5637 **
5638 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5639 ** that does no real locking and is appropriate for use in
5640 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5641 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5642 ** are appropriate for use on OS/2, Unix, and Windows.
5643 **
5644 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5645 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5646 ** implementation is included with the library. In this case the
5647 ** application must supply a custom mutex implementation using the
5648 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5649 ** before calling sqlite3_initialize() or any other public sqlite3_
5650 ** function that calls sqlite3_initialize().)^
5651 **
5652 ** ^The sqlite3_mutex_alloc() routine allocates a new
5653 ** mutex and returns a pointer to it. ^If it returns NULL
5654 ** that means that a mutex could not be allocated.  ^SQLite
5655 ** will unwind its stack and return an error.  ^(The argument
5656 ** to sqlite3_mutex_alloc() is one of these integer constants:
5657 **
5658 ** <ul>
5659 ** <li>  SQLITE_MUTEX_FAST
5660 ** <li>  SQLITE_MUTEX_RECURSIVE
5661 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5662 ** <li>  SQLITE_MUTEX_STATIC_MEM
5663 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5664 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5665 ** <li>  SQLITE_MUTEX_STATIC_LRU
5666 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5667 ** </ul>)^
5668 **
5669 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5670 ** cause sqlite3_mutex_alloc() to create
5671 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5672 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5673 ** The mutex implementation does not need to make a distinction
5674 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5675 ** not want to.  ^SQLite will only request a recursive mutex in
5676 ** cases where it really needs one.  ^If a faster non-recursive mutex
5677 ** implementation is available on the host platform, the mutex subsystem
5678 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5679 **
5680 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5681 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5682 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5683 ** used by the current version of SQLite.  Future versions of SQLite
5684 ** may add additional static mutexes.  Static mutexes are for internal
5685 ** use by SQLite only.  Applications that use SQLite mutexes should
5686 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5687 ** SQLITE_MUTEX_RECURSIVE.
5688 **
5689 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5690 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5691 ** returns a different mutex on every call.  ^But for the static
5692 ** mutex types, the same mutex is returned on every call that has
5693 ** the same type number.
5694 **
5695 ** ^The sqlite3_mutex_free() routine deallocates a previously
5696 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5697 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5698 ** use when they are deallocated.  Attempting to deallocate a static
5699 ** mutex results in undefined behavior.  ^SQLite never deallocates
5700 ** a static mutex.
5701 **
5702 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5703 ** to enter a mutex.  ^If another thread is already within the mutex,
5704 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5705 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5706 ** upon successful entry.  ^(Mutexes created using
5707 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5708 ** In such cases the,
5709 ** mutex must be exited an equal number of times before another thread
5710 ** can enter.)^  ^(If the same thread tries to enter any other
5711 ** kind of mutex more than once, the behavior is undefined.
5712 ** SQLite will never exhibit
5713 ** such behavior in its own use of mutexes.)^
5714 **
5715 ** ^(Some systems (for example, Windows 95) do not support the operation
5716 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5717 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5718 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5719 **
5720 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5721 ** previously entered by the same thread.   ^(The behavior
5722 ** is undefined if the mutex is not currently entered by the
5723 ** calling thread or is not currently allocated.  SQLite will
5724 ** never do either.)^
5725 **
5726 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5727 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5728 ** behave as no-ops.
5729 **
5730 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5731 */
5732 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5733 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5734 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5735 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5736 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5737
5738 /*
5739 ** CAPI3REF: Mutex Methods Object
5740 **
5741 ** An instance of this structure defines the low-level routines
5742 ** used to allocate and use mutexes.
5743 **
5744 ** Usually, the default mutex implementations provided by SQLite are
5745 ** sufficient, however the user has the option of substituting a custom
5746 ** implementation for specialized deployments or systems for which SQLite
5747 ** does not provide a suitable implementation. In this case, the user
5748 ** creates and populates an instance of this structure to pass
5749 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5750 ** Additionally, an instance of this structure can be used as an
5751 ** output variable when querying the system for the current mutex
5752 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5753 **
5754 ** ^The xMutexInit method defined by this structure is invoked as
5755 ** part of system initialization by the sqlite3_initialize() function.
5756 ** ^The xMutexInit routine is called by SQLite exactly once for each
5757 ** effective call to [sqlite3_initialize()].
5758 **
5759 ** ^The xMutexEnd method defined by this structure is invoked as
5760 ** part of system shutdown by the sqlite3_shutdown() function. The
5761 ** implementation of this method is expected to release all outstanding
5762 ** resources obtained by the mutex methods implementation, especially
5763 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5764 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5765 **
5766 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5767 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5768 ** xMutexNotheld) implement the following interfaces (respectively):
5769 **
5770 ** <ul>
5771 **   <li>  [sqlite3_mutex_alloc()] </li>
5772 **   <li>  [sqlite3_mutex_free()] </li>
5773 **   <li>  [sqlite3_mutex_enter()] </li>
5774 **   <li>  [sqlite3_mutex_try()] </li>
5775 **   <li>  [sqlite3_mutex_leave()] </li>
5776 **   <li>  [sqlite3_mutex_held()] </li>
5777 **   <li>  [sqlite3_mutex_notheld()] </li>
5778 ** </ul>)^
5779 **
5780 ** The only difference is that the public sqlite3_XXX functions enumerated
5781 ** above silently ignore any invocations that pass a NULL pointer instead
5782 ** of a valid mutex handle. The implementations of the methods defined
5783 ** by this structure are not required to handle this case, the results
5784 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5785 ** (i.e. it is acceptable to provide an implementation that segfaults if
5786 ** it is passed a NULL pointer).
5787 **
5788 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5789 ** invoke xMutexInit() multiple times within the same process and without
5790 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5791 ** xMutexInit() must be no-ops.
5792 **
5793 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5794 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5795 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5796 ** memory allocation for a fast or recursive mutex.
5797 **
5798 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5799 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5800 ** If xMutexInit fails in any way, it is expected to clean up after itself
5801 ** prior to returning.
5802 */
5803 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5804 struct sqlite3_mutex_methods {
5805   int (*xMutexInit)(void);
5806   int (*xMutexEnd)(void);
5807   sqlite3_mutex *(*xMutexAlloc)(int);
5808   void (*xMutexFree)(sqlite3_mutex *);
5809   void (*xMutexEnter)(sqlite3_mutex *);
5810   int (*xMutexTry)(sqlite3_mutex *);
5811   void (*xMutexLeave)(sqlite3_mutex *);
5812   int (*xMutexHeld)(sqlite3_mutex *);
5813   int (*xMutexNotheld)(sqlite3_mutex *);
5814 };
5815
5816 /*
5817 ** CAPI3REF: Mutex Verification Routines
5818 **
5819 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5820 ** are intended for use inside assert() statements.  ^The SQLite core
5821 ** never uses these routines except inside an assert() and applications
5822 ** are advised to follow the lead of the core.  ^The SQLite core only
5823 ** provides implementations for these routines when it is compiled
5824 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5825 ** are only required to provide these routines if SQLITE_DEBUG is
5826 ** defined and if NDEBUG is not defined.
5827 **
5828 ** ^These routines should return true if the mutex in their argument
5829 ** is held or not held, respectively, by the calling thread.
5830 **
5831 ** ^The implementation is not required to provided versions of these
5832 ** routines that actually work. If the implementation does not provide working
5833 ** versions of these routines, it should at least provide stubs that always
5834 ** return true so that one does not get spurious assertion failures.
5835 **
5836 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5837 ** the routine should return 1.   This seems counter-intuitive since
5838 ** clearly the mutex cannot be held if it does not exist.  But the
5839 ** the reason the mutex does not exist is because the build is not
5840 ** using mutexes.  And we do not want the assert() containing the
5841 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5842 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5843 ** interface should also return 1 when given a NULL pointer.
5844 */
5845 #ifndef NDEBUG
5846 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5847 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5848 #endif
5849
5850 /*
5851 ** CAPI3REF: Mutex Types
5852 **
5853 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5854 ** which is one of these integer constants.
5855 **
5856 ** The set of static mutexes may change from one SQLite release to the
5857 ** next.  Applications that override the built-in mutex logic must be
5858 ** prepared to accommodate additional static mutexes.
5859 */
5860 #define SQLITE_MUTEX_FAST             0
5861 #define SQLITE_MUTEX_RECURSIVE        1
5862 #define SQLITE_MUTEX_STATIC_MASTER    2
5863 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5864 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5865 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5866 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5867 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5868 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
5869 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
5870
5871 /*
5872 ** CAPI3REF: Retrieve the mutex for a database connection
5873 **
5874 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5875 ** serializes access to the [database connection] given in the argument
5876 ** when the [threading mode] is Serialized.
5877 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5878 ** routine returns a NULL pointer.
5879 */
5880 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5881
5882 /*
5883 ** CAPI3REF: Low-Level Control Of Database Files
5884 **
5885 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5886 ** xFileControl method for the [sqlite3_io_methods] object associated
5887 ** with a particular database identified by the second argument. ^The
5888 ** name of the database is "main" for the main database or "temp" for the
5889 ** TEMP database, or the name that appears after the AS keyword for
5890 ** databases that are added using the [ATTACH] SQL command.
5891 ** ^A NULL pointer can be used in place of "main" to refer to the
5892 ** main database file.
5893 ** ^The third and fourth parameters to this routine
5894 ** are passed directly through to the second and third parameters of
5895 ** the xFileControl method.  ^The return value of the xFileControl
5896 ** method becomes the return value of this routine.
5897 **
5898 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5899 ** a pointer to the underlying [sqlite3_file] object to be written into
5900 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
5901 ** case is a short-circuit path which does not actually invoke the
5902 ** underlying sqlite3_io_methods.xFileControl method.
5903 **
5904 ** ^If the second parameter (zDbName) does not match the name of any
5905 ** open database file, then SQLITE_ERROR is returned.  ^This error
5906 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5907 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5908 ** also return SQLITE_ERROR.  There is no way to distinguish between
5909 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5910 ** xFileControl method.
5911 **
5912 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5913 */
5914 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5915
5916 /*
5917 ** CAPI3REF: Testing Interface
5918 **
5919 ** ^The sqlite3_test_control() interface is used to read out internal
5920 ** state of SQLite and to inject faults into SQLite for testing
5921 ** purposes.  ^The first parameter is an operation code that determines
5922 ** the number, meaning, and operation of all subsequent parameters.
5923 **
5924 ** This interface is not for use by applications.  It exists solely
5925 ** for verifying the correct operation of the SQLite library.  Depending
5926 ** on how the SQLite library is compiled, this interface might not exist.
5927 **
5928 ** The details of the operation codes, their meanings, the parameters
5929 ** they take, and what they do are all subject to change without notice.
5930 ** Unlike most of the SQLite API, this function is not guaranteed to
5931 ** operate consistently from one release to the next.
5932 */
5933 SQLITE_API int sqlite3_test_control(int op, ...);
5934
5935 /*
5936 ** CAPI3REF: Testing Interface Operation Codes
5937 **
5938 ** These constants are the valid operation code parameters used
5939 ** as the first argument to [sqlite3_test_control()].
5940 **
5941 ** These parameters and their meanings are subject to change
5942 ** without notice.  These values are for testing purposes only.
5943 ** Applications should not use any of these parameters or the
5944 ** [sqlite3_test_control()] interface.
5945 */
5946 #define SQLITE_TESTCTRL_FIRST                    5
5947 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5948 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5949 #define SQLITE_TESTCTRL_PRNG_RESET               7
5950 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5951 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5952 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5953 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5954 #define SQLITE_TESTCTRL_ASSERT                  12
5955 #define SQLITE_TESTCTRL_ALWAYS                  13
5956 #define SQLITE_TESTCTRL_RESERVE                 14
5957 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5958 #define SQLITE_TESTCTRL_ISKEYWORD               16
5959 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5960 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5961 #define SQLITE_TESTCTRL_LAST                    18
5962
5963 /*
5964 ** CAPI3REF: SQLite Runtime Status
5965 **
5966 ** ^This interface is used to retrieve runtime status information
5967 ** about the performance of SQLite, and optionally to reset various
5968 ** highwater marks.  ^The first argument is an integer code for
5969 ** the specific parameter to measure.  ^(Recognized integer codes
5970 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5971 ** ^The current value of the parameter is returned into *pCurrent.
5972 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5973 ** resetFlag is true, then the highest record value is reset after
5974 ** *pHighwater is written.  ^(Some parameters do not record the highest
5975 ** value.  For those parameters
5976 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5977 ** ^(Other parameters record only the highwater mark and not the current
5978 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5979 **
5980 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5981 ** non-zero [error code] on failure.
5982 **
5983 ** This routine is threadsafe but is not atomic.  This routine can be
5984 ** called while other threads are running the same or different SQLite
5985 ** interfaces.  However the values returned in *pCurrent and
5986 ** *pHighwater reflect the status of SQLite at different points in time
5987 ** and it is possible that another thread might change the parameter
5988 ** in between the times when *pCurrent and *pHighwater are written.
5989 **
5990 ** See also: [sqlite3_db_status()]
5991 */
5992 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5993
5994
5995 /*
5996 ** CAPI3REF: Status Parameters
5997 **
5998 ** These integer constants designate various run-time status parameters
5999 ** that can be returned by [sqlite3_status()].
6000 **
6001 ** <dl>
6002 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6003 ** <dd>This parameter is the current amount of memory checked out
6004 ** using [sqlite3_malloc()], either directly or indirectly.  The
6005 ** figure includes calls made to [sqlite3_malloc()] by the application
6006 ** and internal memory usage by the SQLite library.  Scratch memory
6007 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6008 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6009 ** this parameter.  The amount returned is the sum of the allocation
6010 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6011 **
6012 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6013 ** <dd>This parameter records the largest memory allocation request
6014 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6015 ** internal equivalents).  Only the value returned in the
6016 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6017 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6018 **
6019 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6020 ** <dd>This parameter records the number of separate memory allocations
6021 ** currently checked out.</dd>)^
6022 **
6023 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6024 ** <dd>This parameter returns the number of pages used out of the
6025 ** [pagecache memory allocator] that was configured using 
6026 ** [SQLITE_CONFIG_PAGECACHE].  The
6027 ** value returned is in pages, not in bytes.</dd>)^
6028 **
6029 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6030 ** <dd>This parameter returns the number of bytes of page cache
6031 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6032 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6033 ** returned value includes allocations that overflowed because they
6034 ** where too large (they were larger than the "sz" parameter to
6035 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6036 ** no space was left in the page cache.</dd>)^
6037 **
6038 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6039 ** <dd>This parameter records the largest memory allocation request
6040 ** handed to [pagecache memory allocator].  Only the value returned in the
6041 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6042 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6043 **
6044 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6045 ** <dd>This parameter returns the number of allocations used out of the
6046 ** [scratch memory allocator] configured using
6047 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6048 ** in bytes.  Since a single thread may only have one scratch allocation
6049 ** outstanding at time, this parameter also reports the number of threads
6050 ** using scratch memory at the same time.</dd>)^
6051 **
6052 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6053 ** <dd>This parameter returns the number of bytes of scratch memory
6054 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6055 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6056 ** returned include overflows because the requested allocation was too
6057 ** larger (that is, because the requested allocation was larger than the
6058 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6059 ** slots were available.
6060 ** </dd>)^
6061 **
6062 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6063 ** <dd>This parameter records the largest memory allocation request
6064 ** handed to [scratch memory allocator].  Only the value returned in the
6065 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6066 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6067 **
6068 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6069 ** <dd>This parameter records the deepest parser stack.  It is only
6070 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6071 ** </dl>
6072 **
6073 ** New status parameters may be added from time to time.
6074 */
6075 #define SQLITE_STATUS_MEMORY_USED          0
6076 #define SQLITE_STATUS_PAGECACHE_USED       1
6077 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6078 #define SQLITE_STATUS_SCRATCH_USED         3
6079 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6080 #define SQLITE_STATUS_MALLOC_SIZE          5
6081 #define SQLITE_STATUS_PARSER_STACK         6
6082 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6083 #define SQLITE_STATUS_SCRATCH_SIZE         8
6084 #define SQLITE_STATUS_MALLOC_COUNT         9
6085
6086 /*
6087 ** CAPI3REF: Database Connection Status
6088 **
6089 ** ^This interface is used to retrieve runtime status information 
6090 ** about a single [database connection].  ^The first argument is the
6091 ** database connection object to be interrogated.  ^The second argument
6092 ** is an integer constant, taken from the set of
6093 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6094 ** determines the parameter to interrogate.  The set of 
6095 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6096 ** to grow in future releases of SQLite.
6097 **
6098 ** ^The current value of the requested parameter is written into *pCur
6099 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6100 ** the resetFlg is true, then the highest instantaneous value is
6101 ** reset back down to the current value.
6102 **
6103 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6104 ** non-zero [error code] on failure.
6105 **
6106 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6107 */
6108 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6109
6110 /*
6111 ** CAPI3REF: Status Parameters for database connections
6112 **
6113 ** These constants are the available integer "verbs" that can be passed as
6114 ** the second argument to the [sqlite3_db_status()] interface.
6115 **
6116 ** New verbs may be added in future releases of SQLite. Existing verbs
6117 ** might be discontinued. Applications should check the return code from
6118 ** [sqlite3_db_status()] to make sure that the call worked.
6119 ** The [sqlite3_db_status()] interface will return a non-zero error code
6120 ** if a discontinued or unsupported verb is invoked.
6121 **
6122 ** <dl>
6123 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6124 ** <dd>This parameter returns the number of lookaside memory slots currently
6125 ** checked out.</dd>)^
6126 **
6127 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6128 ** <dd>This parameter returns the number malloc attempts that were 
6129 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6130 ** the current value is always zero.)^
6131 **
6132 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6133 ** <dd>This parameter returns the number malloc attempts that might have
6134 ** been satisfied using lookaside memory but failed due to the amount of
6135 ** memory requested being larger than the lookaside slot size.
6136 ** Only the high-water value is meaningful;
6137 ** the current value is always zero.)^
6138 **
6139 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6140 ** <dd>This parameter returns the number malloc attempts that might have
6141 ** been satisfied using lookaside memory but failed due to all lookaside
6142 ** memory already being in use.
6143 ** Only the high-water value is meaningful;
6144 ** the current value is always zero.)^
6145 **
6146 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6147 ** <dd>This parameter returns the approximate number of of bytes of heap
6148 ** memory used by all pager caches associated with the database connection.)^
6149 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6150 **
6151 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6152 ** <dd>This parameter returns the approximate number of of bytes of heap
6153 ** memory used to store the schema for all databases associated
6154 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6155 ** ^The full amount of memory used by the schemas is reported, even if the
6156 ** schema memory is shared with other database connections due to
6157 ** [shared cache mode] being enabled.
6158 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6159 **
6160 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6161 ** <dd>This parameter returns the approximate number of of bytes of heap
6162 ** and lookaside memory used by all prepared statements associated with
6163 ** the database connection.)^
6164 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6165 ** </dd>
6166 ** </dl>
6167 */
6168 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6169 #define SQLITE_DBSTATUS_CACHE_USED           1
6170 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6171 #define SQLITE_DBSTATUS_STMT_USED            3
6172 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6173 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6174 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6175 #define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6176
6177
6178 /*
6179 ** CAPI3REF: Prepared Statement Status
6180 **
6181 ** ^(Each prepared statement maintains various
6182 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6183 ** of times it has performed specific operations.)^  These counters can
6184 ** be used to monitor the performance characteristics of the prepared
6185 ** statements.  For example, if the number of table steps greatly exceeds
6186 ** the number of table searches or result rows, that would tend to indicate
6187 ** that the prepared statement is using a full table scan rather than
6188 ** an index.  
6189 **
6190 ** ^(This interface is used to retrieve and reset counter values from
6191 ** a [prepared statement].  The first argument is the prepared statement
6192 ** object to be interrogated.  The second argument
6193 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6194 ** to be interrogated.)^
6195 ** ^The current value of the requested counter is returned.
6196 ** ^If the resetFlg is true, then the counter is reset to zero after this
6197 ** interface call returns.
6198 **
6199 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6200 */
6201 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6202
6203 /*
6204 ** CAPI3REF: Status Parameters for prepared statements
6205 **
6206 ** These preprocessor macros define integer codes that name counter
6207 ** values associated with the [sqlite3_stmt_status()] interface.
6208 ** The meanings of the various counters are as follows:
6209 **
6210 ** <dl>
6211 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6212 ** <dd>^This is the number of times that SQLite has stepped forward in
6213 ** a table as part of a full table scan.  Large numbers for this counter
6214 ** may indicate opportunities for performance improvement through 
6215 ** careful use of indices.</dd>
6216 **
6217 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6218 ** <dd>^This is the number of sort operations that have occurred.
6219 ** A non-zero value in this counter may indicate an opportunity to
6220 ** improvement performance through careful use of indices.</dd>
6221 **
6222 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6223 ** <dd>^This is the number of rows inserted into transient indices that
6224 ** were created automatically in order to help joins run faster.
6225 ** A non-zero value in this counter may indicate an opportunity to
6226 ** improvement performance by adding permanent indices that do not
6227 ** need to be reinitialized each time the statement is run.</dd>
6228 **
6229 ** </dl>
6230 */
6231 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6232 #define SQLITE_STMTSTATUS_SORT              2
6233 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6234
6235 /*
6236 ** CAPI3REF: Custom Page Cache Object
6237 **
6238 ** The sqlite3_pcache type is opaque.  It is implemented by
6239 ** the pluggable module.  The SQLite core has no knowledge of
6240 ** its size or internal structure and never deals with the
6241 ** sqlite3_pcache object except by holding and passing pointers
6242 ** to the object.
6243 **
6244 ** See [sqlite3_pcache_methods] for additional information.
6245 */
6246 typedef struct sqlite3_pcache sqlite3_pcache;
6247
6248 /*
6249 ** CAPI3REF: Application Defined Page Cache.
6250 ** KEYWORDS: {page cache}
6251 **
6252 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6253 ** register an alternative page cache implementation by passing in an 
6254 ** instance of the sqlite3_pcache_methods structure.)^
6255 ** In many applications, most of the heap memory allocated by 
6256 ** SQLite is used for the page cache.
6257 ** By implementing a 
6258 ** custom page cache using this API, an application can better control
6259 ** the amount of memory consumed by SQLite, the way in which 
6260 ** that memory is allocated and released, and the policies used to 
6261 ** determine exactly which parts of a database file are cached and for 
6262 ** how long.
6263 **
6264 ** The alternative page cache mechanism is an
6265 ** extreme measure that is only needed by the most demanding applications.
6266 ** The built-in page cache is recommended for most uses.
6267 **
6268 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6269 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6270 ** the application may discard the parameter after the call to
6271 ** [sqlite3_config()] returns.)^
6272 **
6273 ** ^(The xInit() method is called once for each effective 
6274 ** call to [sqlite3_initialize()])^
6275 ** (usually only once during the lifetime of the process). ^(The xInit()
6276 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6277 ** The intent of the xInit() method is to set up global data structures 
6278 ** required by the custom page cache implementation. 
6279 ** ^(If the xInit() method is NULL, then the 
6280 ** built-in default page cache is used instead of the application defined
6281 ** page cache.)^
6282 **
6283 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6284 ** It can be used to clean up 
6285 ** any outstanding resources before process shutdown, if required.
6286 ** ^The xShutdown() method may be NULL.
6287 **
6288 ** ^SQLite automatically serializes calls to the xInit method,
6289 ** so the xInit method need not be threadsafe.  ^The
6290 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6291 ** not need to be threadsafe either.  All other methods must be threadsafe
6292 ** in multithreaded applications.
6293 **
6294 ** ^SQLite will never invoke xInit() more than once without an intervening
6295 ** call to xShutdown().
6296 **
6297 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6298 ** SQLite will typically create one cache instance for each open database file,
6299 ** though this is not guaranteed. ^The
6300 ** first parameter, szPage, is the size in bytes of the pages that must
6301 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6302 ** will the page size of the database file that is to be cached plus an
6303 ** increment (here called "R") of less than 250.  SQLite will use the
6304 ** extra R bytes on each page to store metadata about the underlying
6305 ** database page on disk.  The value of R depends
6306 ** on the SQLite version, the target platform, and how SQLite was compiled.
6307 ** ^(R is constant for a particular build of SQLite. Except, there are two
6308 ** distinct values of R when SQLite is compiled with the proprietary
6309 ** ZIPVFS extension.)^  ^The second argument to
6310 ** xCreate(), bPurgeable, is true if the cache being created will
6311 ** be used to cache database pages of a file stored on disk, or
6312 ** false if it is used for an in-memory database. The cache implementation
6313 ** does not have to do anything special based with the value of bPurgeable;
6314 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6315 ** never invoke xUnpin() except to deliberately delete a page.
6316 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6317 ** false will always have the "discard" flag set to true.  
6318 ** ^Hence, a cache created with bPurgeable false will
6319 ** never contain any unpinned pages.
6320 **
6321 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6322 ** suggested maximum cache-size (number of pages stored by) the cache
6323 ** instance passed as the first argument. This is the value configured using
6324 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6325 ** parameter, the implementation is not required to do anything with this
6326 ** value; it is advisory only.
6327 **
6328 ** The xPagecount() method must return the number of pages currently
6329 ** stored in the cache, both pinned and unpinned.
6330 ** 
6331 ** The xFetch() method locates a page in the cache and returns a pointer to 
6332 ** the page, or a NULL pointer.
6333 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6334 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6335 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page 
6336 ** is considered to be "pinned".
6337 **
6338 ** If the requested page is already in the page cache, then the page cache
6339 ** implementation must return a pointer to the page buffer with its content
6340 ** intact.  If the requested page is not already in the cache, then the
6341 ** cache implementation should use the value of the createFlag
6342 ** parameter to help it determined what action to take:
6343 **
6344 ** <table border=1 width=85% align=center>
6345 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6346 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6347 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6348 **                 Otherwise return NULL.
6349 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6350 **                 NULL if allocating a new page is effectively impossible.
6351 ** </table>
6352 **
6353 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6354 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6355 ** failed.)^  In between the to xFetch() calls, SQLite may
6356 ** attempt to unpin one or more cache pages by spilling the content of
6357 ** pinned pages to disk and synching the operating system disk cache.
6358 **
6359 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6360 ** as its second argument.  If the third parameter, discard, is non-zero,
6361 ** then the page must be evicted from the cache.
6362 ** ^If the discard parameter is
6363 ** zero, then the page may be discarded or retained at the discretion of
6364 ** page cache implementation. ^The page cache implementation
6365 ** may choose to evict unpinned pages at any time.
6366 **
6367 ** The cache must not perform any reference counting. A single 
6368 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6369 ** to xFetch().
6370 **
6371 ** The xRekey() method is used to change the key value associated with the
6372 ** page passed as the second argument. If the cache
6373 ** previously contains an entry associated with newKey, it must be
6374 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6375 ** to be pinned.
6376 **
6377 ** When SQLite calls the xTruncate() method, the cache must discard all
6378 ** existing cache entries with page numbers (keys) greater than or equal
6379 ** to the value of the iLimit parameter passed to xTruncate(). If any
6380 ** of these pages are pinned, they are implicitly unpinned, meaning that
6381 ** they can be safely discarded.
6382 **
6383 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6384 ** All resources associated with the specified cache should be freed. ^After
6385 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6386 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6387 ** functions.
6388 */
6389 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6390 struct sqlite3_pcache_methods {
6391   void *pArg;
6392   int (*xInit)(void*);
6393   void (*xShutdown)(void*);
6394   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6395   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6396   int (*xPagecount)(sqlite3_pcache*);
6397   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6398   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6399   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6400   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6401   void (*xDestroy)(sqlite3_pcache*);
6402 };
6403
6404 /*
6405 ** CAPI3REF: Online Backup Object
6406 **
6407 ** The sqlite3_backup object records state information about an ongoing
6408 ** online backup operation.  ^The sqlite3_backup object is created by
6409 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6410 ** [sqlite3_backup_finish()].
6411 **
6412 ** See Also: [Using the SQLite Online Backup API]
6413 */
6414 typedef struct sqlite3_backup sqlite3_backup;
6415
6416 /*
6417 ** CAPI3REF: Online Backup API.
6418 **
6419 ** The backup API copies the content of one database into another.
6420 ** It is useful either for creating backups of databases or
6421 ** for copying in-memory databases to or from persistent files. 
6422 **
6423 ** See Also: [Using the SQLite Online Backup API]
6424 **
6425 ** ^SQLite holds a write transaction open on the destination database file
6426 ** for the duration of the backup operation.
6427 ** ^The source database is read-locked only while it is being read;
6428 ** it is not locked continuously for the entire backup operation.
6429 ** ^Thus, the backup may be performed on a live source database without
6430 ** preventing other database connections from
6431 ** reading or writing to the source database while the backup is underway.
6432 ** 
6433 ** ^(To perform a backup operation: 
6434 **   <ol>
6435 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6436 **         backup, 
6437 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6438 **         the data between the two databases, and finally
6439 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6440 **         associated with the backup operation. 
6441 **   </ol>)^
6442 ** There should be exactly one call to sqlite3_backup_finish() for each
6443 ** successful call to sqlite3_backup_init().
6444 **
6445 ** <b>sqlite3_backup_init()</b>
6446 **
6447 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6448 ** [database connection] associated with the destination database 
6449 ** and the database name, respectively.
6450 ** ^The database name is "main" for the main database, "temp" for the
6451 ** temporary database, or the name specified after the AS keyword in
6452 ** an [ATTACH] statement for an attached database.
6453 ** ^The S and M arguments passed to 
6454 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6455 ** and database name of the source database, respectively.
6456 ** ^The source and destination [database connections] (parameters S and D)
6457 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6458 ** an error.
6459 **
6460 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6461 ** returned and an error code and error message are stored in the
6462 ** destination [database connection] D.
6463 ** ^The error code and message for the failed call to sqlite3_backup_init()
6464 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6465 ** [sqlite3_errmsg16()] functions.
6466 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6467 ** [sqlite3_backup] object.
6468 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6469 ** sqlite3_backup_finish() functions to perform the specified backup 
6470 ** operation.
6471 **
6472 ** <b>sqlite3_backup_step()</b>
6473 **
6474 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6475 ** the source and destination databases specified by [sqlite3_backup] object B.
6476 ** ^If N is negative, all remaining source pages are copied. 
6477 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6478 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6479 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6480 ** from source to destination, then it returns [SQLITE_DONE].
6481 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6482 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6483 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6484 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6485 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6486 **
6487 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6488 ** <ol>
6489 ** <li> the destination database was opened read-only, or
6490 ** <li> the destination database is using write-ahead-log journaling
6491 ** and the destination and source page sizes differ, or
6492 ** <li> the destination database is an in-memory database and the
6493 ** destination and source page sizes differ.
6494 ** </ol>)^
6495 **
6496 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6497 ** the [sqlite3_busy_handler | busy-handler function]
6498 ** is invoked (if one is specified). ^If the 
6499 ** busy-handler returns non-zero before the lock is available, then 
6500 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6501 ** sqlite3_backup_step() can be retried later. ^If the source
6502 ** [database connection]
6503 ** is being used to write to the source database when sqlite3_backup_step()
6504 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6505 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6506 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6507 ** [SQLITE_READONLY] is returned, then 
6508 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6509 ** errors are considered fatal.)^  The application must accept 
6510 ** that the backup operation has failed and pass the backup operation handle 
6511 ** to the sqlite3_backup_finish() to release associated resources.
6512 **
6513 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6514 ** on the destination file. ^The exclusive lock is not released until either 
6515 ** sqlite3_backup_finish() is called or the backup operation is complete 
6516 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6517 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6518 ** lasts for the duration of the sqlite3_backup_step() call.
6519 ** ^Because the source database is not locked between calls to
6520 ** sqlite3_backup_step(), the source database may be modified mid-way
6521 ** through the backup process.  ^If the source database is modified by an
6522 ** external process or via a database connection other than the one being
6523 ** used by the backup operation, then the backup will be automatically
6524 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6525 ** database is modified by the using the same database connection as is used
6526 ** by the backup operation, then the backup database is automatically
6527 ** updated at the same time.
6528 **
6529 ** <b>sqlite3_backup_finish()</b>
6530 **
6531 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6532 ** application wishes to abandon the backup operation, the application
6533 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6534 ** ^The sqlite3_backup_finish() interfaces releases all
6535 ** resources associated with the [sqlite3_backup] object. 
6536 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6537 ** active write-transaction on the destination database is rolled back.
6538 ** The [sqlite3_backup] object is invalid
6539 ** and may not be used following a call to sqlite3_backup_finish().
6540 **
6541 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6542 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6543 ** sqlite3_backup_step() completed.
6544 ** ^If an out-of-memory condition or IO error occurred during any prior
6545 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6546 ** sqlite3_backup_finish() returns the corresponding [error code].
6547 **
6548 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6549 ** is not a permanent error and does not affect the return value of
6550 ** sqlite3_backup_finish().
6551 **
6552 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6553 **
6554 ** ^Each call to sqlite3_backup_step() sets two values inside
6555 ** the [sqlite3_backup] object: the number of pages still to be backed
6556 ** up and the total number of pages in the source database file.
6557 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6558 ** retrieve these two values, respectively.
6559 **
6560 ** ^The values returned by these functions are only updated by
6561 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6562 ** operation, then the values are not updated to account for any extra
6563 ** pages that need to be updated or the size of the source database file
6564 ** changing.
6565 **
6566 ** <b>Concurrent Usage of Database Handles</b>
6567 **
6568 ** ^The source [database connection] may be used by the application for other
6569 ** purposes while a backup operation is underway or being initialized.
6570 ** ^If SQLite is compiled and configured to support threadsafe database
6571 ** connections, then the source database connection may be used concurrently
6572 ** from within other threads.
6573 **
6574 ** However, the application must guarantee that the destination 
6575 ** [database connection] is not passed to any other API (by any thread) after 
6576 ** sqlite3_backup_init() is called and before the corresponding call to
6577 ** sqlite3_backup_finish().  SQLite does not currently check to see
6578 ** if the application incorrectly accesses the destination [database connection]
6579 ** and so no error code is reported, but the operations may malfunction
6580 ** nevertheless.  Use of the destination database connection while a
6581 ** backup is in progress might also also cause a mutex deadlock.
6582 **
6583 ** If running in [shared cache mode], the application must
6584 ** guarantee that the shared cache used by the destination database
6585 ** is not accessed while the backup is running. In practice this means
6586 ** that the application must guarantee that the disk file being 
6587 ** backed up to is not accessed by any connection within the process,
6588 ** not just the specific connection that was passed to sqlite3_backup_init().
6589 **
6590 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6591 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6592 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6593 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6594 ** same time as another thread is invoking sqlite3_backup_step() it is
6595 ** possible that they return invalid values.
6596 */
6597 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6598   sqlite3 *pDest,                        /* Destination database handle */
6599   const char *zDestName,                 /* Destination database name */
6600   sqlite3 *pSource,                      /* Source database handle */
6601   const char *zSourceName                /* Source database name */
6602 );
6603 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6604 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6605 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6606 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6607
6608 /*
6609 ** CAPI3REF: Unlock Notification
6610 **
6611 ** ^When running in shared-cache mode, a database operation may fail with
6612 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6613 ** individual tables within the shared-cache cannot be obtained. See
6614 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6615 ** ^This API may be used to register a callback that SQLite will invoke 
6616 ** when the connection currently holding the required lock relinquishes it.
6617 ** ^This API is only available if the library was compiled with the
6618 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6619 **
6620 ** See Also: [Using the SQLite Unlock Notification Feature].
6621 **
6622 ** ^Shared-cache locks are released when a database connection concludes
6623 ** its current transaction, either by committing it or rolling it back. 
6624 **
6625 ** ^When a connection (known as the blocked connection) fails to obtain a
6626 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6627 ** identity of the database connection (the blocking connection) that
6628 ** has locked the required resource is stored internally. ^After an 
6629 ** application receives an SQLITE_LOCKED error, it may call the
6630 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6631 ** the first argument to register for a callback that will be invoked
6632 ** when the blocking connections current transaction is concluded. ^The
6633 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6634 ** call that concludes the blocking connections transaction.
6635 **
6636 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6637 ** there is a chance that the blocking connection will have already
6638 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6639 ** If this happens, then the specified callback is invoked immediately,
6640 ** from within the call to sqlite3_unlock_notify().)^
6641 **
6642 ** ^If the blocked connection is attempting to obtain a write-lock on a
6643 ** shared-cache table, and more than one other connection currently holds
6644 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6645 ** the other connections to use as the blocking connection.
6646 **
6647 ** ^(There may be at most one unlock-notify callback registered by a 
6648 ** blocked connection. If sqlite3_unlock_notify() is called when the
6649 ** blocked connection already has a registered unlock-notify callback,
6650 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6651 ** called with a NULL pointer as its second argument, then any existing
6652 ** unlock-notify callback is canceled. ^The blocked connections 
6653 ** unlock-notify callback may also be canceled by closing the blocked
6654 ** connection using [sqlite3_close()].
6655 **
6656 ** The unlock-notify callback is not reentrant. If an application invokes
6657 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6658 ** crash or deadlock may be the result.
6659 **
6660 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6661 ** returns SQLITE_OK.
6662 **
6663 ** <b>Callback Invocation Details</b>
6664 **
6665 ** When an unlock-notify callback is registered, the application provides a 
6666 ** single void* pointer that is passed to the callback when it is invoked.
6667 ** However, the signature of the callback function allows SQLite to pass
6668 ** it an array of void* context pointers. The first argument passed to
6669 ** an unlock-notify callback is a pointer to an array of void* pointers,
6670 ** and the second is the number of entries in the array.
6671 **
6672 ** When a blocking connections transaction is concluded, there may be
6673 ** more than one blocked connection that has registered for an unlock-notify
6674 ** callback. ^If two or more such blocked connections have specified the
6675 ** same callback function, then instead of invoking the callback function
6676 ** multiple times, it is invoked once with the set of void* context pointers
6677 ** specified by the blocked connections bundled together into an array.
6678 ** This gives the application an opportunity to prioritize any actions 
6679 ** related to the set of unblocked database connections.
6680 **
6681 ** <b>Deadlock Detection</b>
6682 **
6683 ** Assuming that after registering for an unlock-notify callback a 
6684 ** database waits for the callback to be issued before taking any further
6685 ** action (a reasonable assumption), then using this API may cause the
6686 ** application to deadlock. For example, if connection X is waiting for
6687 ** connection Y's transaction to be concluded, and similarly connection
6688 ** Y is waiting on connection X's transaction, then neither connection
6689 ** will proceed and the system may remain deadlocked indefinitely.
6690 **
6691 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6692 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6693 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6694 ** unlock-notify callback is registered. The system is said to be in
6695 ** a deadlocked state if connection A has registered for an unlock-notify
6696 ** callback on the conclusion of connection B's transaction, and connection
6697 ** B has itself registered for an unlock-notify callback when connection
6698 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6699 ** the system is also considered to be deadlocked if connection B has
6700 ** registered for an unlock-notify callback on the conclusion of connection
6701 ** C's transaction, where connection C is waiting on connection A. ^Any
6702 ** number of levels of indirection are allowed.
6703 **
6704 ** <b>The "DROP TABLE" Exception</b>
6705 **
6706 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6707 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6708 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6709 ** SQLite checks if there are any currently executing SELECT statements
6710 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6711 ** returned. In this case there is no "blocking connection", so invoking
6712 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6713 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6714 ** or "DROP INDEX" query, an infinite loop might be the result.
6715 **
6716 ** One way around this problem is to check the extended error code returned
6717 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6718 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6719 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6720 ** SQLITE_LOCKED.)^
6721 */
6722 SQLITE_API int sqlite3_unlock_notify(
6723   sqlite3 *pBlocked,                          /* Waiting connection */
6724   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6725   void *pNotifyArg                            /* Argument to pass to xNotify */
6726 );
6727
6728
6729 /*
6730 ** CAPI3REF: String Comparison
6731 **
6732 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6733 ** compare the contents of two buffers containing UTF-8 strings in a
6734 ** case-independent fashion, using the same definition of case independence 
6735 ** that SQLite uses internally when comparing identifiers.
6736 */
6737 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6738
6739 /*
6740 ** CAPI3REF: Error Logging Interface
6741 **
6742 ** ^The [sqlite3_log()] interface writes a message into the error log
6743 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6744 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6745 ** used with [sqlite3_snprintf()] to generate the final output string.
6746 **
6747 ** The sqlite3_log() interface is intended for use by extensions such as
6748 ** virtual tables, collating functions, and SQL functions.  While there is
6749 ** nothing to prevent an application from calling sqlite3_log(), doing so
6750 ** is considered bad form.
6751 **
6752 ** The zFormat string must not be NULL.
6753 **
6754 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6755 ** will not use dynamically allocated memory.  The log message is stored in
6756 ** a fixed-length buffer on the stack.  If the log message is longer than
6757 ** a few hundred characters, it will be truncated to the length of the
6758 ** buffer.
6759 */
6760 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6761
6762 /*
6763 ** CAPI3REF: Write-Ahead Log Commit Hook
6764 **
6765 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6766 ** will be invoked each time a database connection commits data to a
6767 ** [write-ahead log] (i.e. whenever a transaction is committed in
6768 ** [journal_mode | journal_mode=WAL mode]). 
6769 **
6770 ** ^The callback is invoked by SQLite after the commit has taken place and 
6771 ** the associated write-lock on the database released, so the implementation 
6772 ** may read, write or [checkpoint] the database as required.
6773 **
6774 ** ^The first parameter passed to the callback function when it is invoked
6775 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6776 ** registering the callback. ^The second is a copy of the database handle.
6777 ** ^The third parameter is the name of the database that was written to -
6778 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6779 ** is the number of pages currently in the write-ahead log file,
6780 ** including those that were just committed.
6781 **
6782 ** The callback function should normally return [SQLITE_OK].  ^If an error
6783 ** code is returned, that error will propagate back up through the
6784 ** SQLite code base to cause the statement that provoked the callback
6785 ** to report an error, though the commit will have still occurred. If the
6786 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6787 ** that does not correspond to any valid SQLite error code, the results
6788 ** are undefined.
6789 **
6790 ** A single database handle may have at most a single write-ahead log callback 
6791 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6792 ** previously registered write-ahead log callback. ^Note that the
6793 ** [sqlite3_wal_autocheckpoint()] interface and the
6794 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6795 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6796 */
6797 SQLITE_API void *sqlite3_wal_hook(
6798   sqlite3*, 
6799   int(*)(void *,sqlite3*,const char*,int),
6800   void*
6801 );
6802
6803 /*
6804 ** CAPI3REF: Configure an auto-checkpoint
6805 **
6806 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6807 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6808 ** to automatically [checkpoint]
6809 ** after committing a transaction if there are N or
6810 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6811 ** a negative value as the nFrame parameter disables automatic
6812 ** checkpoints entirely.
6813 **
6814 ** ^The callback registered by this function replaces any existing callback
6815 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6816 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6817 ** configured by this function.
6818 **
6819 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6820 ** from SQL.
6821 **
6822 ** ^Every new [database connection] defaults to having the auto-checkpoint
6823 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
6824 ** pages.  The use of this interface
6825 ** is only necessary if the default setting is found to be suboptimal
6826 ** for a particular application.
6827 */
6828 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6829
6830 /*
6831 ** CAPI3REF: Checkpoint a database
6832 **
6833 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6834 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6835 ** empty string, then a checkpoint is run on all databases of
6836 ** connection D.  ^If the database connection D is not in
6837 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6838 **
6839 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6840 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6841 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6842 ** run whenever the WAL reaches a certain size threshold.
6843 **
6844 ** See also: [sqlite3_wal_checkpoint_v2()]
6845 */
6846 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6847
6848 /*
6849 ** CAPI3REF: Checkpoint a database
6850 **
6851 ** Run a checkpoint operation on WAL database zDb attached to database 
6852 ** handle db. The specific operation is determined by the value of the 
6853 ** eMode parameter:
6854 **
6855 ** <dl>
6856 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
6857 **   Checkpoint as many frames as possible without waiting for any database 
6858 **   readers or writers to finish. Sync the db file if all frames in the log
6859 **   are checkpointed. This mode is the same as calling 
6860 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
6861 **
6862 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
6863 **   This mode blocks (calls the busy-handler callback) until there is no
6864 **   database writer and all readers are reading from the most recent database
6865 **   snapshot. It then checkpoints all frames in the log file and syncs the
6866 **   database file. This call blocks database writers while it is running,
6867 **   but not database readers.
6868 **
6869 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
6870 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
6871 **   checkpointing the log file it blocks (calls the busy-handler callback)
6872 **   until all readers are reading from the database file only. This ensures 
6873 **   that the next client to write to the database file restarts the log file 
6874 **   from the beginning. This call blocks database writers while it is running,
6875 **   but not database readers.
6876 ** </dl>
6877 **
6878 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
6879 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
6880 ** the total number of checkpointed frames (including any that were already
6881 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
6882 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
6883 ** If no values are available because of an error, they are both set to -1
6884 ** before returning to communicate this to the caller.
6885 **
6886 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
6887 ** any other process is running a checkpoint operation at the same time, the 
6888 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
6889 ** busy-handler configured, it will not be invoked in this case.
6890 **
6891 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
6892 ** "writer" lock on the database file. If the writer lock cannot be obtained
6893 ** immediately, and a busy-handler is configured, it is invoked and the writer
6894 ** lock retried until either the busy-handler returns 0 or the lock is
6895 ** successfully obtained. The busy-handler is also invoked while waiting for
6896 ** database readers as described above. If the busy-handler returns 0 before
6897 ** the writer lock is obtained or while waiting for database readers, the
6898 ** checkpoint operation proceeds from that point in the same way as 
6899 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
6900 ** without blocking any further. SQLITE_BUSY is returned in this case.
6901 **
6902 ** If parameter zDb is NULL or points to a zero length string, then the
6903 ** specified operation is attempted on all WAL databases. In this case the
6904 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
6905 ** an SQLITE_BUSY error is encountered when processing one or more of the 
6906 ** attached WAL databases, the operation is still attempted on any remaining 
6907 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
6908 ** error occurs while processing an attached database, processing is abandoned 
6909 ** and the error code returned to the caller immediately. If no error 
6910 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
6911 ** databases, SQLITE_OK is returned.
6912 **
6913 ** If database zDb is the name of an attached database that is not in WAL
6914 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
6915 ** zDb is not NULL (or a zero length string) and is not the name of any
6916 ** attached database, SQLITE_ERROR is returned to the caller.
6917 */
6918 SQLITE_API int sqlite3_wal_checkpoint_v2(
6919   sqlite3 *db,                    /* Database handle */
6920   const char *zDb,                /* Name of attached database (or NULL) */
6921   int eMode,                      /* SQLITE_CHECKPOINT_* value */
6922   int *pnLog,                     /* OUT: Size of WAL log in frames */
6923   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
6924 );
6925
6926 /*
6927 ** CAPI3REF: Checkpoint operation parameters
6928 **
6929 ** These constants can be used as the 3rd parameter to
6930 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
6931 ** documentation for additional information about the meaning and use of
6932 ** each of these values.
6933 */
6934 #define SQLITE_CHECKPOINT_PASSIVE 0
6935 #define SQLITE_CHECKPOINT_FULL    1
6936 #define SQLITE_CHECKPOINT_RESTART 2
6937
6938
6939 /*
6940 ** Undo the hack that converts floating point types to integer for
6941 ** builds on processors without floating point support.
6942 */
6943 #ifdef SQLITE_OMIT_FLOATING_POINT
6944 # undef double
6945 #endif
6946
6947 #if 0
6948 }  /* End of the 'extern "C"' block */
6949 #endif
6950 #endif
6951
6952 /*
6953 ** 2010 August 30
6954 **
6955 ** The author disclaims copyright to this source code.  In place of
6956 ** a legal notice, here is a blessing:
6957 **
6958 **    May you do good and not evil.
6959 **    May you find forgiveness for yourself and forgive others.
6960 **    May you share freely, never taking more than you give.
6961 **
6962 *************************************************************************
6963 */
6964
6965 #ifndef _SQLITE3RTREE_H_
6966 #define _SQLITE3RTREE_H_
6967
6968
6969 #if 0
6970 extern "C" {
6971 #endif
6972
6973 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6974
6975 /*
6976 ** Register a geometry callback named zGeom that can be used as part of an
6977 ** R-Tree geometry query as follows:
6978 **
6979 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6980 */
6981 SQLITE_API int sqlite3_rtree_geometry_callback(
6982   sqlite3 *db,
6983   const char *zGeom,
6984   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6985   void *pContext
6986 );
6987
6988
6989 /*
6990 ** A pointer to a structure of the following type is passed as the first
6991 ** argument to callbacks registered using rtree_geometry_callback().
6992 */
6993 struct sqlite3_rtree_geometry {
6994   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
6995   int nParam;                     /* Size of array aParam[] */
6996   double *aParam;                 /* Parameters passed to SQL geom function */
6997   void *pUser;                    /* Callback implementation user data */
6998   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
6999 };
7000
7001
7002 #if 0
7003 }  /* end of the 'extern "C"' block */
7004 #endif
7005
7006 #endif  /* ifndef _SQLITE3RTREE_H_ */
7007
7008
7009 /************** End of sqlite3.h *********************************************/
7010 /************** Continuing where we left off in sqliteInt.h ******************/
7011 /************** Include hash.h in the middle of sqliteInt.h ******************/
7012 /************** Begin file hash.h ********************************************/
7013 /*
7014 ** 2001 September 22
7015 **
7016 ** The author disclaims copyright to this source code.  In place of
7017 ** a legal notice, here is a blessing:
7018 **
7019 **    May you do good and not evil.
7020 **    May you find forgiveness for yourself and forgive others.
7021 **    May you share freely, never taking more than you give.
7022 **
7023 *************************************************************************
7024 ** This is the header file for the generic hash-table implemenation
7025 ** used in SQLite.
7026 */
7027 #ifndef _SQLITE_HASH_H_
7028 #define _SQLITE_HASH_H_
7029
7030 /* Forward declarations of structures. */
7031 typedef struct Hash Hash;
7032 typedef struct HashElem HashElem;
7033
7034 /* A complete hash table is an instance of the following structure.
7035 ** The internals of this structure are intended to be opaque -- client
7036 ** code should not attempt to access or modify the fields of this structure
7037 ** directly.  Change this structure only by using the routines below.
7038 ** However, some of the "procedures" and "functions" for modifying and
7039 ** accessing this structure are really macros, so we can't really make
7040 ** this structure opaque.
7041 **
7042 ** All elements of the hash table are on a single doubly-linked list.
7043 ** Hash.first points to the head of this list.
7044 **
7045 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7046 ** the global doubly-linked list.  The contents of the bucket are the
7047 ** element pointed to plus the next _ht.count-1 elements in the list.
7048 **
7049 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7050 ** by a linear search of the global list.  For small tables, the 
7051 ** Hash.ht table is never allocated because if there are few elements
7052 ** in the table, it is faster to do a linear search than to manage
7053 ** the hash table.
7054 */
7055 struct Hash {
7056   unsigned int htsize;      /* Number of buckets in the hash table */
7057   unsigned int count;       /* Number of entries in this table */
7058   HashElem *first;          /* The first element of the array */
7059   struct _ht {              /* the hash table */
7060     int count;                 /* Number of entries with this hash */
7061     HashElem *chain;           /* Pointer to first entry with this hash */
7062   } *ht;
7063 };
7064
7065 /* Each element in the hash table is an instance of the following 
7066 ** structure.  All elements are stored on a single doubly-linked list.
7067 **
7068 ** Again, this structure is intended to be opaque, but it can't really
7069 ** be opaque because it is used by macros.
7070 */
7071 struct HashElem {
7072   HashElem *next, *prev;       /* Next and previous elements in the table */
7073   void *data;                  /* Data associated with this element */
7074   const char *pKey; int nKey;  /* Key associated with this element */
7075 };
7076
7077 /*
7078 ** Access routines.  To delete, insert a NULL pointer.
7079 */
7080 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7081 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7082 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7083 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7084
7085 /*
7086 ** Macros for looping over all elements of a hash table.  The idiom is
7087 ** like this:
7088 **
7089 **   Hash h;
7090 **   HashElem *p;
7091 **   ...
7092 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7093 **     SomeStructure *pData = sqliteHashData(p);
7094 **     // do something with pData
7095 **   }
7096 */
7097 #define sqliteHashFirst(H)  ((H)->first)
7098 #define sqliteHashNext(E)   ((E)->next)
7099 #define sqliteHashData(E)   ((E)->data)
7100 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7101 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7102
7103 /*
7104 ** Number of entries in a hash table
7105 */
7106 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7107
7108 #endif /* _SQLITE_HASH_H_ */
7109
7110 /************** End of hash.h ************************************************/
7111 /************** Continuing where we left off in sqliteInt.h ******************/
7112 /************** Include parse.h in the middle of sqliteInt.h *****************/
7113 /************** Begin file parse.h *******************************************/
7114 #define TK_SEMI                            1
7115 #define TK_EXPLAIN                         2
7116 #define TK_QUERY                           3
7117 #define TK_PLAN                            4
7118 #define TK_BEGIN                           5
7119 #define TK_TRANSACTION                     6
7120 #define TK_DEFERRED                        7
7121 #define TK_IMMEDIATE                       8
7122 #define TK_EXCLUSIVE                       9
7123 #define TK_COMMIT                         10
7124 #define TK_END                            11
7125 #define TK_ROLLBACK                       12
7126 #define TK_SAVEPOINT                      13
7127 #define TK_RELEASE                        14
7128 #define TK_TO                             15
7129 #define TK_TABLE                          16
7130 #define TK_CREATE                         17
7131 #define TK_IF                             18
7132 #define TK_NOT                            19
7133 #define TK_EXISTS                         20
7134 #define TK_TEMP                           21
7135 #define TK_LP                             22
7136 #define TK_RP                             23
7137 #define TK_AS                             24
7138 #define TK_COMMA                          25
7139 #define TK_ID                             26
7140 #define TK_INDEXED                        27
7141 #define TK_ABORT                          28
7142 #define TK_ACTION                         29
7143 #define TK_AFTER                          30
7144 #define TK_ANALYZE                        31
7145 #define TK_ASC                            32
7146 #define TK_ATTACH                         33
7147 #define TK_BEFORE                         34
7148 #define TK_BY                             35
7149 #define TK_CASCADE                        36
7150 #define TK_CAST                           37
7151 #define TK_COLUMNKW                       38
7152 #define TK_CONFLICT                       39
7153 #define TK_DATABASE                       40
7154 #define TK_DESC                           41
7155 #define TK_DETACH                         42
7156 #define TK_EACH                           43
7157 #define TK_FAIL                           44
7158 #define TK_FOR                            45
7159 #define TK_IGNORE                         46
7160 #define TK_INITIALLY                      47
7161 #define TK_INSTEAD                        48
7162 #define TK_LIKE_KW                        49
7163 #define TK_MATCH                          50
7164 #define TK_NO                             51
7165 #define TK_KEY                            52
7166 #define TK_OF                             53
7167 #define TK_OFFSET                         54
7168 #define TK_PRAGMA                         55
7169 #define TK_RAISE                          56
7170 #define TK_REPLACE                        57
7171 #define TK_RESTRICT                       58
7172 #define TK_ROW                            59
7173 #define TK_TRIGGER                        60
7174 #define TK_VACUUM                         61
7175 #define TK_VIEW                           62
7176 #define TK_VIRTUAL                        63
7177 #define TK_REINDEX                        64
7178 #define TK_RENAME                         65
7179 #define TK_CTIME_KW                       66
7180 #define TK_ANY                            67
7181 #define TK_OR                             68
7182 #define TK_AND                            69
7183 #define TK_IS                             70
7184 #define TK_BETWEEN                        71
7185 #define TK_IN                             72
7186 #define TK_ISNULL                         73
7187 #define TK_NOTNULL                        74
7188 #define TK_NE                             75
7189 #define TK_EQ                             76
7190 #define TK_GT                             77
7191 #define TK_LE                             78
7192 #define TK_LT                             79
7193 #define TK_GE                             80
7194 #define TK_ESCAPE                         81
7195 #define TK_BITAND                         82
7196 #define TK_BITOR                          83
7197 #define TK_LSHIFT                         84
7198 #define TK_RSHIFT                         85
7199 #define TK_PLUS                           86
7200 #define TK_MINUS                          87
7201 #define TK_STAR                           88
7202 #define TK_SLASH                          89
7203 #define TK_REM                            90
7204 #define TK_CONCAT                         91
7205 #define TK_COLLATE                        92
7206 #define TK_BITNOT                         93
7207 #define TK_STRING                         94
7208 #define TK_JOIN_KW                        95
7209 #define TK_CONSTRAINT                     96
7210 #define TK_DEFAULT                        97
7211 #define TK_NULL                           98
7212 #define TK_PRIMARY                        99
7213 #define TK_UNIQUE                         100
7214 #define TK_CHECK                          101
7215 #define TK_REFERENCES                     102
7216 #define TK_AUTOINCR                       103
7217 #define TK_ON                             104
7218 #define TK_INSERT                         105
7219 #define TK_DELETE                         106
7220 #define TK_UPDATE                         107
7221 #define TK_SET                            108
7222 #define TK_DEFERRABLE                     109
7223 #define TK_FOREIGN                        110
7224 #define TK_DROP                           111
7225 #define TK_UNION                          112
7226 #define TK_ALL                            113
7227 #define TK_EXCEPT                         114
7228 #define TK_INTERSECT                      115
7229 #define TK_SELECT                         116
7230 #define TK_DISTINCT                       117
7231 #define TK_DOT                            118
7232 #define TK_FROM                           119
7233 #define TK_JOIN                           120
7234 #define TK_USING                          121
7235 #define TK_ORDER                          122
7236 #define TK_GROUP                          123
7237 #define TK_HAVING                         124
7238 #define TK_LIMIT                          125
7239 #define TK_WHERE                          126
7240 #define TK_INTO                           127
7241 #define TK_VALUES                         128
7242 #define TK_INTEGER                        129
7243 #define TK_FLOAT                          130
7244 #define TK_BLOB                           131
7245 #define TK_REGISTER                       132
7246 #define TK_VARIABLE                       133
7247 #define TK_CASE                           134
7248 #define TK_WHEN                           135
7249 #define TK_THEN                           136
7250 #define TK_ELSE                           137
7251 #define TK_INDEX                          138
7252 #define TK_ALTER                          139
7253 #define TK_ADD                            140
7254 #define TK_TO_TEXT                        141
7255 #define TK_TO_BLOB                        142
7256 #define TK_TO_NUMERIC                     143
7257 #define TK_TO_INT                         144
7258 #define TK_TO_REAL                        145
7259 #define TK_ISNOT                          146
7260 #define TK_END_OF_FILE                    147
7261 #define TK_ILLEGAL                        148
7262 #define TK_SPACE                          149
7263 #define TK_UNCLOSED_STRING                150
7264 #define TK_FUNCTION                       151
7265 #define TK_COLUMN                         152
7266 #define TK_AGG_FUNCTION                   153
7267 #define TK_AGG_COLUMN                     154
7268 #define TK_CONST_FUNC                     155
7269 #define TK_UMINUS                         156
7270 #define TK_UPLUS                          157
7271
7272 /************** End of parse.h ***********************************************/
7273 /************** Continuing where we left off in sqliteInt.h ******************/
7274 #include <stdio.h>
7275 #include <stdlib.h>
7276 #include <string.h>
7277 #include <assert.h>
7278 #include <stddef.h>
7279
7280 /*
7281 ** If compiling for a processor that lacks floating point support,
7282 ** substitute integer for floating-point
7283 */
7284 #ifdef SQLITE_OMIT_FLOATING_POINT
7285 # define double sqlite_int64
7286 # define float sqlite_int64
7287 # define LONGDOUBLE_TYPE sqlite_int64
7288 # ifndef SQLITE_BIG_DBL
7289 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7290 # endif
7291 # define SQLITE_OMIT_DATETIME_FUNCS 1
7292 # define SQLITE_OMIT_TRACE 1
7293 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7294 # undef SQLITE_HAVE_ISNAN
7295 #endif
7296 #ifndef SQLITE_BIG_DBL
7297 # define SQLITE_BIG_DBL (1e99)
7298 #endif
7299
7300 /*
7301 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7302 ** afterward. Having this macro allows us to cause the C compiler 
7303 ** to omit code used by TEMP tables without messy #ifndef statements.
7304 */
7305 #ifdef SQLITE_OMIT_TEMPDB
7306 #define OMIT_TEMPDB 1
7307 #else
7308 #define OMIT_TEMPDB 0
7309 #endif
7310
7311 /*
7312 ** The "file format" number is an integer that is incremented whenever
7313 ** the VDBE-level file format changes.  The following macros define the
7314 ** the default file format for new databases and the maximum file format
7315 ** that the library can read.
7316 */
7317 #define SQLITE_MAX_FILE_FORMAT 4
7318 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7319 # define SQLITE_DEFAULT_FILE_FORMAT 1
7320 #endif
7321
7322 /*
7323 ** Determine whether triggers are recursive by default.  This can be
7324 ** changed at run-time using a pragma.
7325 */
7326 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7327 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7328 #endif
7329
7330 /*
7331 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7332 ** on the command-line
7333 */
7334 #ifndef SQLITE_TEMP_STORE
7335 # define SQLITE_TEMP_STORE 1
7336 #endif
7337
7338 /*
7339 ** GCC does not define the offsetof() macro so we'll have to do it
7340 ** ourselves.
7341 */
7342 #ifndef offsetof
7343 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7344 #endif
7345
7346 /*
7347 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7348 ** not, there are still machines out there that use EBCDIC.)
7349 */
7350 #if 'A' == '\301'
7351 # define SQLITE_EBCDIC 1
7352 #else
7353 # define SQLITE_ASCII 1
7354 #endif
7355
7356 /*
7357 ** Integers of known sizes.  These typedefs might change for architectures
7358 ** where the sizes very.  Preprocessor macros are available so that the
7359 ** types can be conveniently redefined at compile-type.  Like this:
7360 **
7361 **         cc '-DUINTPTR_TYPE=long long int' ...
7362 */
7363 #ifndef UINT32_TYPE
7364 # ifdef HAVE_UINT32_T
7365 #  define UINT32_TYPE uint32_t
7366 # else
7367 #  define UINT32_TYPE unsigned int
7368 # endif
7369 #endif
7370 #ifndef UINT16_TYPE
7371 # ifdef HAVE_UINT16_T
7372 #  define UINT16_TYPE uint16_t
7373 # else
7374 #  define UINT16_TYPE unsigned short int
7375 # endif
7376 #endif
7377 #ifndef INT16_TYPE
7378 # ifdef HAVE_INT16_T
7379 #  define INT16_TYPE int16_t
7380 # else
7381 #  define INT16_TYPE short int
7382 # endif
7383 #endif
7384 #ifndef UINT8_TYPE
7385 # ifdef HAVE_UINT8_T
7386 #  define UINT8_TYPE uint8_t
7387 # else
7388 #  define UINT8_TYPE unsigned char
7389 # endif
7390 #endif
7391 #ifndef INT8_TYPE
7392 # ifdef HAVE_INT8_T
7393 #  define INT8_TYPE int8_t
7394 # else
7395 #  define INT8_TYPE signed char
7396 # endif
7397 #endif
7398 #ifndef LONGDOUBLE_TYPE
7399 # define LONGDOUBLE_TYPE long double
7400 #endif
7401 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7402 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7403 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7404 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7405 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7406 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7407 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7408
7409 /*
7410 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7411 ** that can be stored in a u32 without loss of data.  The value
7412 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7413 ** have to specify the value in the less intuitive manner shown:
7414 */
7415 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7416
7417 /*
7418 ** Macros to determine whether the machine is big or little endian,
7419 ** evaluated at runtime.
7420 */
7421 #ifdef SQLITE_AMALGAMATION
7422 SQLITE_PRIVATE const int sqlite3one = 1;
7423 #else
7424 SQLITE_PRIVATE const int sqlite3one;
7425 #endif
7426 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7427                              || defined(__x86_64) || defined(__x86_64__)
7428 # define SQLITE_BIGENDIAN    0
7429 # define SQLITE_LITTLEENDIAN 1
7430 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7431 #else
7432 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7433 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7434 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7435 #endif
7436
7437 /*
7438 ** Constants for the largest and smallest possible 64-bit signed integers.
7439 ** These macros are designed to work correctly on both 32-bit and 64-bit
7440 ** compilers.
7441 */
7442 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7443 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7444
7445 /* 
7446 ** Round up a number to the next larger multiple of 8.  This is used
7447 ** to force 8-byte alignment on 64-bit architectures.
7448 */
7449 #define ROUND8(x)     (((x)+7)&~7)
7450
7451 /*
7452 ** Round down to the nearest multiple of 8
7453 */
7454 #define ROUNDDOWN8(x) ((x)&~7)
7455
7456 /*
7457 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7458 ** macro is used only within assert() to verify that the code gets
7459 ** all alignment restrictions correct.
7460 **
7461 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7462 ** underlying malloc() implemention might return us 4-byte aligned
7463 ** pointers.  In that case, only verify 4-byte alignment.
7464 */
7465 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7466 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7467 #else
7468 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7469 #endif
7470
7471
7472 /*
7473 ** An instance of the following structure is used to store the busy-handler
7474 ** callback for a given sqlite handle. 
7475 **
7476 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7477 ** callback for the database handle. Each pager opened via the sqlite
7478 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7479 ** callback is currently invoked only from within pager.c.
7480 */
7481 typedef struct BusyHandler BusyHandler;
7482 struct BusyHandler {
7483   int (*xFunc)(void *,int);  /* The busy callback */
7484   void *pArg;                /* First arg to busy callback */
7485   int nBusy;                 /* Incremented with each busy call */
7486 };
7487
7488 /*
7489 ** Name of the master database table.  The master database table
7490 ** is a special table that holds the names and attributes of all
7491 ** user tables and indices.
7492 */
7493 #define MASTER_NAME       "sqlite_master"
7494 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7495
7496 /*
7497 ** The root-page of the master database table.
7498 */
7499 #define MASTER_ROOT       1
7500
7501 /*
7502 ** The name of the schema table.
7503 */
7504 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7505
7506 /*
7507 ** A convenience macro that returns the number of elements in
7508 ** an array.
7509 */
7510 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7511
7512 /*
7513 ** The following value as a destructor means to use sqlite3DbFree().
7514 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7515 */
7516 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7517
7518 /*
7519 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7520 ** not support Writable Static Data (WSD) such as global and static variables.
7521 ** All variables must either be on the stack or dynamically allocated from
7522 ** the heap.  When WSD is unsupported, the variable declarations scattered
7523 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7524 ** macro is used for this purpose.  And instead of referencing the variable
7525 ** directly, we use its constant as a key to lookup the run-time allocated
7526 ** buffer that holds real variable.  The constant is also the initializer
7527 ** for the run-time allocated buffer.
7528 **
7529 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7530 ** macros become no-ops and have zero performance impact.
7531 */
7532 #ifdef SQLITE_OMIT_WSD
7533   #define SQLITE_WSD const
7534   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7535   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7536 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7537 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7538 #else
7539   #define SQLITE_WSD 
7540   #define GLOBAL(t,v) v
7541   #define sqlite3GlobalConfig sqlite3Config
7542 #endif
7543
7544 /*
7545 ** The following macros are used to suppress compiler warnings and to
7546 ** make it clear to human readers when a function parameter is deliberately 
7547 ** left unused within the body of a function. This usually happens when
7548 ** a function is called via a function pointer. For example the 
7549 ** implementation of an SQL aggregate step callback may not use the
7550 ** parameter indicating the number of arguments passed to the aggregate,
7551 ** if it knows that this is enforced elsewhere.
7552 **
7553 ** When a function parameter is not used at all within the body of a function,
7554 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7555 ** However, these macros may also be used to suppress warnings related to
7556 ** parameters that may or may not be used depending on compilation options.
7557 ** For example those parameters only used in assert() statements. In these
7558 ** cases the parameters are named as per the usual conventions.
7559 */
7560 #define UNUSED_PARAMETER(x) (void)(x)
7561 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7562
7563 /*
7564 ** Forward references to structures
7565 */
7566 typedef struct AggInfo AggInfo;
7567 typedef struct AuthContext AuthContext;
7568 typedef struct AutoincInfo AutoincInfo;
7569 typedef struct Bitvec Bitvec;
7570 typedef struct CollSeq CollSeq;
7571 typedef struct Column Column;
7572 typedef struct Db Db;
7573 typedef struct Schema Schema;
7574 typedef struct Expr Expr;
7575 typedef struct ExprList ExprList;
7576 typedef struct ExprSpan ExprSpan;
7577 typedef struct FKey FKey;
7578 typedef struct FuncDestructor FuncDestructor;
7579 typedef struct FuncDef FuncDef;
7580 typedef struct FuncDefHash FuncDefHash;
7581 typedef struct IdList IdList;
7582 typedef struct Index Index;
7583 typedef struct IndexSample IndexSample;
7584 typedef struct KeyClass KeyClass;
7585 typedef struct KeyInfo KeyInfo;
7586 typedef struct Lookaside Lookaside;
7587 typedef struct LookasideSlot LookasideSlot;
7588 typedef struct Module Module;
7589 typedef struct NameContext NameContext;
7590 typedef struct Parse Parse;
7591 typedef struct RowSet RowSet;
7592 typedef struct Savepoint Savepoint;
7593 typedef struct Select Select;
7594 typedef struct SrcList SrcList;
7595 typedef struct StrAccum StrAccum;
7596 typedef struct Table Table;
7597 typedef struct TableLock TableLock;
7598 typedef struct Token Token;
7599 typedef struct Trigger Trigger;
7600 typedef struct TriggerPrg TriggerPrg;
7601 typedef struct TriggerStep TriggerStep;
7602 typedef struct UnpackedRecord UnpackedRecord;
7603 typedef struct VTable VTable;
7604 typedef struct Walker Walker;
7605 typedef struct WherePlan WherePlan;
7606 typedef struct WhereInfo WhereInfo;
7607 typedef struct WhereLevel WhereLevel;
7608
7609 /*
7610 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7611 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7612 ** pointer types (i.e. FuncDef) defined above.
7613 */
7614 /************** Include btree.h in the middle of sqliteInt.h *****************/
7615 /************** Begin file btree.h *******************************************/
7616 /*
7617 ** 2001 September 15
7618 **
7619 ** The author disclaims copyright to this source code.  In place of
7620 ** a legal notice, here is a blessing:
7621 **
7622 **    May you do good and not evil.
7623 **    May you find forgiveness for yourself and forgive others.
7624 **    May you share freely, never taking more than you give.
7625 **
7626 *************************************************************************
7627 ** This header file defines the interface that the sqlite B-Tree file
7628 ** subsystem.  See comments in the source code for a detailed description
7629 ** of what each interface routine does.
7630 */
7631 #ifndef _BTREE_H_
7632 #define _BTREE_H_
7633
7634 /* TODO: This definition is just included so other modules compile. It
7635 ** needs to be revisited.
7636 */
7637 #define SQLITE_N_BTREE_META 10
7638
7639 /*
7640 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7641 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7642 */
7643 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7644   #define SQLITE_DEFAULT_AUTOVACUUM 0
7645 #endif
7646
7647 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7648 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7649 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7650
7651 /*
7652 ** Forward declarations of structure
7653 */
7654 typedef struct Btree Btree;
7655 typedef struct BtCursor BtCursor;
7656 typedef struct BtShared BtShared;
7657
7658
7659 SQLITE_PRIVATE int sqlite3BtreeOpen(
7660   const char *zFilename,   /* Name of database file to open */
7661   sqlite3 *db,             /* Associated database connection */
7662   Btree **ppBtree,         /* Return open Btree* here */
7663   int flags,               /* Flags */
7664   int vfsFlags             /* Flags passed through to VFS open */
7665 );
7666
7667 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7668 ** following values.
7669 **
7670 ** NOTE:  These values must match the corresponding PAGER_ values in
7671 ** pager.h.
7672 */
7673 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7674 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7675 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7676 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7677 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7678
7679 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7680 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7681 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7682 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7683 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7684 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7685 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7686 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7687 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7688 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7689 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7690 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7691 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7692 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7693 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7694 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7695 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7696 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7697 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7698 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7699 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7700 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7701 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7702 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7703 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7704 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7705
7706 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7707 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7708 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7709
7710 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7711
7712 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7713 ** of the flags shown below.
7714 **
7715 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7716 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7717 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7718 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7719 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7720 ** indices.)
7721 */
7722 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7723 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7724
7725 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7726 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7727 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7728
7729 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7730 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7731
7732 /*
7733 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7734 ** should be one of the following values. The integer values are assigned 
7735 ** to constants so that the offset of the corresponding field in an
7736 ** SQLite database header may be found using the following formula:
7737 **
7738 **   offset = 36 + (idx * 4)
7739 **
7740 ** For example, the free-page-count field is located at byte offset 36 of
7741 ** the database file header. The incr-vacuum-flag field is located at
7742 ** byte offset 64 (== 36+4*7).
7743 */
7744 #define BTREE_FREE_PAGE_COUNT     0
7745 #define BTREE_SCHEMA_VERSION      1
7746 #define BTREE_FILE_FORMAT         2
7747 #define BTREE_DEFAULT_CACHE_SIZE  3
7748 #define BTREE_LARGEST_ROOT_PAGE   4
7749 #define BTREE_TEXT_ENCODING       5
7750 #define BTREE_USER_VERSION        6
7751 #define BTREE_INCR_VACUUM         7
7752
7753 SQLITE_PRIVATE int sqlite3BtreeCursor(
7754   Btree*,                              /* BTree containing table to open */
7755   int iTable,                          /* Index of root page */
7756   int wrFlag,                          /* 1 for writing.  0 for read-only */
7757   struct KeyInfo*,                     /* First argument to compare function */
7758   BtCursor *pCursor                    /* Space to write cursor structure */
7759 );
7760 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7761 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7762
7763 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7764 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7765   BtCursor*,
7766   UnpackedRecord *pUnKey,
7767   i64 intKey,
7768   int bias,
7769   int *pRes
7770 );
7771 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7772 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7773 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7774                                   const void *pData, int nData,
7775                                   int nZero, int bias, int seekResult);
7776 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7777 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7778 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7779 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7780 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7781 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7782 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7783 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7784 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7785 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7786 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7787 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7788 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7789
7790 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7791 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7792
7793 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7794 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7795 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7796
7797 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7798
7799 #ifndef NDEBUG
7800 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7801 #endif
7802
7803 #ifndef SQLITE_OMIT_BTREECOUNT
7804 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7805 #endif
7806
7807 #ifdef SQLITE_TEST
7808 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7809 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7810 #endif
7811
7812 #ifndef SQLITE_OMIT_WAL
7813 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
7814 #endif
7815
7816 /*
7817 ** If we are not using shared cache, then there is no need to
7818 ** use mutexes to access the BtShared structures.  So make the
7819 ** Enter and Leave procedures no-ops.
7820 */
7821 #ifndef SQLITE_OMIT_SHARED_CACHE
7822 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7823 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7824 #else
7825 # define sqlite3BtreeEnter(X) 
7826 # define sqlite3BtreeEnterAll(X)
7827 #endif
7828
7829 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7830 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
7831 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7832 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7833 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7834 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7835 #ifndef NDEBUG
7836   /* These routines are used inside assert() statements only. */
7837 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7838 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7839 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
7840 #endif
7841 #else
7842
7843 # define sqlite3BtreeSharable(X) 0
7844 # define sqlite3BtreeLeave(X)
7845 # define sqlite3BtreeEnterCursor(X)
7846 # define sqlite3BtreeLeaveCursor(X)
7847 # define sqlite3BtreeLeaveAll(X)
7848
7849 # define sqlite3BtreeHoldsMutex(X) 1
7850 # define sqlite3BtreeHoldsAllMutexes(X) 1
7851 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
7852 #endif
7853
7854
7855 #endif /* _BTREE_H_ */
7856
7857 /************** End of btree.h ***********************************************/
7858 /************** Continuing where we left off in sqliteInt.h ******************/
7859 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7860 /************** Begin file vdbe.h ********************************************/
7861 /*
7862 ** 2001 September 15
7863 **
7864 ** The author disclaims copyright to this source code.  In place of
7865 ** a legal notice, here is a blessing:
7866 **
7867 **    May you do good and not evil.
7868 **    May you find forgiveness for yourself and forgive others.
7869 **    May you share freely, never taking more than you give.
7870 **
7871 *************************************************************************
7872 ** Header file for the Virtual DataBase Engine (VDBE)
7873 **
7874 ** This header defines the interface to the virtual database engine
7875 ** or VDBE.  The VDBE implements an abstract machine that runs a
7876 ** simple program to access and modify the underlying database.
7877 */
7878 #ifndef _SQLITE_VDBE_H_
7879 #define _SQLITE_VDBE_H_
7880
7881 /*
7882 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7883 ** in the source file sqliteVdbe.c are allowed to see the insides
7884 ** of this structure.
7885 */
7886 typedef struct Vdbe Vdbe;
7887
7888 /*
7889 ** The names of the following types declared in vdbeInt.h are required
7890 ** for the VdbeOp definition.
7891 */
7892 typedef struct VdbeFunc VdbeFunc;
7893 typedef struct Mem Mem;
7894 typedef struct SubProgram SubProgram;
7895
7896 /*
7897 ** A single instruction of the virtual machine has an opcode
7898 ** and as many as three operands.  The instruction is recorded
7899 ** as an instance of the following structure:
7900 */
7901 struct VdbeOp {
7902   u8 opcode;          /* What operation to perform */
7903   signed char p4type; /* One of the P4_xxx constants for p4 */
7904   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7905   u8 p5;              /* Fifth parameter is an unsigned character */
7906   int p1;             /* First operand */
7907   int p2;             /* Second parameter (often the jump destination) */
7908   int p3;             /* The third parameter */
7909   union {             /* fourth parameter */
7910     int i;                 /* Integer value if p4type==P4_INT32 */
7911     void *p;               /* Generic pointer */
7912     char *z;               /* Pointer to data for string (char array) types */
7913     i64 *pI64;             /* Used when p4type is P4_INT64 */
7914     double *pReal;         /* Used when p4type is P4_REAL */
7915     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7916     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7917     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7918     Mem *pMem;             /* Used when p4type is P4_MEM */
7919     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7920     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7921     int *ai;               /* Used when p4type is P4_INTARRAY */
7922     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7923   } p4;
7924 #ifdef SQLITE_DEBUG
7925   char *zComment;          /* Comment to improve readability */
7926 #endif
7927 #ifdef VDBE_PROFILE
7928   int cnt;                 /* Number of times this instruction was executed */
7929   u64 cycles;              /* Total time spent executing this instruction */
7930 #endif
7931 };
7932 typedef struct VdbeOp VdbeOp;
7933
7934
7935 /*
7936 ** A sub-routine used to implement a trigger program.
7937 */
7938 struct SubProgram {
7939   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7940   int nOp;                      /* Elements in aOp[] */
7941   int nMem;                     /* Number of memory cells required */
7942   int nCsr;                     /* Number of cursors required */
7943   void *token;                  /* id that may be used to recursive triggers */
7944   SubProgram *pNext;            /* Next sub-program already visited */
7945 };
7946
7947 /*
7948 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7949 ** it takes up less space.
7950 */
7951 struct VdbeOpList {
7952   u8 opcode;          /* What operation to perform */
7953   signed char p1;     /* First operand */
7954   signed char p2;     /* Second parameter (often the jump destination) */
7955   signed char p3;     /* Third parameter */
7956 };
7957 typedef struct VdbeOpList VdbeOpList;
7958
7959 /*
7960 ** Allowed values of VdbeOp.p4type
7961 */
7962 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7963 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7964 #define P4_STATIC   (-2)  /* Pointer to a static string */
7965 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7966 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7967 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7968 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7969 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7970 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
7971 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7972 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7973 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7974 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7975 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7976 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7977 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7978
7979 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7980 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7981 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7982 ** gets freed when the Vdbe is finalized so it still should be obtained
7983 ** from a single sqliteMalloc().  But no copy is made and the calling
7984 ** function should *not* try to free the KeyInfo.
7985 */
7986 #define P4_KEYINFO_HANDOFF (-16)
7987 #define P4_KEYINFO_STATIC  (-17)
7988
7989 /*
7990 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7991 ** number of columns of data returned by the statement.
7992 */
7993 #define COLNAME_NAME     0
7994 #define COLNAME_DECLTYPE 1
7995 #define COLNAME_DATABASE 2
7996 #define COLNAME_TABLE    3
7997 #define COLNAME_COLUMN   4
7998 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7999 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8000 #else
8001 # ifdef SQLITE_OMIT_DECLTYPE
8002 #   define COLNAME_N      1      /* Store only the name */
8003 # else
8004 #   define COLNAME_N      2      /* Store the name and decltype */
8005 # endif
8006 #endif
8007
8008 /*
8009 ** The following macro converts a relative address in the p2 field
8010 ** of a VdbeOp structure into a negative number so that 
8011 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8012 ** the macro again restores the address.
8013 */
8014 #define ADDR(X)  (-1-(X))
8015
8016 /*
8017 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8018 ** header file that defines a number for each opcode used by the VDBE.
8019 */
8020 /************** Include opcodes.h in the middle of vdbe.h ********************/
8021 /************** Begin file opcodes.h *****************************************/
8022 /* Automatically generated.  Do not edit */
8023 /* See the mkopcodeh.awk script for details */
8024 #define OP_Goto                                 1
8025 #define OP_Gosub                                2
8026 #define OP_Return                               3
8027 #define OP_Yield                                4
8028 #define OP_HaltIfNull                           5
8029 #define OP_Halt                                 6
8030 #define OP_Integer                              7
8031 #define OP_Int64                                8
8032 #define OP_Real                               130   /* same as TK_FLOAT    */
8033 #define OP_String8                             94   /* same as TK_STRING   */
8034 #define OP_String                               9
8035 #define OP_Null                                10
8036 #define OP_Blob                                11
8037 #define OP_Variable                            12
8038 #define OP_Move                                13
8039 #define OP_Copy                                14
8040 #define OP_SCopy                               15
8041 #define OP_ResultRow                           16
8042 #define OP_Concat                              91   /* same as TK_CONCAT   */
8043 #define OP_Add                                 86   /* same as TK_PLUS     */
8044 #define OP_Subtract                            87   /* same as TK_MINUS    */
8045 #define OP_Multiply                            88   /* same as TK_STAR     */
8046 #define OP_Divide                              89   /* same as TK_SLASH    */
8047 #define OP_Remainder                           90   /* same as TK_REM      */
8048 #define OP_CollSeq                             17
8049 #define OP_Function                            18
8050 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8051 #define OP_BitOr                               83   /* same as TK_BITOR    */
8052 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8053 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8054 #define OP_AddImm                              20
8055 #define OP_MustBeInt                           21
8056 #define OP_RealAffinity                        22
8057 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8058 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8059 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8060 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8061 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8062 #define OP_Eq                                  76   /* same as TK_EQ       */
8063 #define OP_Ne                                  75   /* same as TK_NE       */
8064 #define OP_Lt                                  79   /* same as TK_LT       */
8065 #define OP_Le                                  78   /* same as TK_LE       */
8066 #define OP_Gt                                  77   /* same as TK_GT       */
8067 #define OP_Ge                                  80   /* same as TK_GE       */
8068 #define OP_Permutation                         23
8069 #define OP_Compare                             24
8070 #define OP_Jump                                25
8071 #define OP_And                                 69   /* same as TK_AND      */
8072 #define OP_Or                                  68   /* same as TK_OR       */
8073 #define OP_Not                                 19   /* same as TK_NOT      */
8074 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8075 #define OP_If                                  26
8076 #define OP_IfNot                               27
8077 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8078 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8079 #define OP_Column                              28
8080 #define OP_Affinity                            29
8081 #define OP_MakeRecord                          30
8082 #define OP_Count                               31
8083 #define OP_Savepoint                           32
8084 #define OP_AutoCommit                          33
8085 #define OP_Transaction                         34
8086 #define OP_ReadCookie                          35
8087 #define OP_SetCookie                           36
8088 #define OP_VerifyCookie                        37
8089 #define OP_OpenRead                            38
8090 #define OP_OpenWrite                           39
8091 #define OP_OpenAutoindex                       40
8092 #define OP_OpenEphemeral                       41
8093 #define OP_OpenPseudo                          42
8094 #define OP_Close                               43
8095 #define OP_SeekLt                              44
8096 #define OP_SeekLe                              45
8097 #define OP_SeekGe                              46
8098 #define OP_SeekGt                              47
8099 #define OP_Seek                                48
8100 #define OP_NotFound                            49
8101 #define OP_Found                               50
8102 #define OP_IsUnique                            51
8103 #define OP_NotExists                           52
8104 #define OP_Sequence                            53
8105 #define OP_NewRowid                            54
8106 #define OP_Insert                              55
8107 #define OP_InsertInt                           56
8108 #define OP_Delete                              57
8109 #define OP_ResetCount                          58
8110 #define OP_RowKey                              59
8111 #define OP_RowData                             60
8112 #define OP_Rowid                               61
8113 #define OP_NullRow                             62
8114 #define OP_Last                                63
8115 #define OP_Sort                                64
8116 #define OP_Rewind                              65
8117 #define OP_Prev                                66
8118 #define OP_Next                                67
8119 #define OP_IdxInsert                           70
8120 #define OP_IdxDelete                           71
8121 #define OP_IdxRowid                            72
8122 #define OP_IdxLT                               81
8123 #define OP_IdxGE                               92
8124 #define OP_Destroy                             95
8125 #define OP_Clear                               96
8126 #define OP_CreateIndex                         97
8127 #define OP_CreateTable                         98
8128 #define OP_ParseSchema                         99
8129 #define OP_LoadAnalysis                       100
8130 #define OP_DropTable                          101
8131 #define OP_DropIndex                          102
8132 #define OP_DropTrigger                        103
8133 #define OP_IntegrityCk                        104
8134 #define OP_RowSetAdd                          105
8135 #define OP_RowSetRead                         106
8136 #define OP_RowSetTest                         107
8137 #define OP_Program                            108
8138 #define OP_Param                              109
8139 #define OP_FkCounter                          110
8140 #define OP_FkIfZero                           111
8141 #define OP_MemMax                             112
8142 #define OP_IfPos                              113
8143 #define OP_IfNeg                              114
8144 #define OP_IfZero                             115
8145 #define OP_AggStep                            116
8146 #define OP_AggFinal                           117
8147 #define OP_Checkpoint                         118
8148 #define OP_JournalMode                        119
8149 #define OP_Vacuum                             120
8150 #define OP_IncrVacuum                         121
8151 #define OP_Expire                             122
8152 #define OP_TableLock                          123
8153 #define OP_VBegin                             124
8154 #define OP_VCreate                            125
8155 #define OP_VDestroy                           126
8156 #define OP_VOpen                              127
8157 #define OP_VFilter                            128
8158 #define OP_VColumn                            129
8159 #define OP_VNext                              131
8160 #define OP_VRename                            132
8161 #define OP_VUpdate                            133
8162 #define OP_Pagecount                          134
8163 #define OP_MaxPgcnt                           135
8164 #define OP_Trace                              136
8165 #define OP_Noop                               137
8166 #define OP_Explain                            138
8167
8168 /* The following opcode values are never used */
8169 #define OP_NotUsed_139                        139
8170 #define OP_NotUsed_140                        140
8171
8172
8173 /* Properties such as "out2" or "jump" that are specified in
8174 ** comments following the "case" for each opcode in the vdbe.c
8175 ** are encoded into bitvectors as follows:
8176 */
8177 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8178 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8179 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8180 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8181 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8182 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8183 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8184 #define OPFLG_INITIALIZER {\
8185 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8186 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8187 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8188 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8189 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8190 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8191 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8192 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8193 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8194 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8195 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8196 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8197 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8198 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8199 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8200 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8201 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8202 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8203 /* 144 */ 0x04, 0x04,}
8204
8205 /************** End of opcodes.h *********************************************/
8206 /************** Continuing where we left off in vdbe.h ***********************/
8207
8208 /*
8209 ** Prototypes for the VDBE interface.  See comments on the implementation
8210 ** for a description of what each of these routines does.
8211 */
8212 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8213 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8214 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8215 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8216 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8217 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8218 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8219 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8220 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8221 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8222 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8223 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8224 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8225 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8226 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8227 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8228 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8229 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8230 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8231 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8232 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8233 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8234 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8235 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8236 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8237 #ifdef SQLITE_DEBUG
8238 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8239 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8240 #endif
8241 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8242 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8243 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8244 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8245 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8246 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8247 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8248 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8249 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8250 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8251 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8252 #ifndef SQLITE_OMIT_TRACE
8253 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8254 #endif
8255
8256 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8257 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8258 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8259
8260 #ifndef SQLITE_OMIT_TRIGGER
8261 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8262 #endif
8263
8264
8265 #ifndef NDEBUG
8266 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8267 # define VdbeComment(X)  sqlite3VdbeComment X
8268 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8269 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8270 #else
8271 # define VdbeComment(X)
8272 # define VdbeNoopComment(X)
8273 #endif
8274
8275 #endif
8276
8277 /************** End of vdbe.h ************************************************/
8278 /************** Continuing where we left off in sqliteInt.h ******************/
8279 /************** Include pager.h in the middle of sqliteInt.h *****************/
8280 /************** Begin file pager.h *******************************************/
8281 /*
8282 ** 2001 September 15
8283 **
8284 ** The author disclaims copyright to this source code.  In place of
8285 ** a legal notice, here is a blessing:
8286 **
8287 **    May you do good and not evil.
8288 **    May you find forgiveness for yourself and forgive others.
8289 **    May you share freely, never taking more than you give.
8290 **
8291 *************************************************************************
8292 ** This header file defines the interface that the sqlite page cache
8293 ** subsystem.  The page cache subsystem reads and writes a file a page
8294 ** at a time and provides a journal for rollback.
8295 */
8296
8297 #ifndef _PAGER_H_
8298 #define _PAGER_H_
8299
8300 /*
8301 ** Default maximum size for persistent journal files. A negative 
8302 ** value means no limit. This value may be overridden using the 
8303 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8304 */
8305 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8306   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8307 #endif
8308
8309 /*
8310 ** The type used to represent a page number.  The first page in a file
8311 ** is called page 1.  0 is used to represent "not a page".
8312 */
8313 typedef u32 Pgno;
8314
8315 /*
8316 ** Each open file is managed by a separate instance of the "Pager" structure.
8317 */
8318 typedef struct Pager Pager;
8319
8320 /*
8321 ** Handle type for pages.
8322 */
8323 typedef struct PgHdr DbPage;
8324
8325 /*
8326 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8327 ** reserved for working around a windows/posix incompatibility). It is
8328 ** used in the journal to signify that the remainder of the journal file 
8329 ** is devoted to storing a master journal name - there are no more pages to
8330 ** roll back. See comments for function writeMasterJournal() in pager.c 
8331 ** for details.
8332 */
8333 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8334
8335 /*
8336 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8337 **
8338 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8339 */
8340 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8341 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8342 #define PAGER_MEMORY        0x0004    /* In-memory database */
8343
8344 /*
8345 ** Valid values for the second argument to sqlite3PagerLockingMode().
8346 */
8347 #define PAGER_LOCKINGMODE_QUERY      -1
8348 #define PAGER_LOCKINGMODE_NORMAL      0
8349 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8350
8351 /*
8352 ** Numeric constants that encode the journalmode.  
8353 */
8354 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8355 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8356 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8357 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8358 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8359 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8360 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8361
8362 /*
8363 ** The remainder of this file contains the declarations of the functions
8364 ** that make up the Pager sub-system API. See source code comments for 
8365 ** a detailed description of each routine.
8366 */
8367
8368 /* Open and close a Pager connection. */ 
8369 SQLITE_PRIVATE int sqlite3PagerOpen(
8370   sqlite3_vfs*,
8371   Pager **ppPager,
8372   const char*,
8373   int,
8374   int,
8375   int,
8376   void(*)(DbPage*)
8377 );
8378 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8379 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8380
8381 /* Functions used to configure a Pager object. */
8382 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8383 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8384 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8385 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8386 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8387 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8388 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8389 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8390 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8391 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8392 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8393
8394 /* Functions used to obtain and release page references. */ 
8395 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8396 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8397 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8398 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8399 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8400
8401 /* Operations on page references. */
8402 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8403 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8404 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8405 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8406 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8407 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8408
8409 /* Functions used to manage pager transactions and savepoints. */
8410 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8411 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8412 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8413 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8414 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8415 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8416 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8417 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8418 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8419 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8420
8421 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8422 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8423 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8424 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8425 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8426
8427 /* Functions used to query pager state and configuration. */
8428 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8429 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8430 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8431 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8432 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8433 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8434 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8435 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8436 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8437 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8438
8439 /* Functions used to truncate the database file. */
8440 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8441
8442 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8443 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8444 #endif
8445
8446 /* Functions to support testing and debugging. */
8447 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8448 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8449 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8450 #endif
8451 #ifdef SQLITE_TEST
8452 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8453 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8454   void disable_simulated_io_errors(void);
8455   void enable_simulated_io_errors(void);
8456 #else
8457 # define disable_simulated_io_errors()
8458 # define enable_simulated_io_errors()
8459 #endif
8460
8461 #endif /* _PAGER_H_ */
8462
8463 /************** End of pager.h ***********************************************/
8464 /************** Continuing where we left off in sqliteInt.h ******************/
8465 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8466 /************** Begin file pcache.h ******************************************/
8467 /*
8468 ** 2008 August 05
8469 **
8470 ** The author disclaims copyright to this source code.  In place of
8471 ** a legal notice, here is a blessing:
8472 **
8473 **    May you do good and not evil.
8474 **    May you find forgiveness for yourself and forgive others.
8475 **    May you share freely, never taking more than you give.
8476 **
8477 *************************************************************************
8478 ** This header file defines the interface that the sqlite page cache
8479 ** subsystem. 
8480 */
8481
8482 #ifndef _PCACHE_H_
8483
8484 typedef struct PgHdr PgHdr;
8485 typedef struct PCache PCache;
8486
8487 /*
8488 ** Every page in the cache is controlled by an instance of the following
8489 ** structure.
8490 */
8491 struct PgHdr {
8492   void *pData;                   /* Content of this page */
8493   void *pExtra;                  /* Extra content */
8494   PgHdr *pDirty;                 /* Transient list of dirty pages */
8495   Pgno pgno;                     /* Page number for this page */
8496   Pager *pPager;                 /* The pager this page is part of */
8497 #ifdef SQLITE_CHECK_PAGES
8498   u32 pageHash;                  /* Hash of page content */
8499 #endif
8500   u16 flags;                     /* PGHDR flags defined below */
8501
8502   /**********************************************************************
8503   ** Elements above are public.  All that follows is private to pcache.c
8504   ** and should not be accessed by other modules.
8505   */
8506   i16 nRef;                      /* Number of users of this page */
8507   PCache *pCache;                /* Cache that owns this page */
8508
8509   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8510   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8511 };
8512
8513 /* Bit values for PgHdr.flags */
8514 #define PGHDR_DIRTY             0x002  /* Page has changed */
8515 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8516                                        ** writing this page to the database */
8517 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8518 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8519 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8520
8521 /* Initialize and shutdown the page cache subsystem */
8522 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8523 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8524
8525 /* Page cache buffer management:
8526 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8527 */
8528 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8529
8530 /* Create a new pager cache.
8531 ** Under memory stress, invoke xStress to try to make pages clean.
8532 ** Only clean and unpinned pages can be reclaimed.
8533 */
8534 SQLITE_PRIVATE void sqlite3PcacheOpen(
8535   int szPage,                    /* Size of every page */
8536   int szExtra,                   /* Extra space associated with each page */
8537   int bPurgeable,                /* True if pages are on backing store */
8538   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8539   void *pStress,                 /* Argument to xStress */
8540   PCache *pToInit                /* Preallocated space for the PCache */
8541 );
8542
8543 /* Modify the page-size after the cache has been created. */
8544 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8545
8546 /* Return the size in bytes of a PCache object.  Used to preallocate
8547 ** storage space.
8548 */
8549 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8550
8551 /* One release per successful fetch.  Page is pinned until released.
8552 ** Reference counted. 
8553 */
8554 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8555 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8556
8557 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8558 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8559 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8560 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8561
8562 /* Change a page number.  Used by incr-vacuum. */
8563 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8564
8565 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8566 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8567
8568 /* Get a list of all dirty pages in the cache, sorted by page number */
8569 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8570
8571 /* Reset and close the cache object */
8572 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8573
8574 /* Clear flags from pages of the page cache */
8575 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8576
8577 /* Discard the contents of the cache */
8578 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8579
8580 /* Return the total number of outstanding page references */
8581 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8582
8583 /* Increment the reference count of an existing page */
8584 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8585
8586 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8587
8588 /* Return the total number of pages stored in the cache */
8589 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8590
8591 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8592 /* Iterate through all dirty pages currently stored in the cache. This
8593 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8594 ** library is built.
8595 */
8596 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8597 #endif
8598
8599 /* Set and get the suggested cache-size for the specified pager-cache.
8600 **
8601 ** If no global maximum is configured, then the system attempts to limit
8602 ** the total number of pages cached by purgeable pager-caches to the sum
8603 ** of the suggested cache-sizes.
8604 */
8605 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8606 #ifdef SQLITE_TEST
8607 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8608 #endif
8609
8610 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8611 /* Try to return memory used by the pcache module to the main memory heap */
8612 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8613 #endif
8614
8615 #ifdef SQLITE_TEST
8616 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8617 #endif
8618
8619 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8620
8621 #endif /* _PCACHE_H_ */
8622
8623 /************** End of pcache.h **********************************************/
8624 /************** Continuing where we left off in sqliteInt.h ******************/
8625
8626 /************** Include os.h in the middle of sqliteInt.h ********************/
8627 /************** Begin file os.h **********************************************/
8628 /*
8629 ** 2001 September 16
8630 **
8631 ** The author disclaims copyright to this source code.  In place of
8632 ** a legal notice, here is a blessing:
8633 **
8634 **    May you do good and not evil.
8635 **    May you find forgiveness for yourself and forgive others.
8636 **    May you share freely, never taking more than you give.
8637 **
8638 ******************************************************************************
8639 **
8640 ** This header file (together with is companion C source-code file
8641 ** "os.c") attempt to abstract the underlying operating system so that
8642 ** the SQLite library will work on both POSIX and windows systems.
8643 **
8644 ** This header file is #include-ed by sqliteInt.h and thus ends up
8645 ** being included by every source file.
8646 */
8647 #ifndef _SQLITE_OS_H_
8648 #define _SQLITE_OS_H_
8649
8650 /*
8651 ** Figure out if we are dealing with Unix, Windows, or some other
8652 ** operating system.  After the following block of preprocess macros,
8653 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8654 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8655 ** three will be 0.
8656 */
8657 #if defined(SQLITE_OS_OTHER)
8658 # if SQLITE_OS_OTHER==1
8659 #   undef SQLITE_OS_UNIX
8660 #   define SQLITE_OS_UNIX 0
8661 #   undef SQLITE_OS_WIN
8662 #   define SQLITE_OS_WIN 0
8663 #   undef SQLITE_OS_OS2
8664 #   define SQLITE_OS_OS2 0
8665 # else
8666 #   undef SQLITE_OS_OTHER
8667 # endif
8668 #endif
8669 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8670 # define SQLITE_OS_OTHER 0
8671 # ifndef SQLITE_OS_WIN
8672 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8673 #     define SQLITE_OS_WIN 1
8674 #     define SQLITE_OS_UNIX 0
8675 #     define SQLITE_OS_OS2 0
8676 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8677 #     define SQLITE_OS_WIN 0
8678 #     define SQLITE_OS_UNIX 0
8679 #     define SQLITE_OS_OS2 1
8680 #   else
8681 #     define SQLITE_OS_WIN 0
8682 #     define SQLITE_OS_UNIX 1
8683 #     define SQLITE_OS_OS2 0
8684 #  endif
8685 # else
8686 #  define SQLITE_OS_UNIX 0
8687 #  define SQLITE_OS_OS2 0
8688 # endif
8689 #else
8690 # ifndef SQLITE_OS_WIN
8691 #  define SQLITE_OS_WIN 0
8692 # endif
8693 #endif
8694
8695 /*
8696 ** Determine if we are dealing with WindowsCE - which has a much
8697 ** reduced API.
8698 */
8699 #if defined(_WIN32_WCE)
8700 # define SQLITE_OS_WINCE 1
8701 #else
8702 # define SQLITE_OS_WINCE 0
8703 #endif
8704
8705
8706 /*
8707 ** Define the maximum size of a temporary filename
8708 */
8709 #if SQLITE_OS_WIN
8710 # include <windows.h>
8711 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8712 #elif SQLITE_OS_OS2
8713 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8714 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8715 # endif
8716 # define INCL_DOSDATETIME
8717 # define INCL_DOSFILEMGR
8718 # define INCL_DOSERRORS
8719 # define INCL_DOSMISC
8720 # define INCL_DOSPROCESS
8721 # define INCL_DOSMODULEMGR
8722 # define INCL_DOSSEMAPHORES
8723 # include <os2.h>
8724 # include <uconv.h>
8725 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8726 #else
8727 # define SQLITE_TEMPNAME_SIZE 200
8728 #endif
8729
8730 /* If the SET_FULLSYNC macro is not defined above, then make it
8731 ** a no-op
8732 */
8733 #ifndef SET_FULLSYNC
8734 # define SET_FULLSYNC(x,y)
8735 #endif
8736
8737 /*
8738 ** The default size of a disk sector
8739 */
8740 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8741 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8742 #endif
8743
8744 /*
8745 ** Temporary files are named starting with this prefix followed by 16 random
8746 ** alphanumeric characters, and no file extension. They are stored in the
8747 ** OS's standard temporary file directory, and are deleted prior to exit.
8748 ** If sqlite is being embedded in another program, you may wish to change the
8749 ** prefix to reflect your program's name, so that if your program exits
8750 ** prematurely, old temporary files can be easily identified. This can be done
8751 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8752 **
8753 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8754 ** Mcafee started using SQLite in their anti-virus product and it
8755 ** started putting files with the "sqlite" name in the c:/temp folder.
8756 ** This annoyed many windows users.  Those users would then do a 
8757 ** Google search for "sqlite", find the telephone numbers of the
8758 ** developers and call to wake them up at night and complain.
8759 ** For this reason, the default name prefix is changed to be "sqlite" 
8760 ** spelled backwards.  So the temp files are still identified, but
8761 ** anybody smart enough to figure out the code is also likely smart
8762 ** enough to know that calling the developer will not help get rid
8763 ** of the file.
8764 */
8765 #ifndef SQLITE_TEMP_FILE_PREFIX
8766 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8767 #endif
8768
8769 /*
8770 ** The following values may be passed as the second argument to
8771 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8772 **
8773 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8774 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8775 **            any time. Other processes may hold and obtain new SHARED locks.
8776 ** PENDING:   A single process may hold a PENDING lock on a file at
8777 **            any one time. Existing SHARED locks may persist, but no new
8778 **            SHARED locks may be obtained by other processes.
8779 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8780 **
8781 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8782 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8783 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8784 ** sqlite3OsLock().
8785 */
8786 #define NO_LOCK         0
8787 #define SHARED_LOCK     1
8788 #define RESERVED_LOCK   2
8789 #define PENDING_LOCK    3
8790 #define EXCLUSIVE_LOCK  4
8791
8792 /*
8793 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8794 **
8795 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8796 ** those functions are not available.  So we use only LockFile() and
8797 ** UnlockFile().
8798 **
8799 ** LockFile() prevents not just writing but also reading by other processes.
8800 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8801 ** byte out of a specific range of bytes. The lock byte is obtained at 
8802 ** random so two separate readers can probably access the file at the 
8803 ** same time, unless they are unlucky and choose the same lock byte.
8804 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8805 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8806 ** a single byte of the file that is designated as the reserved lock byte.
8807 ** A PENDING_LOCK is obtained by locking a designated byte different from
8808 ** the RESERVED_LOCK byte.
8809 **
8810 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8811 ** which means we can use reader/writer locks.  When reader/writer locks
8812 ** are used, the lock is placed on the same range of bytes that is used
8813 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8814 ** will support two or more Win95 readers or two or more WinNT readers.
8815 ** But a single Win95 reader will lock out all WinNT readers and a single
8816 ** WinNT reader will lock out all other Win95 readers.
8817 **
8818 ** The following #defines specify the range of bytes used for locking.
8819 ** SHARED_SIZE is the number of bytes available in the pool from which
8820 ** a random byte is selected for a shared lock.  The pool of bytes for
8821 ** shared locks begins at SHARED_FIRST. 
8822 **
8823 ** The same locking strategy and
8824 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8825 ** clients on win95, winNT, and unix all talking to the same shared file
8826 ** and all locking correctly.  To do so would require that samba (or whatever
8827 ** tool is being used for file sharing) implements locks correctly between
8828 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8829 ** using the same locking range we are at least open to the possibility.
8830 **
8831 ** Locking in windows is manditory.  For this reason, we cannot store
8832 ** actual data in the bytes used for locking.  The pager never allocates
8833 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8834 ** that all locks will fit on a single page even at the minimum page size.
8835 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8836 ** is set high so that we don't have to allocate an unused page except
8837 ** for very large databases.  But one should test the page skipping logic 
8838 ** by setting PENDING_BYTE low and running the entire regression suite.
8839 **
8840 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8841 ** file format.  Depending on how it is changed, you might not notice
8842 ** the incompatibility right away, even running a full regression test.
8843 ** The default location of PENDING_BYTE is the first byte past the
8844 ** 1GB boundary.
8845 **
8846 */
8847 #ifdef SQLITE_OMIT_WSD
8848 # define PENDING_BYTE     (0x40000000)
8849 #else
8850 # define PENDING_BYTE      sqlite3PendingByte
8851 #endif
8852 #define RESERVED_BYTE     (PENDING_BYTE+1)
8853 #define SHARED_FIRST      (PENDING_BYTE+2)
8854 #define SHARED_SIZE       510
8855
8856 /*
8857 ** Wrapper around OS specific sqlite3_os_init() function.
8858 */
8859 SQLITE_PRIVATE int sqlite3OsInit(void);
8860
8861 /* 
8862 ** Functions for accessing sqlite3_file methods 
8863 */
8864 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8865 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8866 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8867 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8868 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8869 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8870 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8871 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8872 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8873 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8874 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8875 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8876 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8877 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8878 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8879 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8880 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8881
8882 /* 
8883 ** Functions for accessing sqlite3_vfs methods 
8884 */
8885 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8886 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8887 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8888 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8889 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8890 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8891 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8892 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8893 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8894 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8895 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8896 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8897 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8898
8899 /*
8900 ** Convenience functions for opening and closing files using 
8901 ** sqlite3_malloc() to obtain space for the file-handle structure.
8902 */
8903 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8904 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8905
8906 #endif /* _SQLITE_OS_H_ */
8907
8908 /************** End of os.h **************************************************/
8909 /************** Continuing where we left off in sqliteInt.h ******************/
8910 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8911 /************** Begin file mutex.h *******************************************/
8912 /*
8913 ** 2007 August 28
8914 **
8915 ** The author disclaims copyright to this source code.  In place of
8916 ** a legal notice, here is a blessing:
8917 **
8918 **    May you do good and not evil.
8919 **    May you find forgiveness for yourself and forgive others.
8920 **    May you share freely, never taking more than you give.
8921 **
8922 *************************************************************************
8923 **
8924 ** This file contains the common header for all mutex implementations.
8925 ** The sqliteInt.h header #includes this file so that it is available
8926 ** to all source files.  We break it out in an effort to keep the code
8927 ** better organized.
8928 **
8929 ** NOTE:  source files should *not* #include this header file directly.
8930 ** Source files should #include the sqliteInt.h file and let that file
8931 ** include this one indirectly.
8932 */
8933
8934
8935 /*
8936 ** Figure out what version of the code to use.  The choices are
8937 **
8938 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8939 **                             mutexes implemention cannot be overridden
8940 **                             at start-time.
8941 **
8942 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8943 **                             mutual exclusion is provided.  But this
8944 **                             implementation can be overridden at
8945 **                             start-time.
8946 **
8947 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8948 **
8949 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8950 **
8951 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8952 */
8953 #if !SQLITE_THREADSAFE
8954 # define SQLITE_MUTEX_OMIT
8955 #endif
8956 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8957 #  if SQLITE_OS_UNIX
8958 #    define SQLITE_MUTEX_PTHREADS
8959 #  elif SQLITE_OS_WIN
8960 #    define SQLITE_MUTEX_W32
8961 #  elif SQLITE_OS_OS2
8962 #    define SQLITE_MUTEX_OS2
8963 #  else
8964 #    define SQLITE_MUTEX_NOOP
8965 #  endif
8966 #endif
8967
8968 #ifdef SQLITE_MUTEX_OMIT
8969 /*
8970 ** If this is a no-op implementation, implement everything as macros.
8971 */
8972 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8973 #define sqlite3_mutex_free(X)
8974 #define sqlite3_mutex_enter(X)
8975 #define sqlite3_mutex_try(X)      SQLITE_OK
8976 #define sqlite3_mutex_leave(X)
8977 #define sqlite3_mutex_held(X)     ((void)(X),1)
8978 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
8979 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8980 #define sqlite3MutexInit()        SQLITE_OK
8981 #define sqlite3MutexEnd()
8982 #endif /* defined(SQLITE_MUTEX_OMIT) */
8983
8984 /************** End of mutex.h ***********************************************/
8985 /************** Continuing where we left off in sqliteInt.h ******************/
8986
8987
8988 /*
8989 ** Each database file to be accessed by the system is an instance
8990 ** of the following structure.  There are normally two of these structures
8991 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8992 ** aDb[1] is the database file used to hold temporary tables.  Additional
8993 ** databases may be attached.
8994 */
8995 struct Db {
8996   char *zName;         /* Name of this database */
8997   Btree *pBt;          /* The B*Tree structure for this database file */
8998   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8999   u8 safety_level;     /* How aggressive at syncing data to disk */
9000   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9001 };
9002
9003 /*
9004 ** An instance of the following structure stores a database schema.
9005 **
9006 ** Most Schema objects are associated with a Btree.  The exception is
9007 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9008 ** In shared cache mode, a single Schema object can be shared by multiple
9009 ** Btrees that refer to the same underlying BtShared object.
9010 ** 
9011 ** Schema objects are automatically deallocated when the last Btree that
9012 ** references them is destroyed.   The TEMP Schema is manually freed by
9013 ** sqlite3_close().
9014 *
9015 ** A thread must be holding a mutex on the corresponding Btree in order
9016 ** to access Schema content.  This implies that the thread must also be
9017 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9018 ** For a TEMP Schema, on the connection mutex is required.
9019 */
9020 struct Schema {
9021   int schema_cookie;   /* Database schema version number for this file */
9022   int iGeneration;     /* Generation counter.  Incremented with each change */
9023   Hash tblHash;        /* All tables indexed by name */
9024   Hash idxHash;        /* All (named) indices indexed by name */
9025   Hash trigHash;       /* All triggers indexed by name */
9026   Hash fkeyHash;       /* All foreign keys by referenced table name */
9027   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9028   u8 file_format;      /* Schema format version for this file */
9029   u8 enc;              /* Text encoding used by this database */
9030   u16 flags;           /* Flags associated with this schema */
9031   int cache_size;      /* Number of pages to use in the cache */
9032 };
9033
9034 /*
9035 ** These macros can be used to test, set, or clear bits in the 
9036 ** Db.pSchema->flags field.
9037 */
9038 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9039 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9040 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9041 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9042
9043 /*
9044 ** Allowed values for the DB.pSchema->flags field.
9045 **
9046 ** The DB_SchemaLoaded flag is set after the database schema has been
9047 ** read into internal hash tables.
9048 **
9049 ** DB_UnresetViews means that one or more views have column names that
9050 ** have been filled out.  If the schema changes, these column names might
9051 ** changes and so the view will need to be reset.
9052 */
9053 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9054 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9055 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9056
9057 /*
9058 ** The number of different kinds of things that can be limited
9059 ** using the sqlite3_limit() interface.
9060 */
9061 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9062
9063 /*
9064 ** Lookaside malloc is a set of fixed-size buffers that can be used
9065 ** to satisfy small transient memory allocation requests for objects
9066 ** associated with a particular database connection.  The use of
9067 ** lookaside malloc provides a significant performance enhancement
9068 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9069 ** SQL statements.
9070 **
9071 ** The Lookaside structure holds configuration information about the
9072 ** lookaside malloc subsystem.  Each available memory allocation in
9073 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9074 ** objects.
9075 **
9076 ** Lookaside allocations are only allowed for objects that are associated
9077 ** with a particular database connection.  Hence, schema information cannot
9078 ** be stored in lookaside because in shared cache mode the schema information
9079 ** is shared by multiple database connections.  Therefore, while parsing
9080 ** schema information, the Lookaside.bEnabled flag is cleared so that
9081 ** lookaside allocations are not used to construct the schema objects.
9082 */
9083 struct Lookaside {
9084   u16 sz;                 /* Size of each buffer in bytes */
9085   u8 bEnabled;            /* False to disable new lookaside allocations */
9086   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9087   int nOut;               /* Number of buffers currently checked out */
9088   int mxOut;              /* Highwater mark for nOut */
9089   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9090   LookasideSlot *pFree;   /* List of available buffers */
9091   void *pStart;           /* First byte of available memory space */
9092   void *pEnd;             /* First byte past end of available space */
9093 };
9094 struct LookasideSlot {
9095   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9096 };
9097
9098 /*
9099 ** A hash table for function definitions.
9100 **
9101 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9102 ** Collisions are on the FuncDef.pHash chain.
9103 */
9104 struct FuncDefHash {
9105   FuncDef *a[23];       /* Hash table for functions */
9106 };
9107
9108 /*
9109 ** Each database connection is an instance of the following structure.
9110 **
9111 ** The sqlite.lastRowid records the last insert rowid generated by an
9112 ** insert statement.  Inserts on views do not affect its value.  Each
9113 ** trigger has its own context, so that lastRowid can be updated inside
9114 ** triggers as usual.  The previous value will be restored once the trigger
9115 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9116 ** longer (since after version 2.8.12) reset to -1.
9117 **
9118 ** The sqlite.nChange does not count changes within triggers and keeps no
9119 ** context.  It is reset at start of sqlite3_exec.
9120 ** The sqlite.lsChange represents the number of changes made by the last
9121 ** insert, update, or delete statement.  It remains constant throughout the
9122 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9123 ** context stack just like lastRowid so that the count of changes
9124 ** within a trigger is not seen outside the trigger.  Changes to views do not
9125 ** affect the value of lsChange.
9126 ** The sqlite.csChange keeps track of the number of current changes (since
9127 ** the last statement) and is used to update sqlite_lsChange.
9128 **
9129 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9130 ** store the most recent error code and, if applicable, string. The
9131 ** internal function sqlite3Error() is used to set these variables
9132 ** consistently.
9133 */
9134 struct sqlite3 {
9135   sqlite3_vfs *pVfs;            /* OS Interface */
9136   int nDb;                      /* Number of backends currently in use */
9137   Db *aDb;                      /* All backends */
9138   int flags;                    /* Miscellaneous flags. See below */
9139   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9140   int errCode;                  /* Most recent error code (SQLITE_*) */
9141   int errMask;                  /* & result codes with this before returning */
9142   u8 autoCommit;                /* The auto-commit flag. */
9143   u8 temp_store;                /* 1: file 2: memory 0: default */
9144   u8 mallocFailed;              /* True if we have seen a malloc failure */
9145   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9146   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9147   u8 suppressErr;               /* Do not issue error messages if true */
9148   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9149   int nTable;                   /* Number of tables in the database */
9150   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9151   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9152   u32 magic;                    /* Magic number for detect library misuse */
9153   int nChange;                  /* Value returned by sqlite3_changes() */
9154   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9155   sqlite3_mutex *mutex;         /* Connection mutex */
9156   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9157   struct sqlite3InitInfo {      /* Information used during initialization */
9158     int iDb;                    /* When back is being initialized */
9159     int newTnum;                /* Rootpage of table being initialized */
9160     u8 busy;                    /* TRUE if currently initializing */
9161     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9162   } init;
9163   int nExtension;               /* Number of loaded extensions */
9164   void **aExtension;            /* Array of shared library handles */
9165   struct Vdbe *pVdbe;           /* List of active virtual machines */
9166   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9167   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9168   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9169   void (*xTrace)(void*,const char*);        /* Trace function */
9170   void *pTraceArg;                          /* Argument to the trace function */
9171   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9172   void *pProfileArg;                        /* Argument to profile function */
9173   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9174   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9175   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9176   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9177   void *pUpdateArg;
9178   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9179 #ifndef SQLITE_OMIT_WAL
9180   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9181   void *pWalArg;
9182 #endif
9183   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9184   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9185   void *pCollNeededArg;
9186   sqlite3_value *pErr;          /* Most recent error message */
9187   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9188   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9189   union {
9190     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9191     double notUsed1;            /* Spacer */
9192   } u1;
9193   Lookaside lookaside;          /* Lookaside malloc configuration */
9194 #ifndef SQLITE_OMIT_AUTHORIZATION
9195   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9196                                 /* Access authorization function */
9197   void *pAuthArg;               /* 1st argument to the access auth function */
9198 #endif
9199 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9200   int (*xProgress)(void *);     /* The progress callback */
9201   void *pProgressArg;           /* Argument to the progress callback */
9202   int nProgressOps;             /* Number of opcodes for progress callback */
9203 #endif
9204 #ifndef SQLITE_OMIT_VIRTUALTABLE
9205   Hash aModule;                 /* populated by sqlite3_create_module() */
9206   Table *pVTab;                 /* vtab with active Connect/Create method */
9207   VTable **aVTrans;             /* Virtual tables with open transactions */
9208   int nVTrans;                  /* Allocated size of aVTrans */
9209   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9210 #endif
9211   FuncDefHash aFunc;            /* Hash table of connection functions */
9212   Hash aCollSeq;                /* All collating sequences */
9213   BusyHandler busyHandler;      /* Busy callback */
9214   int busyTimeout;              /* Busy handler timeout, in msec */
9215   Db aDbStatic[2];              /* Static space for the 2 default backends */
9216   Savepoint *pSavepoint;        /* List of active savepoints */
9217   int nSavepoint;               /* Number of non-transaction savepoints */
9218   int nStatement;               /* Number of nested statement-transactions  */
9219   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9220   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9221   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9222
9223 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9224   /* The following variables are all protected by the STATIC_MASTER 
9225   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9226   **
9227   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9228   ** unlock so that it can proceed.
9229   **
9230   ** When X.pBlockingConnection==Y, that means that something that X tried
9231   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9232   ** held by Y.
9233   */
9234   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9235   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9236   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9237   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9238   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9239 #endif
9240 };
9241
9242 /*
9243 ** A macro to discover the encoding of a database.
9244 */
9245 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9246
9247 /*
9248 ** Possible values for the sqlite3.flags.
9249 */
9250 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9251 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9252 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9253 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9254 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9255                                           /*   DELETE, or UPDATE and return */
9256                                           /*   the count using a callback. */
9257 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9258                                           /*   result set is empty */
9259 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9260 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9261 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9262 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
9263                                           ** accessing read-only databases */
9264 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9265 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9266 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9267 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9268 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9269 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9270 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9271 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9272 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9273 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9274 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9275 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9276 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9277
9278 /*
9279 ** Bits of the sqlite3.flags field that are used by the
9280 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9281 ** These must be the low-order bits of the flags field.
9282 */
9283 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9284 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9285 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9286 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9287 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9288 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9289 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9290 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9291
9292 /*
9293 ** Possible values for the sqlite.magic field.
9294 ** The numbers are obtained at random and have no special meaning, other
9295 ** than being distinct from one another.
9296 */
9297 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9298 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9299 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9300 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9301 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9302
9303 /*
9304 ** Each SQL function is defined by an instance of the following
9305 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9306 ** hash table.  When multiple functions have the same name, the hash table
9307 ** points to a linked list of these structures.
9308 */
9309 struct FuncDef {
9310   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9311   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9312   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9313   void *pUserData;     /* User data parameter */
9314   FuncDef *pNext;      /* Next function with same name */
9315   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9316   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9317   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9318   char *zName;         /* SQL name of the function. */
9319   FuncDef *pHash;      /* Next with a different name but the same hash */
9320   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9321 };
9322
9323 /*
9324 ** This structure encapsulates a user-function destructor callback (as
9325 ** configured using create_function_v2()) and a reference counter. When
9326 ** create_function_v2() is called to create a function with a destructor,
9327 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9328 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9329 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9330 ** member of each of the new FuncDef objects is set to point to the allocated
9331 ** FuncDestructor.
9332 **
9333 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9334 ** count on this object is decremented. When it reaches 0, the destructor
9335 ** is invoked and the FuncDestructor structure freed.
9336 */
9337 struct FuncDestructor {
9338   int nRef;
9339   void (*xDestroy)(void *);
9340   void *pUserData;
9341 };
9342
9343 /*
9344 ** Possible values for FuncDef.flags
9345 */
9346 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9347 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9348 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9349 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9350 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9351 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9352 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9353
9354 /*
9355 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9356 ** used to create the initializers for the FuncDef structures.
9357 **
9358 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9359 **     Used to create a scalar function definition of a function zName 
9360 **     implemented by C function xFunc that accepts nArg arguments. The
9361 **     value passed as iArg is cast to a (void*) and made available
9362 **     as the user-data (sqlite3_user_data()) for the function. If 
9363 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9364 **
9365 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9366 **     Used to create an aggregate function definition implemented by
9367 **     the C functions xStep and xFinal. The first four parameters
9368 **     are interpreted in the same way as the first 4 parameters to
9369 **     FUNCTION().
9370 **
9371 **   LIKEFUNC(zName, nArg, pArg, flags)
9372 **     Used to create a scalar function definition of a function zName 
9373 **     that accepts nArg arguments and is implemented by a call to C 
9374 **     function likeFunc. Argument pArg is cast to a (void *) and made
9375 **     available as the function user-data (sqlite3_user_data()). The
9376 **     FuncDef.flags variable is set to the value passed as the flags
9377 **     parameter.
9378 */
9379 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9380   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9381    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9382 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9383   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9384    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9385 #define LIKEFUNC(zName, nArg, arg, flags) \
9386   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9387 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9388   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9389    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9390
9391 /*
9392 ** All current savepoints are stored in a linked list starting at
9393 ** sqlite3.pSavepoint. The first element in the list is the most recently
9394 ** opened savepoint. Savepoints are added to the list by the vdbe
9395 ** OP_Savepoint instruction.
9396 */
9397 struct Savepoint {
9398   char *zName;                        /* Savepoint name (nul-terminated) */
9399   i64 nDeferredCons;                  /* Number of deferred fk violations */
9400   Savepoint *pNext;                   /* Parent savepoint (if any) */
9401 };
9402
9403 /*
9404 ** The following are used as the second parameter to sqlite3Savepoint(),
9405 ** and as the P1 argument to the OP_Savepoint instruction.
9406 */
9407 #define SAVEPOINT_BEGIN      0
9408 #define SAVEPOINT_RELEASE    1
9409 #define SAVEPOINT_ROLLBACK   2
9410
9411
9412 /*
9413 ** Each SQLite module (virtual table definition) is defined by an
9414 ** instance of the following structure, stored in the sqlite3.aModule
9415 ** hash table.
9416 */
9417 struct Module {
9418   const sqlite3_module *pModule;       /* Callback pointers */
9419   const char *zName;                   /* Name passed to create_module() */
9420   void *pAux;                          /* pAux passed to create_module() */
9421   void (*xDestroy)(void *);            /* Module destructor function */
9422 };
9423
9424 /*
9425 ** information about each column of an SQL table is held in an instance
9426 ** of this structure.
9427 */
9428 struct Column {
9429   char *zName;     /* Name of this column */
9430   Expr *pDflt;     /* Default value of this column */
9431   char *zDflt;     /* Original text of the default value */
9432   char *zType;     /* Data type for this column */
9433   char *zColl;     /* Collating sequence.  If NULL, use the default */
9434   u8 notNull;      /* True if there is a NOT NULL constraint */
9435   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9436   char affinity;   /* One of the SQLITE_AFF_... values */
9437 #ifndef SQLITE_OMIT_VIRTUALTABLE
9438   u8 isHidden;     /* True if this column is 'hidden' */
9439 #endif
9440 };
9441
9442 /*
9443 ** A "Collating Sequence" is defined by an instance of the following
9444 ** structure. Conceptually, a collating sequence consists of a name and
9445 ** a comparison routine that defines the order of that sequence.
9446 **
9447 ** There may two separate implementations of the collation function, one
9448 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9449 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9450 ** native byte order. When a collation sequence is invoked, SQLite selects
9451 ** the version that will require the least expensive encoding
9452 ** translations, if any.
9453 **
9454 ** The CollSeq.pUser member variable is an extra parameter that passed in
9455 ** as the first argument to the UTF-8 comparison function, xCmp.
9456 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9457 ** xCmp16.
9458 **
9459 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9460 ** collating sequence is undefined.  Indices built on an undefined
9461 ** collating sequence may not be read or written.
9462 */
9463 struct CollSeq {
9464   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9465   u8 enc;               /* Text encoding handled by xCmp() */
9466   u8 type;              /* One of the SQLITE_COLL_... values below */
9467   void *pUser;          /* First argument to xCmp() */
9468   int (*xCmp)(void*,int, const void*, int, const void*);
9469   void (*xDel)(void*);  /* Destructor for pUser */
9470 };
9471
9472 /*
9473 ** Allowed values of CollSeq.type:
9474 */
9475 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9476 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9477 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9478 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9479
9480 /*
9481 ** A sort order can be either ASC or DESC.
9482 */
9483 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9484 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9485
9486 /*
9487 ** Column affinity types.
9488 **
9489 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9490 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9491 ** the speed a little by numbering the values consecutively.  
9492 **
9493 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9494 ** when multiple affinity types are concatenated into a string and
9495 ** used as the P4 operand, they will be more readable.
9496 **
9497 ** Note also that the numeric types are grouped together so that testing
9498 ** for a numeric type is a single comparison.
9499 */
9500 #define SQLITE_AFF_TEXT     'a'
9501 #define SQLITE_AFF_NONE     'b'
9502 #define SQLITE_AFF_NUMERIC  'c'
9503 #define SQLITE_AFF_INTEGER  'd'
9504 #define SQLITE_AFF_REAL     'e'
9505
9506 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9507
9508 /*
9509 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9510 ** affinity value. 
9511 */
9512 #define SQLITE_AFF_MASK     0x67
9513
9514 /*
9515 ** Additional bit values that can be ORed with an affinity without
9516 ** changing the affinity.
9517 */
9518 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9519 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9520 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9521
9522 /*
9523 ** An object of this type is created for each virtual table present in
9524 ** the database schema. 
9525 **
9526 ** If the database schema is shared, then there is one instance of this
9527 ** structure for each database connection (sqlite3*) that uses the shared
9528 ** schema. This is because each database connection requires its own unique
9529 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9530 ** implementation. sqlite3_vtab* handles can not be shared between 
9531 ** database connections, even when the rest of the in-memory database 
9532 ** schema is shared, as the implementation often stores the database
9533 ** connection handle passed to it via the xConnect() or xCreate() method
9534 ** during initialization internally. This database connection handle may
9535 ** then be used by the virtual table implementation to access real tables 
9536 ** within the database. So that they appear as part of the callers 
9537 ** transaction, these accesses need to be made via the same database 
9538 ** connection as that used to execute SQL operations on the virtual table.
9539 **
9540 ** All VTable objects that correspond to a single table in a shared
9541 ** database schema are initially stored in a linked-list pointed to by
9542 ** the Table.pVTable member variable of the corresponding Table object.
9543 ** When an sqlite3_prepare() operation is required to access the virtual
9544 ** table, it searches the list for the VTable that corresponds to the
9545 ** database connection doing the preparing so as to use the correct
9546 ** sqlite3_vtab* handle in the compiled query.
9547 **
9548 ** When an in-memory Table object is deleted (for example when the
9549 ** schema is being reloaded for some reason), the VTable objects are not 
9550 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9551 ** immediately. Instead, they are moved from the Table.pVTable list to
9552 ** another linked list headed by the sqlite3.pDisconnect member of the
9553 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9554 ** next time a statement is prepared using said sqlite3*. This is done
9555 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9556 ** Refer to comments above function sqlite3VtabUnlockList() for an
9557 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9558 ** list without holding the corresponding sqlite3.mutex mutex.
9559 **
9560 ** The memory for objects of this type is always allocated by 
9561 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9562 ** the first argument.
9563 */
9564 struct VTable {
9565   sqlite3 *db;              /* Database connection associated with this table */
9566   Module *pMod;             /* Pointer to module implementation */
9567   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9568   int nRef;                 /* Number of pointers to this structure */
9569   VTable *pNext;            /* Next in linked list (see above) */
9570 };
9571
9572 /*
9573 ** Each SQL table is represented in memory by an instance of the
9574 ** following structure.
9575 **
9576 ** Table.zName is the name of the table.  The case of the original
9577 ** CREATE TABLE statement is stored, but case is not significant for
9578 ** comparisons.
9579 **
9580 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9581 ** pointer to an array of Column structures, one for each column.
9582 **
9583 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9584 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9585 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9586 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9587 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9588 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9589 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9590 **
9591 ** Table.tnum is the page number for the root BTree page of the table in the
9592 ** database file.  If Table.iDb is the index of the database table backend
9593 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9594 ** holds temporary tables and indices.  If TF_Ephemeral is set
9595 ** then the table is stored in a file that is automatically deleted
9596 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9597 ** refers VDBE cursor number that holds the table open, not to the root
9598 ** page number.  Transient tables are used to hold the results of a
9599 ** sub-query that appears instead of a real table name in the FROM clause 
9600 ** of a SELECT statement.
9601 */
9602 struct Table {
9603   char *zName;         /* Name of the table or view */
9604   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9605   int nCol;            /* Number of columns in this table */
9606   Column *aCol;        /* Information about each column */
9607   Index *pIndex;       /* List of SQL indexes on this table. */
9608   int tnum;            /* Root BTree node for this table (see note above) */
9609   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9610   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9611   u16 nRef;            /* Number of pointers to this Table */
9612   u8 tabFlags;         /* Mask of TF_* values */
9613   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9614   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9615   char *zColAff;       /* String defining the affinity of each column */
9616 #ifndef SQLITE_OMIT_CHECK
9617   Expr *pCheck;        /* The AND of all CHECK constraints */
9618 #endif
9619 #ifndef SQLITE_OMIT_ALTERTABLE
9620   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9621 #endif
9622 #ifndef SQLITE_OMIT_VIRTUALTABLE
9623   VTable *pVTable;     /* List of VTable objects. */
9624   int nModuleArg;      /* Number of arguments to the module */
9625   char **azModuleArg;  /* Text of all module args. [0] is module name */
9626 #endif
9627   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9628   Schema *pSchema;     /* Schema that contains this table */
9629   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9630 };
9631
9632 /*
9633 ** Allowed values for Tabe.tabFlags.
9634 */
9635 #define TF_Readonly        0x01    /* Read-only system table */
9636 #define TF_Ephemeral       0x02    /* An ephemeral table */
9637 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9638 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9639 #define TF_Virtual         0x10    /* Is a virtual table */
9640 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9641
9642
9643
9644 /*
9645 ** Test to see whether or not a table is a virtual table.  This is
9646 ** done as a macro so that it will be optimized out when virtual
9647 ** table support is omitted from the build.
9648 */
9649 #ifndef SQLITE_OMIT_VIRTUALTABLE
9650 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9651 #  define IsHiddenColumn(X) ((X)->isHidden)
9652 #else
9653 #  define IsVirtual(X)      0
9654 #  define IsHiddenColumn(X) 0
9655 #endif
9656
9657 /*
9658 ** Each foreign key constraint is an instance of the following structure.
9659 **
9660 ** A foreign key is associated with two tables.  The "from" table is
9661 ** the table that contains the REFERENCES clause that creates the foreign
9662 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9663 ** Consider this example:
9664 **
9665 **     CREATE TABLE ex1(
9666 **       a INTEGER PRIMARY KEY,
9667 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9668 **     );
9669 **
9670 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9671 **
9672 ** Each REFERENCES clause generates an instance of the following structure
9673 ** which is attached to the from-table.  The to-table need not exist when
9674 ** the from-table is created.  The existence of the to-table is not checked.
9675 */
9676 struct FKey {
9677   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9678   FKey *pNextFrom;  /* Next foreign key in pFrom */
9679   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9680   FKey *pNextTo;    /* Next foreign key on table named zTo */
9681   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9682   int nCol;         /* Number of columns in this key */
9683   /* EV: R-30323-21917 */
9684   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9685   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9686   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9687   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9688     int iFrom;         /* Index of column in pFrom */
9689     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9690   } aCol[1];        /* One entry for each of nCol column s */
9691 };
9692
9693 /*
9694 ** SQLite supports many different ways to resolve a constraint
9695 ** error.  ROLLBACK processing means that a constraint violation
9696 ** causes the operation in process to fail and for the current transaction
9697 ** to be rolled back.  ABORT processing means the operation in process
9698 ** fails and any prior changes from that one operation are backed out,
9699 ** but the transaction is not rolled back.  FAIL processing means that
9700 ** the operation in progress stops and returns an error code.  But prior
9701 ** changes due to the same operation are not backed out and no rollback
9702 ** occurs.  IGNORE means that the particular row that caused the constraint
9703 ** error is not inserted or updated.  Processing continues and no error
9704 ** is returned.  REPLACE means that preexisting database rows that caused
9705 ** a UNIQUE constraint violation are removed so that the new insert or
9706 ** update can proceed.  Processing continues and no error is reported.
9707 **
9708 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9709 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9710 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9711 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9712 ** referenced table row is propagated into the row that holds the
9713 ** foreign key.
9714 ** 
9715 ** The following symbolic values are used to record which type
9716 ** of action to take.
9717 */
9718 #define OE_None     0   /* There is no constraint to check */
9719 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9720 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9721 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9722 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9723 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9724
9725 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9726 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9727 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9728 #define OE_Cascade  9   /* Cascade the changes */
9729
9730 #define OE_Default  99  /* Do whatever the default action is */
9731
9732
9733 /*
9734 ** An instance of the following structure is passed as the first
9735 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9736 ** comparison of the two index keys.
9737 */
9738 struct KeyInfo {
9739   sqlite3 *db;        /* The database connection */
9740   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9741   u16 nField;         /* Number of entries in aColl[] */
9742   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9743   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9744 };
9745
9746 /*
9747 ** An instance of the following structure holds information about a
9748 ** single index record that has already been parsed out into individual
9749 ** values.
9750 **
9751 ** A record is an object that contains one or more fields of data.
9752 ** Records are used to store the content of a table row and to store
9753 ** the key of an index.  A blob encoding of a record is created by
9754 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9755 ** OP_Column opcode.
9756 **
9757 ** This structure holds a record that has already been disassembled
9758 ** into its constituent fields.
9759 */
9760 struct UnpackedRecord {
9761   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9762   u16 nField;         /* Number of entries in apMem[] */
9763   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9764   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9765   Mem *aMem;          /* Values */
9766 };
9767
9768 /*
9769 ** Allowed values of UnpackedRecord.flags
9770 */
9771 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9772 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9773 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9774 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9775 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9776 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9777
9778 /*
9779 ** Each SQL index is represented in memory by an
9780 ** instance of the following structure.
9781 **
9782 ** The columns of the table that are to be indexed are described
9783 ** by the aiColumn[] field of this structure.  For example, suppose
9784 ** we have the following table and index:
9785 **
9786 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9787 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9788 **
9789 ** In the Table structure describing Ex1, nCol==3 because there are
9790 ** three columns in the table.  In the Index structure describing
9791 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9792 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9793 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9794 ** The second column to be indexed (c1) has an index of 0 in
9795 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9796 **
9797 ** The Index.onError field determines whether or not the indexed columns
9798 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9799 ** it means this is not a unique index.  Otherwise it is a unique index
9800 ** and the value of Index.onError indicate the which conflict resolution 
9801 ** algorithm to employ whenever an attempt is made to insert a non-unique
9802 ** element.
9803 */
9804 struct Index {
9805   char *zName;     /* Name of this index */
9806   int nColumn;     /* Number of columns in the table used by this index */
9807   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9808   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9809   Table *pTable;   /* The SQL table being indexed */
9810   int tnum;        /* Page containing root of this index in database file */
9811   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9812   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9813   u8 bUnordered;   /* Use this index for == or IN queries only */
9814   char *zColAff;   /* String defining the affinity of each column */
9815   Index *pNext;    /* The next index associated with the same table */
9816   Schema *pSchema; /* Schema containing this index */
9817   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9818   char **azColl;   /* Array of collation sequence names for index */
9819   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9820 };
9821
9822 /*
9823 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9824 ** using a structure of this type.
9825 */
9826 struct IndexSample {
9827   union {
9828     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9829     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9830   } u;
9831   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9832   u8 nByte;         /* Size in byte of text or blob. */
9833 };
9834
9835 /*
9836 ** Each token coming out of the lexer is an instance of
9837 ** this structure.  Tokens are also used as part of an expression.
9838 **
9839 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9840 ** may contain random values.  Do not make any assumptions about Token.dyn
9841 ** and Token.n when Token.z==0.
9842 */
9843 struct Token {
9844   const char *z;     /* Text of the token.  Not NULL-terminated! */
9845   unsigned int n;    /* Number of characters in this token */
9846 };
9847
9848 /*
9849 ** An instance of this structure contains information needed to generate
9850 ** code for a SELECT that contains aggregate functions.
9851 **
9852 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9853 ** pointer to this structure.  The Expr.iColumn field is the index in
9854 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9855 ** code for that node.
9856 **
9857 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9858 ** original Select structure that describes the SELECT statement.  These
9859 ** fields do not need to be freed when deallocating the AggInfo structure.
9860 */
9861 struct AggInfo {
9862   u8 directMode;          /* Direct rendering mode means take data directly
9863                           ** from source tables rather than from accumulators */
9864   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9865                           ** than the source table */
9866   int sortingIdx;         /* Cursor number of the sorting index */
9867   ExprList *pGroupBy;     /* The group by clause */
9868   int nSortingColumn;     /* Number of columns in the sorting index */
9869   struct AggInfo_col {    /* For each column used in source tables */
9870     Table *pTab;             /* Source table */
9871     int iTable;              /* Cursor number of the source table */
9872     int iColumn;             /* Column number within the source table */
9873     int iSorterColumn;       /* Column number in the sorting index */
9874     int iMem;                /* Memory location that acts as accumulator */
9875     Expr *pExpr;             /* The original expression */
9876   } *aCol;
9877   int nColumn;            /* Number of used entries in aCol[] */
9878   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9879   int nAccumulator;       /* Number of columns that show through to the output.
9880                           ** Additional columns are used only as parameters to
9881                           ** aggregate functions */
9882   struct AggInfo_func {   /* For each aggregate function */
9883     Expr *pExpr;             /* Expression encoding the function */
9884     FuncDef *pFunc;          /* The aggregate function implementation */
9885     int iMem;                /* Memory location that acts as accumulator */
9886     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9887   } *aFunc;
9888   int nFunc;              /* Number of entries in aFunc[] */
9889   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9890 };
9891
9892 /*
9893 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9894 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9895 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9896 ** it uses less memory in the Expr object, which is a big memory user
9897 ** in systems with lots of prepared statements.  And few applications
9898 ** need more than about 10 or 20 variables.  But some extreme users want
9899 ** to have prepared statements with over 32767 variables, and for them
9900 ** the option is available (at compile-time).
9901 */
9902 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9903 typedef i16 ynVar;
9904 #else
9905 typedef int ynVar;
9906 #endif
9907
9908 /*
9909 ** Each node of an expression in the parse tree is an instance
9910 ** of this structure.
9911 **
9912 ** Expr.op is the opcode. The integer parser token codes are reused
9913 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9914 ** code representing the ">=" operator. This same integer code is reused
9915 ** to represent the greater-than-or-equal-to operator in the expression
9916 ** tree.
9917 **
9918 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9919 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9920 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9921 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9922 ** then Expr.token contains the name of the function.
9923 **
9924 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9925 ** binary operator. Either or both may be NULL.
9926 **
9927 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9928 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9929 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9930 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9931 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9932 ** valid.
9933 **
9934 ** An expression of the form ID or ID.ID refers to a column in a table.
9935 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9936 ** the integer cursor number of a VDBE cursor pointing to that table and
9937 ** Expr.iColumn is the column number for the specific column.  If the
9938 ** expression is used as a result in an aggregate SELECT, then the
9939 ** value is also stored in the Expr.iAgg column in the aggregate so that
9940 ** it can be accessed after all aggregates are computed.
9941 **
9942 ** If the expression is an unbound variable marker (a question mark 
9943 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9944 ** number for that variable.
9945 **
9946 ** If the expression is a subquery then Expr.iColumn holds an integer
9947 ** register number containing the result of the subquery.  If the
9948 ** subquery gives a constant result, then iTable is -1.  If the subquery
9949 ** gives a different answer at different times during statement processing
9950 ** then iTable is the address of a subroutine that computes the subquery.
9951 **
9952 ** If the Expr is of type OP_Column, and the table it is selecting from
9953 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9954 ** corresponding table definition.
9955 **
9956 ** ALLOCATION NOTES:
9957 **
9958 ** Expr objects can use a lot of memory space in database schema.  To
9959 ** help reduce memory requirements, sometimes an Expr object will be
9960 ** truncated.  And to reduce the number of memory allocations, sometimes
9961 ** two or more Expr objects will be stored in a single memory allocation,
9962 ** together with Expr.zToken strings.
9963 **
9964 ** If the EP_Reduced and EP_TokenOnly flags are set when
9965 ** an Expr object is truncated.  When EP_Reduced is set, then all
9966 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9967 ** are contained within the same memory allocation.  Note, however, that
9968 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9969 ** allocated, regardless of whether or not EP_Reduced is set.
9970 */
9971 struct Expr {
9972   u8 op;                 /* Operation performed by this node */
9973   char affinity;         /* The affinity of the column or 0 if not a column */
9974   u16 flags;             /* Various flags.  EP_* See below */
9975   union {
9976     char *zToken;          /* Token value. Zero terminated and dequoted */
9977     int iValue;            /* Non-negative integer value if EP_IntValue */
9978   } u;
9979
9980   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9981   ** space is allocated for the fields below this point. An attempt to
9982   ** access them will result in a segfault or malfunction. 
9983   *********************************************************************/
9984
9985   Expr *pLeft;           /* Left subnode */
9986   Expr *pRight;          /* Right subnode */
9987   union {
9988     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9989     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9990   } x;
9991   CollSeq *pColl;        /* The collation type of the column or 0 */
9992
9993   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9994   ** space is allocated for the fields below this point. An attempt to
9995   ** access them will result in a segfault or malfunction.
9996   *********************************************************************/
9997
9998   int iTable;            /* TK_COLUMN: cursor number of table holding column
9999                          ** TK_REGISTER: register number
10000                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10001   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10002                          ** TK_VARIABLE: variable number (always >= 1). */
10003   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10004   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10005   u8 flags2;             /* Second set of flags.  EP2_... */
10006   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10007   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10008   Table *pTab;           /* Table for TK_COLUMN expressions. */
10009 #if SQLITE_MAX_EXPR_DEPTH>0
10010   int nHeight;           /* Height of the tree headed by this node */
10011 #endif
10012 };
10013
10014 /*
10015 ** The following are the meanings of bits in the Expr.flags field.
10016 */
10017 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10018 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10019 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10020 #define EP_Error      0x0008  /* Expression contains one or more errors */
10021 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10022 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10023 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10024 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10025 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10026 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10027 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10028 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10029
10030 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10031 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10032 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10033
10034 /*
10035 ** The following are the meanings of bits in the Expr.flags2 field.
10036 */
10037 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10038 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10039
10040 /*
10041 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10042 ** flag on an expression structure.  This flag is used for VV&A only.  The
10043 ** routine is implemented as a macro that only works when in debugging mode,
10044 ** so as not to burden production code.
10045 */
10046 #ifdef SQLITE_DEBUG
10047 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10048 #else
10049 # define ExprSetIrreducible(X)
10050 #endif
10051
10052 /*
10053 ** These macros can be used to test, set, or clear bits in the 
10054 ** Expr.flags field.
10055 */
10056 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10057 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10058 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10059 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10060
10061 /*
10062 ** Macros to determine the number of bytes required by a normal Expr 
10063 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10064 ** and an Expr struct with the EP_TokenOnly flag set.
10065 */
10066 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10067 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10068 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10069
10070 /*
10071 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10072 ** above sqlite3ExprDup() for details.
10073 */
10074 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10075
10076 /*
10077 ** A list of expressions.  Each expression may optionally have a
10078 ** name.  An expr/name combination can be used in several ways, such
10079 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10080 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10081 ** also be used as the argument to a function, in which case the a.zName
10082 ** field is not used.
10083 */
10084 struct ExprList {
10085   int nExpr;             /* Number of expressions on the list */
10086   int nAlloc;            /* Number of entries allocated below */
10087   int iECursor;          /* VDBE Cursor associated with this ExprList */
10088   struct ExprList_item {
10089     Expr *pExpr;           /* The list of expressions */
10090     char *zName;           /* Token associated with this expression */
10091     char *zSpan;           /* Original text of the expression */
10092     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10093     u8 done;               /* A flag to indicate when processing is finished */
10094     u16 iCol;              /* For ORDER BY, column number in result set */
10095     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10096   } *a;                  /* One entry for each expression */
10097 };
10098
10099 /*
10100 ** An instance of this structure is used by the parser to record both
10101 ** the parse tree for an expression and the span of input text for an
10102 ** expression.
10103 */
10104 struct ExprSpan {
10105   Expr *pExpr;          /* The expression parse tree */
10106   const char *zStart;   /* First character of input text */
10107   const char *zEnd;     /* One character past the end of input text */
10108 };
10109
10110 /*
10111 ** An instance of this structure can hold a simple list of identifiers,
10112 ** such as the list "a,b,c" in the following statements:
10113 **
10114 **      INSERT INTO t(a,b,c) VALUES ...;
10115 **      CREATE INDEX idx ON t(a,b,c);
10116 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10117 **
10118 ** The IdList.a.idx field is used when the IdList represents the list of
10119 ** column names after a table name in an INSERT statement.  In the statement
10120 **
10121 **     INSERT INTO t(a,b,c) ...
10122 **
10123 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10124 */
10125 struct IdList {
10126   struct IdList_item {
10127     char *zName;      /* Name of the identifier */
10128     int idx;          /* Index in some Table.aCol[] of a column named zName */
10129   } *a;
10130   int nId;         /* Number of identifiers on the list */
10131   int nAlloc;      /* Number of entries allocated for a[] below */
10132 };
10133
10134 /*
10135 ** The bitmask datatype defined below is used for various optimizations.
10136 **
10137 ** Changing this from a 64-bit to a 32-bit type limits the number of
10138 ** tables in a join to 32 instead of 64.  But it also reduces the size
10139 ** of the library by 738 bytes on ix86.
10140 */
10141 typedef u64 Bitmask;
10142
10143 /*
10144 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10145 */
10146 #define BMS  ((int)(sizeof(Bitmask)*8))
10147
10148 /*
10149 ** The following structure describes the FROM clause of a SELECT statement.
10150 ** Each table or subquery in the FROM clause is a separate element of
10151 ** the SrcList.a[] array.
10152 **
10153 ** With the addition of multiple database support, the following structure
10154 ** can also be used to describe a particular table such as the table that
10155 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10156 ** such a table must be a simple name: ID.  But in SQLite, the table can
10157 ** now be identified by a database name, a dot, then the table name: ID.ID.
10158 **
10159 ** The jointype starts out showing the join type between the current table
10160 ** and the next table on the list.  The parser builds the list this way.
10161 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10162 ** jointype expresses the join between the table and the previous table.
10163 **
10164 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10165 ** contains more than 63 columns and the 64-th or later column is used.
10166 */
10167 struct SrcList {
10168   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10169   i16 nAlloc;      /* Number of entries allocated in a[] below */
10170   struct SrcList_item {
10171     char *zDatabase;  /* Name of database holding this table */
10172     char *zName;      /* Name of the table */
10173     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10174     Table *pTab;      /* An SQL table corresponding to zName */
10175     Select *pSelect;  /* A SELECT statement used in place of a table name */
10176     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10177     u8 jointype;      /* Type of join between this able and the previous */
10178     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10179 #ifndef SQLITE_OMIT_EXPLAIN
10180     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10181 #endif
10182     int iCursor;      /* The VDBE cursor number used to access this table */
10183     Expr *pOn;        /* The ON clause of a join */
10184     IdList *pUsing;   /* The USING clause of a join */
10185     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10186     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10187     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10188   } a[1];             /* One entry for each identifier on the list */
10189 };
10190
10191 /*
10192 ** Permitted values of the SrcList.a.jointype field
10193 */
10194 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10195 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10196 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10197 #define JT_LEFT      0x0008    /* Left outer join */
10198 #define JT_RIGHT     0x0010    /* Right outer join */
10199 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10200 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10201
10202
10203 /*
10204 ** A WherePlan object holds information that describes a lookup
10205 ** strategy.
10206 **
10207 ** This object is intended to be opaque outside of the where.c module.
10208 ** It is included here only so that that compiler will know how big it
10209 ** is.  None of the fields in this object should be used outside of
10210 ** the where.c module.
10211 **
10212 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10213 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10214 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10215 ** case that more than one of these conditions is true.
10216 */
10217 struct WherePlan {
10218   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10219   u32 nEq;                       /* Number of == constraints */
10220   double nRow;                   /* Estimated number of rows (for EQP) */
10221   union {
10222     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10223     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10224     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10225   } u;
10226 };
10227
10228 /*
10229 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10230 ** structure contains a single instance of this structure.  This structure
10231 ** is intended to be private the the where.c module and should not be
10232 ** access or modified by other modules.
10233 **
10234 ** The pIdxInfo field is used to help pick the best index on a
10235 ** virtual table.  The pIdxInfo pointer contains indexing
10236 ** information for the i-th table in the FROM clause before reordering.
10237 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10238 ** All other information in the i-th WhereLevel object for the i-th table
10239 ** after FROM clause ordering.
10240 */
10241 struct WhereLevel {
10242   WherePlan plan;       /* query plan for this element of the FROM clause */
10243   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10244   int iTabCur;          /* The VDBE cursor used to access the table */
10245   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10246   int addrBrk;          /* Jump here to break out of the loop */
10247   int addrNxt;          /* Jump here to start the next IN combination */
10248   int addrCont;         /* Jump here to continue with the next loop cycle */
10249   int addrFirst;        /* First instruction of interior of the loop */
10250   u8 iFrom;             /* Which entry in the FROM clause */
10251   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10252   int p1, p2;           /* Operands of the opcode used to ends the loop */
10253   union {               /* Information that depends on plan.wsFlags */
10254     struct {
10255       int nIn;              /* Number of entries in aInLoop[] */
10256       struct InLoop {
10257         int iCur;              /* The VDBE cursor used by this IN operator */
10258         int addrInTop;         /* Top of the IN loop */
10259       } *aInLoop;           /* Information about each nested IN operator */
10260     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10261   } u;
10262
10263   /* The following field is really not part of the current level.  But
10264   ** we need a place to cache virtual table index information for each
10265   ** virtual table in the FROM clause and the WhereLevel structure is
10266   ** a convenient place since there is one WhereLevel for each FROM clause
10267   ** element.
10268   */
10269   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10270 };
10271
10272 /*
10273 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10274 ** and the WhereInfo.wctrlFlags member.
10275 */
10276 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10277 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10278 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10279 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10280 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10281 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10282 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10283 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10284 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10285
10286 /*
10287 ** The WHERE clause processing routine has two halves.  The
10288 ** first part does the start of the WHERE loop and the second
10289 ** half does the tail of the WHERE loop.  An instance of
10290 ** this structure is returned by the first half and passed
10291 ** into the second half to give some continuity.
10292 */
10293 struct WhereInfo {
10294   Parse *pParse;       /* Parsing and code generating context */
10295   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10296   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10297   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10298   SrcList *pTabList;             /* List of tables in the join */
10299   int iTop;                      /* The very beginning of the WHERE loop */
10300   int iContinue;                 /* Jump here to continue with next record */
10301   int iBreak;                    /* Jump here to break out of the loop */
10302   int nLevel;                    /* Number of nested loop */
10303   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10304   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10305   double nRowOut;                /* Estimated number of output rows */
10306   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10307 };
10308
10309 /*
10310 ** A NameContext defines a context in which to resolve table and column
10311 ** names.  The context consists of a list of tables (the pSrcList) field and
10312 ** a list of named expression (pEList).  The named expression list may
10313 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10314 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10315 ** pEList corresponds to the result set of a SELECT and is NULL for
10316 ** other statements.
10317 **
10318 ** NameContexts can be nested.  When resolving names, the inner-most 
10319 ** context is searched first.  If no match is found, the next outer
10320 ** context is checked.  If there is still no match, the next context
10321 ** is checked.  This process continues until either a match is found
10322 ** or all contexts are check.  When a match is found, the nRef member of
10323 ** the context containing the match is incremented. 
10324 **
10325 ** Each subquery gets a new NameContext.  The pNext field points to the
10326 ** NameContext in the parent query.  Thus the process of scanning the
10327 ** NameContext list corresponds to searching through successively outer
10328 ** subqueries looking for a match.
10329 */
10330 struct NameContext {
10331   Parse *pParse;       /* The parser */
10332   SrcList *pSrcList;   /* One or more tables used to resolve names */
10333   ExprList *pEList;    /* Optional list of named expressions */
10334   int nRef;            /* Number of names resolved by this context */
10335   int nErr;            /* Number of errors encountered while resolving names */
10336   u8 allowAgg;         /* Aggregate functions allowed here */
10337   u8 hasAgg;           /* True if aggregates are seen */
10338   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10339   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10340   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10341   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10342 };
10343
10344 /*
10345 ** An instance of the following structure contains all information
10346 ** needed to generate code for a single SELECT statement.
10347 **
10348 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10349 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10350 ** limit and nOffset to the value of the offset (or 0 if there is not
10351 ** offset).  But later on, nLimit and nOffset become the memory locations
10352 ** in the VDBE that record the limit and offset counters.
10353 **
10354 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10355 ** These addresses must be stored so that we can go back and fill in
10356 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10357 ** the number of columns in P2 can be computed at the same time
10358 ** as the OP_OpenEphm instruction is coded because not
10359 ** enough information about the compound query is known at that point.
10360 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10361 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10362 ** sequences for the ORDER BY clause.
10363 */
10364 struct Select {
10365   ExprList *pEList;      /* The fields of the result */
10366   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10367   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10368   u16 selFlags;          /* Various SF_* values */
10369   SrcList *pSrc;         /* The FROM clause */
10370   Expr *pWhere;          /* The WHERE clause */
10371   ExprList *pGroupBy;    /* The GROUP BY clause */
10372   Expr *pHaving;         /* The HAVING clause */
10373   ExprList *pOrderBy;    /* The ORDER BY clause */
10374   Select *pPrior;        /* Prior select in a compound select statement */
10375   Select *pNext;         /* Next select to the left in a compound */
10376   Select *pRightmost;    /* Right-most select in a compound select statement */
10377   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10378   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10379   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10380   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10381   double nSelectRow;     /* Estimated number of result rows */
10382 };
10383
10384 /*
10385 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10386 ** "Select Flag".
10387 */
10388 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10389 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10390 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10391 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10392 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10393 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10394
10395
10396 /*
10397 ** The results of a select can be distributed in several ways.  The
10398 ** "SRT" prefix means "SELECT Result Type".
10399 */
10400 #define SRT_Union        1  /* Store result as keys in an index */
10401 #define SRT_Except       2  /* Remove result from a UNION index */
10402 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10403 #define SRT_Discard      4  /* Do not save the results anywhere */
10404
10405 /* The ORDER BY clause is ignored for all of the above */
10406 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10407
10408 #define SRT_Output       5  /* Output each row of result */
10409 #define SRT_Mem          6  /* Store result in a memory cell */
10410 #define SRT_Set          7  /* Store results as keys in an index */
10411 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10412 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10413 #define SRT_Coroutine   10  /* Generate a single row of result */
10414
10415 /*
10416 ** A structure used to customize the behavior of sqlite3Select(). See
10417 ** comments above sqlite3Select() for details.
10418 */
10419 typedef struct SelectDest SelectDest;
10420 struct SelectDest {
10421   u8 eDest;         /* How to dispose of the results */
10422   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10423   int iParm;        /* A parameter used by the eDest disposal method */
10424   int iMem;         /* Base register where results are written */
10425   int nMem;         /* Number of registers allocated */
10426 };
10427
10428 /*
10429 ** During code generation of statements that do inserts into AUTOINCREMENT 
10430 ** tables, the following information is attached to the Table.u.autoInc.p
10431 ** pointer of each autoincrement table to record some side information that
10432 ** the code generator needs.  We have to keep per-table autoincrement
10433 ** information in case inserts are down within triggers.  Triggers do not
10434 ** normally coordinate their activities, but we do need to coordinate the
10435 ** loading and saving of autoincrement information.
10436 */
10437 struct AutoincInfo {
10438   AutoincInfo *pNext;   /* Next info block in a list of them all */
10439   Table *pTab;          /* Table this info block refers to */
10440   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10441   int regCtr;           /* Memory register holding the rowid counter */
10442 };
10443
10444 /*
10445 ** Size of the column cache
10446 */
10447 #ifndef SQLITE_N_COLCACHE
10448 # define SQLITE_N_COLCACHE 10
10449 #endif
10450
10451 /*
10452 ** At least one instance of the following structure is created for each 
10453 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10454 ** statement. All such objects are stored in the linked list headed at
10455 ** Parse.pTriggerPrg and deleted once statement compilation has been
10456 ** completed.
10457 **
10458 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10459 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10460 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10461 ** The Parse.pTriggerPrg list never contains two entries with the same
10462 ** values for both pTrigger and orconf.
10463 **
10464 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10465 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10466 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10467 ** a mask of new.* columns used by the program.
10468 */
10469 struct TriggerPrg {
10470   Trigger *pTrigger;      /* Trigger this program was coded from */
10471   int orconf;             /* Default ON CONFLICT policy */
10472   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10473   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10474   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10475 };
10476
10477 /*
10478 ** The yDbMask datatype for the bitmask of all attached databases.
10479 */
10480 #if SQLITE_MAX_ATTACHED>30
10481   typedef sqlite3_uint64 yDbMask;
10482 #else
10483   typedef unsigned int yDbMask;
10484 #endif
10485
10486 /*
10487 ** An SQL parser context.  A copy of this structure is passed through
10488 ** the parser and down into all the parser action routine in order to
10489 ** carry around information that is global to the entire parse.
10490 **
10491 ** The structure is divided into two parts.  When the parser and code
10492 ** generate call themselves recursively, the first part of the structure
10493 ** is constant but the second part is reset at the beginning and end of
10494 ** each recursion.
10495 **
10496 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10497 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10498 ** used to store the set of table-locks required by the statement being
10499 ** compiled. Function sqlite3TableLock() is used to add entries to the
10500 ** list.
10501 */
10502 struct Parse {
10503   sqlite3 *db;         /* The main database structure */
10504   int rc;              /* Return code from execution */
10505   char *zErrMsg;       /* An error message */
10506   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10507   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10508   u8 nameClash;        /* A permanent table name clashes with temp table name */
10509   u8 checkSchema;      /* Causes schema cookie check after an error */
10510   u8 nested;           /* Number of nested calls to the parser/code generator */
10511   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10512   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10513   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10514   int aTempReg[8];     /* Holding area for temporary registers */
10515   int nRangeReg;       /* Size of the temporary register block */
10516   int iRangeReg;       /* First register in temporary register block */
10517   int nErr;            /* Number of errors seen */
10518   int nTab;            /* Number of previously allocated VDBE cursors */
10519   int nMem;            /* Number of memory cells used so far */
10520   int nSet;            /* Number of sets used so far */
10521   int ckBase;          /* Base register of data during check constraints */
10522   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10523   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10524   u8 nColCache;        /* Number of entries in the column cache */
10525   u8 iColCache;        /* Next entry of the cache to replace */
10526   struct yColCache {
10527     int iTable;           /* Table cursor number */
10528     int iColumn;          /* Table column number */
10529     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10530     int iLevel;           /* Nesting level */
10531     int iReg;             /* Reg with value of this column. 0 means none. */
10532     int lru;              /* Least recently used entry has the smallest value */
10533   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10534   yDbMask writeMask;   /* Start a write transaction on these databases */
10535   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10536   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10537   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10538   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10539   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10540 #ifndef SQLITE_OMIT_SHARED_CACHE
10541   int nTableLock;        /* Number of locks in aTableLock */
10542   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10543 #endif
10544   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10545   int regRoot;         /* Register holding root page number for new objects */
10546   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10547   int nMaxArg;         /* Max args passed to user function by sub-program */
10548
10549   /* Information used while coding trigger programs. */
10550   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10551   Table *pTriggerTab;  /* Table triggers are being coded for */
10552   u32 oldmask;         /* Mask of old.* columns referenced */
10553   u32 newmask;         /* Mask of new.* columns referenced */
10554   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10555   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10556   u8 disableTriggers;  /* True to disable triggers */
10557   double nQueryLoop;   /* Estimated number of iterations of a query */
10558
10559   /* Above is constant between recursions.  Below is reset before and after
10560   ** each recursion */
10561
10562   int nVar;            /* Number of '?' variables seen in the SQL so far */
10563   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10564   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10565   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10566   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10567   int nAlias;          /* Number of aliased result set columns */
10568   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10569   int *aAlias;         /* Register used to hold aliased result */
10570   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10571   Token sNameToken;    /* Token with unqualified schema object name */
10572   Token sLastToken;    /* The last token parsed */
10573   const char *zTail;   /* All SQL text past the last semicolon parsed */
10574   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10575   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10576   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10577 #ifndef SQLITE_OMIT_VIRTUALTABLE
10578   Token sArg;                /* Complete text of a module argument */
10579   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10580   int nVtabLock;             /* Number of virtual tables to lock */
10581   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10582 #endif
10583   int nHeight;            /* Expression tree height of current sub-select */
10584   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10585   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10586
10587 #ifndef SQLITE_OMIT_EXPLAIN
10588   int iSelectId;
10589   int iNextSelectId;
10590 #endif
10591 };
10592
10593 #ifdef SQLITE_OMIT_VIRTUALTABLE
10594   #define IN_DECLARE_VTAB 0
10595 #else
10596   #define IN_DECLARE_VTAB (pParse->declareVtab)
10597 #endif
10598
10599 /*
10600 ** An instance of the following structure can be declared on a stack and used
10601 ** to save the Parse.zAuthContext value so that it can be restored later.
10602 */
10603 struct AuthContext {
10604   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10605   Parse *pParse;              /* The Parse structure */
10606 };
10607
10608 /*
10609 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10610 */
10611 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10612 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10613 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10614 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10615 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10616 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10617
10618 /*
10619  * Each trigger present in the database schema is stored as an instance of
10620  * struct Trigger. 
10621  *
10622  * Pointers to instances of struct Trigger are stored in two ways.
10623  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10624  *    database). This allows Trigger structures to be retrieved by name.
10625  * 2. All triggers associated with a single table form a linked list, using the
10626  *    pNext member of struct Trigger. A pointer to the first element of the
10627  *    linked list is stored as the "pTrigger" member of the associated
10628  *    struct Table.
10629  *
10630  * The "step_list" member points to the first element of a linked list
10631  * containing the SQL statements specified as the trigger program.
10632  */
10633 struct Trigger {
10634   char *zName;            /* The name of the trigger                        */
10635   char *table;            /* The table or view to which the trigger applies */
10636   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10637   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10638   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10639   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10640                              the <column-list> is stored here */
10641   Schema *pSchema;        /* Schema containing the trigger */
10642   Schema *pTabSchema;     /* Schema containing the table */
10643   TriggerStep *step_list; /* Link list of trigger program steps             */
10644   Trigger *pNext;         /* Next trigger associated with the table */
10645 };
10646
10647 /*
10648 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10649 ** determine which. 
10650 **
10651 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10652 ** In that cases, the constants below can be ORed together.
10653 */
10654 #define TRIGGER_BEFORE  1
10655 #define TRIGGER_AFTER   2
10656
10657 /*
10658  * An instance of struct TriggerStep is used to store a single SQL statement
10659  * that is a part of a trigger-program. 
10660  *
10661  * Instances of struct TriggerStep are stored in a singly linked list (linked
10662  * using the "pNext" member) referenced by the "step_list" member of the 
10663  * associated struct Trigger instance. The first element of the linked list is
10664  * the first step of the trigger-program.
10665  * 
10666  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10667  * "SELECT" statement. The meanings of the other members is determined by the 
10668  * value of "op" as follows:
10669  *
10670  * (op == TK_INSERT)
10671  * orconf    -> stores the ON CONFLICT algorithm
10672  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10673  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10674  * target    -> A token holding the quoted name of the table to insert into.
10675  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10676  *              this stores values to be inserted. Otherwise NULL.
10677  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10678  *              statement, then this stores the column-names to be
10679  *              inserted into.
10680  *
10681  * (op == TK_DELETE)
10682  * target    -> A token holding the quoted name of the table to delete from.
10683  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10684  *              Otherwise NULL.
10685  * 
10686  * (op == TK_UPDATE)
10687  * target    -> A token holding the quoted name of the table to update rows of.
10688  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10689  *              Otherwise NULL.
10690  * pExprList -> A list of the columns to update and the expressions to update
10691  *              them to. See sqlite3Update() documentation of "pChanges"
10692  *              argument.
10693  * 
10694  */
10695 struct TriggerStep {
10696   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10697   u8 orconf;           /* OE_Rollback etc. */
10698   Trigger *pTrig;      /* The trigger that this step is a part of */
10699   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10700   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10701   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10702   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10703   IdList *pIdList;     /* Column names for INSERT */
10704   TriggerStep *pNext;  /* Next in the link-list */
10705   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10706 };
10707
10708 /*
10709 ** The following structure contains information used by the sqliteFix...
10710 ** routines as they walk the parse tree to make database references
10711 ** explicit.  
10712 */
10713 typedef struct DbFixer DbFixer;
10714 struct DbFixer {
10715   Parse *pParse;      /* The parsing context.  Error messages written here */
10716   const char *zDb;    /* Make sure all objects are contained in this database */
10717   const char *zType;  /* Type of the container - used for error messages */
10718   const Token *pName; /* Name of the container - used for error messages */
10719 };
10720
10721 /*
10722 ** An objected used to accumulate the text of a string where we
10723 ** do not necessarily know how big the string will be in the end.
10724 */
10725 struct StrAccum {
10726   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10727   char *zBase;         /* A base allocation.  Not from malloc. */
10728   char *zText;         /* The string collected so far */
10729   int  nChar;          /* Length of the string so far */
10730   int  nAlloc;         /* Amount of space allocated in zText */
10731   int  mxAlloc;        /* Maximum allowed string length */
10732   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10733   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10734   u8   tooBig;         /* Becomes true if string size exceeds limits */
10735 };
10736
10737 /*
10738 ** A pointer to this structure is used to communicate information
10739 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10740 */
10741 typedef struct {
10742   sqlite3 *db;        /* The database being initialized */
10743   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10744   char **pzErrMsg;    /* Error message stored here */
10745   int rc;             /* Result code stored here */
10746 } InitData;
10747
10748 /*
10749 ** Structure containing global configuration data for the SQLite library.
10750 **
10751 ** This structure also contains some state information.
10752 */
10753 struct Sqlite3Config {
10754   int bMemstat;                     /* True to enable memory status */
10755   int bCoreMutex;                   /* True to enable core mutexing */
10756   int bFullMutex;                   /* True to enable full mutexing */
10757   int mxStrlen;                     /* Maximum string length */
10758   int szLookaside;                  /* Default lookaside buffer size */
10759   int nLookaside;                   /* Default lookaside buffer count */
10760   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10761   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10762   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10763   void *pHeap;                      /* Heap storage space */
10764   int nHeap;                        /* Size of pHeap[] */
10765   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10766   void *pScratch;                   /* Scratch memory */
10767   int szScratch;                    /* Size of each scratch buffer */
10768   int nScratch;                     /* Number of scratch buffers */
10769   void *pPage;                      /* Page cache memory */
10770   int szPage;                       /* Size of each page in pPage[] */
10771   int nPage;                        /* Number of pages in pPage[] */
10772   int mxParserStack;                /* maximum depth of the parser stack */
10773   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10774   /* The above might be initialized to non-zero.  The following need to always
10775   ** initially be zero, however. */
10776   int isInit;                       /* True after initialization has finished */
10777   int inProgress;                   /* True while initialization in progress */
10778   int isMutexInit;                  /* True after mutexes are initialized */
10779   int isMallocInit;                 /* True after malloc is initialized */
10780   int isPCacheInit;                 /* True after malloc is initialized */
10781   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10782   int nRefInitMutex;                /* Number of users of pInitMutex */
10783   void (*xLog)(void*,int,const char*); /* Function for logging */
10784   void *pLogArg;                       /* First argument to xLog() */
10785 };
10786
10787 /*
10788 ** Context pointer passed down through the tree-walk.
10789 */
10790 struct Walker {
10791   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10792   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10793   Parse *pParse;                            /* Parser context.  */
10794   union {                                   /* Extra data for callback */
10795     NameContext *pNC;                          /* Naming context */
10796     int i;                                     /* Integer value */
10797   } u;
10798 };
10799
10800 /* Forward declarations */
10801 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10802 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10803 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10804 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10805 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10806
10807 /*
10808 ** Return code from the parse-tree walking primitives and their
10809 ** callbacks.
10810 */
10811 #define WRC_Continue    0   /* Continue down into children */
10812 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10813 #define WRC_Abort       2   /* Abandon the tree walk */
10814
10815 /*
10816 ** Assuming zIn points to the first byte of a UTF-8 character,
10817 ** advance zIn to point to the first byte of the next UTF-8 character.
10818 */
10819 #define SQLITE_SKIP_UTF8(zIn) {                        \
10820   if( (*(zIn++))>=0xc0 ){                              \
10821     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10822   }                                                    \
10823 }
10824
10825 /*
10826 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10827 ** the same name but without the _BKPT suffix.  These macros invoke
10828 ** routines that report the line-number on which the error originated
10829 ** using sqlite3_log().  The routines also provide a convenient place
10830 ** to set a debugger breakpoint.
10831 */
10832 SQLITE_PRIVATE int sqlite3CorruptError(int);
10833 SQLITE_PRIVATE int sqlite3MisuseError(int);
10834 SQLITE_PRIVATE int sqlite3CantopenError(int);
10835 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10836 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10837 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10838
10839
10840 /*
10841 ** FTS4 is really an extension for FTS3.  It is enabled using the
10842 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10843 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10844 */
10845 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10846 # define SQLITE_ENABLE_FTS3
10847 #endif
10848
10849 /*
10850 ** The ctype.h header is needed for non-ASCII systems.  It is also
10851 ** needed by FTS3 when FTS3 is included in the amalgamation.
10852 */
10853 #if !defined(SQLITE_ASCII) || \
10854     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10855 # include <ctype.h>
10856 #endif
10857
10858 /*
10859 ** The following macros mimic the standard library functions toupper(),
10860 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10861 ** sqlite versions only work for ASCII characters, regardless of locale.
10862 */
10863 #ifdef SQLITE_ASCII
10864 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10865 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10866 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10867 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10868 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10869 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10870 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10871 #else
10872 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10873 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10874 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10875 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10876 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10877 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10878 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10879 #endif
10880
10881 /*
10882 ** Internal function prototypes
10883 */
10884 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10885 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10886 #define sqlite3StrNICmp sqlite3_strnicmp
10887
10888 SQLITE_PRIVATE int sqlite3MallocInit(void);
10889 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10890 SQLITE_PRIVATE void *sqlite3Malloc(int);
10891 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10892 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10893 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10894 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10895 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10896 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10897 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10898 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10899 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10900 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10901 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10902 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10903 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10904 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10905 SQLITE_PRIVATE void sqlite3PageFree(void*);
10906 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10907 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10908 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10909
10910 /*
10911 ** On systems with ample stack space and that support alloca(), make
10912 ** use of alloca() to obtain space for large automatic objects.  By default,
10913 ** obtain space from malloc().
10914 **
10915 ** The alloca() routine never returns NULL.  This will cause code paths
10916 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10917 */
10918 #ifdef SQLITE_USE_ALLOCA
10919 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10920 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10921 # define sqlite3StackFree(D,P)       
10922 #else
10923 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10924 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10925 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10926 #endif
10927
10928 #ifdef SQLITE_ENABLE_MEMSYS3
10929 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10930 #endif
10931 #ifdef SQLITE_ENABLE_MEMSYS5
10932 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10933 #endif
10934
10935
10936 #ifndef SQLITE_MUTEX_OMIT
10937 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10938 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10939 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10940 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10941 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10942 #endif
10943
10944 SQLITE_PRIVATE int sqlite3StatusValue(int);
10945 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10946 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10947
10948 #ifndef SQLITE_OMIT_FLOATING_POINT
10949 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10950 #else
10951 # define sqlite3IsNaN(X)  0
10952 #endif
10953
10954 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10955 #ifndef SQLITE_OMIT_TRACE
10956 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10957 #endif
10958 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10959 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10960 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10961 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10962 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10963 #endif
10964 #if defined(SQLITE_TEST)
10965 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10966 #endif
10967 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10968 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10969 SQLITE_PRIVATE int sqlite3Dequote(char*);
10970 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10971 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10972 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10973 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10974 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10975 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10976 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10977 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10978 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10979 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10980 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10981 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10982 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10983 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10984 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10985 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10986 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10987 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10988 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10989 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10990 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10991 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10992 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10993 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10994 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10995 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10996 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10997 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10998 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10999 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11000 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11001 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11002 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11003 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11004 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11005 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11006
11007 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11008 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11009 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11010 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11011 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11012 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11013 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11014
11015 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11016 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11017 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11018 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11019 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11020
11021 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11022
11023 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11024 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11025 #else
11026 # define sqlite3ViewGetColumnNames(A,B) 0
11027 #endif
11028
11029 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11030 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11031 #ifndef SQLITE_OMIT_AUTOINCREMENT
11032 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11033 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11034 #else
11035 # define sqlite3AutoincrementBegin(X)
11036 # define sqlite3AutoincrementEnd(X)
11037 #endif
11038 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11039 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11040 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11041 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11042 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11043 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11044 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11045                                       Token*, Select*, Expr*, IdList*);
11046 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11047 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11048 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11049 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11050 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11051 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11052 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11053                         Token*, int, int);
11054 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11055 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11056 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11057                          Expr*,ExprList*,int,Expr*,Expr*);
11058 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11059 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11060 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11061 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11062 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11063 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11064 #endif
11065 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11066 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11067 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11068 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11069 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11070 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11071 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11072 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11073 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11074 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11075 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11076 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11077 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11078 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11079 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11080 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11081 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11082 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11083 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11084 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11085 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11086 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11087 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11088 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11089 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11090 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11091 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11092 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11093 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11094 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11095 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11096 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11097 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11098 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11099 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11100 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11101 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11102 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11103 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11104 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11105 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11106 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11107 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11108 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11109 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11110 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11111 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11112 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11113 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11114 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11115 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11116 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11117 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11118 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11119 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11120 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11121 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11122 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11123                                      int*,int,int,int,int,int*);
11124 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11125 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11126 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11127 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11128 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11129 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11130 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11131 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11132 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11133 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11134 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11135 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11136 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11137 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11138 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11139 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11140 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11141 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11142 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11143
11144 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11145 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11146 #endif
11147
11148 #ifndef SQLITE_OMIT_TRIGGER
11149 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11150                            Expr*,int, int);
11151 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11152 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11153 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11154 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11155 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11156 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11157                             int, int, int);
11158 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11159   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11160 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11161 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11162 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11163                                         ExprList*,Select*,u8);
11164 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11165 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11166 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11167 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11168 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11169 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11170 #else
11171 # define sqlite3TriggersExist(B,C,D,E,F) 0
11172 # define sqlite3DeleteTrigger(A,B)
11173 # define sqlite3DropTriggerPtr(A,B)
11174 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11175 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11176 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11177 # define sqlite3TriggerList(X, Y) 0
11178 # define sqlite3ParseToplevel(p) p
11179 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11180 #endif
11181
11182 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11183 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11184 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11185 #ifndef SQLITE_OMIT_AUTHORIZATION
11186 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11187 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11188 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11189 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11190 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11191 #else
11192 # define sqlite3AuthRead(a,b,c,d)
11193 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11194 # define sqlite3AuthContextPush(a,b,c)
11195 # define sqlite3AuthContextPop(a)  ((void)(a))
11196 #endif
11197 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11198 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11199 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11200 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11201 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11202 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11203 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11204 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11205 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11206 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11207 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11208 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11209 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11210 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11211
11212 /*
11213 ** Routines to read and write variable-length integers.  These used to
11214 ** be defined locally, but now we use the varint routines in the util.c
11215 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11216 ** are coded to assume the single byte case is already handled (which 
11217 ** the MACRO form does).
11218 */
11219 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11220 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11221 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11222 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11223 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11224
11225 /*
11226 ** The header of a record consists of a sequence variable-length integers.
11227 ** These integers are almost always small and are encoded as a single byte.
11228 ** The following macros take advantage this fact to provide a fast encode
11229 ** and decode of the integers in a record header.  It is faster for the common
11230 ** case where the integer is a single byte.  It is a little slower when the
11231 ** integer is two or more bytes.  But overall it is faster.
11232 **
11233 ** The following expressions are equivalent:
11234 **
11235 **     x = sqlite3GetVarint32( A, &B );
11236 **     x = sqlite3PutVarint32( A, B );
11237 **
11238 **     x = getVarint32( A, B );
11239 **     x = putVarint32( A, B );
11240 **
11241 */
11242 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11243 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11244 #define getVarint    sqlite3GetVarint
11245 #define putVarint    sqlite3PutVarint
11246
11247
11248 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11249 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11250 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11251 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11252 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11253 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11254 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11255 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11256 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11257 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11258 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11259 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11260 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11261 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11262 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11263 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11264 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11265 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11266 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11267 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11268 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11269 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11270 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11271
11272 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11273 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11274 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11275                         void(*)(void*));
11276 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11277 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11278 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11279 #ifdef SQLITE_ENABLE_STAT2
11280 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11281 #endif
11282 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11283 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11284 #ifndef SQLITE_AMALGAMATION
11285 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11286 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11287 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11288 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11289 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11290 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11291 #ifndef SQLITE_OMIT_WSD
11292 SQLITE_PRIVATE int sqlite3PendingByte;
11293 #endif
11294 #endif
11295 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11296 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11297 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11298 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11299 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11300 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11301 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11302 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11303 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11304 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11305 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11306 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11307 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11308 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11309 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11310 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11311 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11312 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11313 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11314 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11315 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11316 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11317 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11318 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11319 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11320 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11321 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11322 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11323 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11324 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11325 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11326 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11327   void (*)(sqlite3_context*,int,sqlite3_value **),
11328   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11329   FuncDestructor *pDestructor
11330 );
11331 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11332 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11333
11334 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11335 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11336 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11337 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11338 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11339 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11340
11341 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11342 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11343
11344 /*
11345 ** The interface to the LEMON-generated parser
11346 */
11347 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11348 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11349 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11350 #ifdef YYTRACKMAXSTACKDEPTH
11351 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11352 #endif
11353
11354 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11355 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11356 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11357 #else
11358 # define sqlite3CloseExtensions(X)
11359 #endif
11360
11361 #ifndef SQLITE_OMIT_SHARED_CACHE
11362 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11363 #else
11364   #define sqlite3TableLock(v,w,x,y,z)
11365 #endif
11366
11367 #ifdef SQLITE_TEST
11368 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11369 #endif
11370
11371 #ifdef SQLITE_OMIT_VIRTUALTABLE
11372 #  define sqlite3VtabClear(Y)
11373 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11374 #  define sqlite3VtabRollback(X)
11375 #  define sqlite3VtabCommit(X)
11376 #  define sqlite3VtabInSync(db) 0
11377 #  define sqlite3VtabLock(X) 
11378 #  define sqlite3VtabUnlock(X)
11379 #  define sqlite3VtabUnlockList(X)
11380 #else
11381 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11382 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11383 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11384 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11385 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11386 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11387 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11388 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11389 #endif
11390 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11391 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11392 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11393 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11394 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11395 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11396 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11397 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11398 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11399 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11400 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11401 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11402 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11403 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11404 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11405 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11406 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11407 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11408 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11409 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11410 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11411
11412 /* Declarations for functions in fkey.c. All of these are replaced by
11413 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11414 ** key functionality is available. If OMIT_TRIGGER is defined but
11415 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11416 ** this case foreign keys are parsed, but no other functionality is 
11417 ** provided (enforcement of FK constraints requires the triggers sub-system).
11418 */
11419 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11420 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11421 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11422 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11423 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11424 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11425 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11426 #else
11427   #define sqlite3FkActions(a,b,c,d)
11428   #define sqlite3FkCheck(a,b,c,d)
11429   #define sqlite3FkDropTable(a,b,c)
11430   #define sqlite3FkOldmask(a,b)      0
11431   #define sqlite3FkRequired(a,b,c,d) 0
11432 #endif
11433 #ifndef SQLITE_OMIT_FOREIGN_KEY
11434 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11435 #else
11436   #define sqlite3FkDelete(a,b)
11437 #endif
11438
11439
11440 /*
11441 ** Available fault injectors.  Should be numbered beginning with 0.
11442 */
11443 #define SQLITE_FAULTINJECTOR_MALLOC     0
11444 #define SQLITE_FAULTINJECTOR_COUNT      1
11445
11446 /*
11447 ** The interface to the code in fault.c used for identifying "benign"
11448 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11449 ** is not defined.
11450 */
11451 #ifndef SQLITE_OMIT_BUILTIN_TEST
11452 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11453 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11454 #else
11455   #define sqlite3BeginBenignMalloc()
11456   #define sqlite3EndBenignMalloc()
11457 #endif
11458
11459 #define IN_INDEX_ROWID           1
11460 #define IN_INDEX_EPH             2
11461 #define IN_INDEX_INDEX           3
11462 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11463
11464 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11465 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11466 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11467 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11468 #else
11469   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11470 #endif
11471
11472 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11473 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11474 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11475
11476 #if SQLITE_MAX_EXPR_DEPTH>0
11477 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11478 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11479 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11480 #else
11481   #define sqlite3ExprSetHeight(x,y)
11482   #define sqlite3SelectExprHeight(x) 0
11483   #define sqlite3ExprCheckHeight(x,y)
11484 #endif
11485
11486 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11487 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11488
11489 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11490 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11491 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11492 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11493 #else
11494   #define sqlite3ConnectionBlocked(x,y)
11495   #define sqlite3ConnectionUnlocked(x)
11496   #define sqlite3ConnectionClosed(x)
11497 #endif
11498
11499 #ifdef SQLITE_DEBUG
11500 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11501 #endif
11502
11503 /*
11504 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11505 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11506 ** print I/O tracing messages. 
11507 */
11508 #ifdef SQLITE_ENABLE_IOTRACE
11509 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11510 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11511 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11512 #else
11513 # define IOTRACE(A)
11514 # define sqlite3VdbeIOTraceSql(X)
11515 #endif
11516
11517 /*
11518 ** These routines are available for the mem2.c debugging memory allocator
11519 ** only.  They are used to verify that different "types" of memory
11520 ** allocations are properly tracked by the system.
11521 **
11522 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11523 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11524 ** a single bit set.
11525 **
11526 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11527 ** argument match the type set by the previous sqlite3MemdebugSetType().
11528 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11529 **
11530 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11531 ** argument match the type set by the previous sqlite3MemdebugSetType().
11532 **
11533 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11534 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11535 ** it might have been allocated by lookaside, except the allocation was
11536 ** too large or lookaside was already full.  It is important to verify
11537 ** that allocations that might have been satisfied by lookaside are not
11538 ** passed back to non-lookaside free() routines.  Asserts such as the
11539 ** example above are placed on the non-lookaside free() routines to verify
11540 ** this constraint. 
11541 **
11542 ** All of this is no-op for a production build.  It only comes into
11543 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11544 */
11545 #ifdef SQLITE_MEMDEBUG
11546 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11547 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11548 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11549 #else
11550 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11551 # define sqlite3MemdebugHasType(X,Y)  1
11552 # define sqlite3MemdebugNoType(X,Y)   1
11553 #endif
11554 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11555 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11556 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11557 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11558 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11559
11560 #endif /* _SQLITEINT_H_ */
11561
11562 /************** End of sqliteInt.h *******************************************/
11563 /************** Begin file global.c ******************************************/
11564 /*
11565 ** 2008 June 13
11566 **
11567 ** The author disclaims copyright to this source code.  In place of
11568 ** a legal notice, here is a blessing:
11569 **
11570 **    May you do good and not evil.
11571 **    May you find forgiveness for yourself and forgive others.
11572 **    May you share freely, never taking more than you give.
11573 **
11574 *************************************************************************
11575 **
11576 ** This file contains definitions of global variables and contants.
11577 */
11578
11579 /* An array to map all upper-case characters into their corresponding
11580 ** lower-case character. 
11581 **
11582 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11583 ** handle case conversions for the UTF character set since the tables
11584 ** involved are nearly as big or bigger than SQLite itself.
11585 */
11586 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11587 #ifdef SQLITE_ASCII
11588       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11589      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11590      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11591      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11592     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11593     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11594     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11595     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11596     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11597     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11598     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11599     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11600     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11601     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11602     252,253,254,255
11603 #endif
11604 #ifdef SQLITE_EBCDIC
11605       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11606      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11607      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11608      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11609      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11610      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11611      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11612     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11613     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11614     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11615     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11616     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11617     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11618     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11619     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11620     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11621 #endif
11622 };
11623
11624 /*
11625 ** The following 256 byte lookup table is used to support SQLites built-in
11626 ** equivalents to the following standard library functions:
11627 **
11628 **   isspace()                        0x01
11629 **   isalpha()                        0x02
11630 **   isdigit()                        0x04
11631 **   isalnum()                        0x06
11632 **   isxdigit()                       0x08
11633 **   toupper()                        0x20
11634 **   SQLite identifier character      0x40
11635 **
11636 ** Bit 0x20 is set if the mapped character requires translation to upper
11637 ** case. i.e. if the character is a lower-case ASCII character.
11638 ** If x is a lower-case ASCII character, then its upper-case equivalent
11639 ** is (x - 0x20). Therefore toupper() can be implemented as:
11640 **
11641 **   (x & ~(map[x]&0x20))
11642 **
11643 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11644 ** array. tolower() is used more often than toupper() by SQLite.
11645 **
11646 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11647 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11648 ** non-ASCII UTF character. Hence the test for whether or not a character is
11649 ** part of an identifier is 0x46.
11650 **
11651 ** SQLite's versions are identical to the standard versions assuming a
11652 ** locale of "C". They are implemented as macros in sqliteInt.h.
11653 */
11654 #ifdef SQLITE_ASCII
11655 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11656   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11657   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11658   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11659   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11660   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11661   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11662   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11663   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11664
11665   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11666   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11667   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11668   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11669   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11670   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11671   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11672   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11673
11674   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11675   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11676   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11677   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11678   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11679   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11680   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11681   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11682
11683   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11684   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11685   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11686   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11687   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11688   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11689   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11690   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11691 };
11692 #endif
11693
11694
11695
11696 /*
11697 ** The following singleton contains the global configuration for
11698 ** the SQLite library.
11699 */
11700 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11701    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11702    1,                         /* bCoreMutex */
11703    SQLITE_THREADSAFE==1,      /* bFullMutex */
11704    0x7ffffffe,                /* mxStrlen */
11705    100,                       /* szLookaside */
11706    500,                       /* nLookaside */
11707    {0,0,0,0,0,0,0,0},         /* m */
11708    {0,0,0,0,0,0,0,0,0},       /* mutex */
11709    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11710    (void*)0,                  /* pHeap */
11711    0,                         /* nHeap */
11712    0, 0,                      /* mnHeap, mxHeap */
11713    (void*)0,                  /* pScratch */
11714    0,                         /* szScratch */
11715    0,                         /* nScratch */
11716    (void*)0,                  /* pPage */
11717    0,                         /* szPage */
11718    0,                         /* nPage */
11719    0,                         /* mxParserStack */
11720    0,                         /* sharedCacheEnabled */
11721    /* All the rest should always be initialized to zero */
11722    0,                         /* isInit */
11723    0,                         /* inProgress */
11724    0,                         /* isMutexInit */
11725    0,                         /* isMallocInit */
11726    0,                         /* isPCacheInit */
11727    0,                         /* pInitMutex */
11728    0,                         /* nRefInitMutex */
11729    0,                         /* xLog */
11730    0,                         /* pLogArg */
11731 };
11732
11733
11734 /*
11735 ** Hash table for global functions - functions common to all
11736 ** database connections.  After initialization, this table is
11737 ** read-only.
11738 */
11739 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11740
11741 /*
11742 ** Constant tokens for values 0 and 1.
11743 */
11744 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11745    { "0", 1 },
11746    { "1", 1 }
11747 };
11748
11749
11750 /*
11751 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11752 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11753 ** the database page that contains the pending byte.  It never attempts
11754 ** to read or write that page.  The pending byte page is set assign
11755 ** for use by the VFS layers as space for managing file locks.
11756 **
11757 ** During testing, it is often desirable to move the pending byte to
11758 ** a different position in the file.  This allows code that has to
11759 ** deal with the pending byte to run on files that are much smaller
11760 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11761 ** move the pending byte.
11762 **
11763 ** IMPORTANT:  Changing the pending byte to any value other than
11764 ** 0x40000000 results in an incompatible database file format!
11765 ** Changing the pending byte during operating results in undefined
11766 ** and dileterious behavior.
11767 */
11768 #ifndef SQLITE_OMIT_WSD
11769 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11770 #endif
11771
11772 /*
11773 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11774 ** created by mkopcodeh.awk during compilation.  Data is obtained
11775 ** from the comments following the "case OP_xxxx:" statements in
11776 ** the vdbe.c file.  
11777 */
11778 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11779
11780 /************** End of global.c **********************************************/
11781 /************** Begin file ctime.c *******************************************/
11782 /*
11783 ** 2010 February 23
11784 **
11785 ** The author disclaims copyright to this source code.  In place of
11786 ** a legal notice, here is a blessing:
11787 **
11788 **    May you do good and not evil.
11789 **    May you find forgiveness for yourself and forgive others.
11790 **    May you share freely, never taking more than you give.
11791 **
11792 *************************************************************************
11793 **
11794 ** This file implements routines used to report what compile-time options
11795 ** SQLite was built with.
11796 */
11797
11798 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11799
11800
11801 /*
11802 ** An array of names of all compile-time options.  This array should 
11803 ** be sorted A-Z.
11804 **
11805 ** This array looks large, but in a typical installation actually uses
11806 ** only a handful of compile-time options, so most times this array is usually
11807 ** rather short and uses little memory space.
11808 */
11809 static const char * const azCompileOpt[] = {
11810
11811 /* These macros are provided to "stringify" the value of the define
11812 ** for those options in which the value is meaningful. */
11813 #define CTIMEOPT_VAL_(opt) #opt
11814 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11815
11816 #ifdef SQLITE_32BIT_ROWID
11817   "32BIT_ROWID",
11818 #endif
11819 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11820   "4_BYTE_ALIGNED_MALLOC",
11821 #endif
11822 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11823   "CASE_SENSITIVE_LIKE",
11824 #endif
11825 #ifdef SQLITE_CHECK_PAGES
11826   "CHECK_PAGES",
11827 #endif
11828 #ifdef SQLITE_COVERAGE_TEST
11829   "COVERAGE_TEST",
11830 #endif
11831 #ifdef SQLITE_DEBUG
11832   "DEBUG",
11833 #endif
11834 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11835   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11836 #endif
11837 #ifdef SQLITE_DISABLE_DIRSYNC
11838   "DISABLE_DIRSYNC",
11839 #endif
11840 #ifdef SQLITE_DISABLE_LFS
11841   "DISABLE_LFS",
11842 #endif
11843 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11844   "ENABLE_ATOMIC_WRITE",
11845 #endif
11846 #ifdef SQLITE_ENABLE_CEROD
11847   "ENABLE_CEROD",
11848 #endif
11849 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11850   "ENABLE_COLUMN_METADATA",
11851 #endif
11852 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11853   "ENABLE_EXPENSIVE_ASSERT",
11854 #endif
11855 #ifdef SQLITE_ENABLE_FTS1
11856   "ENABLE_FTS1",
11857 #endif
11858 #ifdef SQLITE_ENABLE_FTS2
11859   "ENABLE_FTS2",
11860 #endif
11861 #ifdef SQLITE_ENABLE_FTS3
11862   "ENABLE_FTS3",
11863 #endif
11864 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11865   "ENABLE_FTS3_PARENTHESIS",
11866 #endif
11867 #ifdef SQLITE_ENABLE_FTS4
11868   "ENABLE_FTS4",
11869 #endif
11870 #ifdef SQLITE_ENABLE_ICU
11871   "ENABLE_ICU",
11872 #endif
11873 #ifdef SQLITE_ENABLE_IOTRACE
11874   "ENABLE_IOTRACE",
11875 #endif
11876 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11877   "ENABLE_LOAD_EXTENSION",
11878 #endif
11879 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11880   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11881 #endif
11882 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11883   "ENABLE_MEMORY_MANAGEMENT",
11884 #endif
11885 #ifdef SQLITE_ENABLE_MEMSYS3
11886   "ENABLE_MEMSYS3",
11887 #endif
11888 #ifdef SQLITE_ENABLE_MEMSYS5
11889   "ENABLE_MEMSYS5",
11890 #endif
11891 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11892   "ENABLE_OVERSIZE_CELL_CHECK",
11893 #endif
11894 #ifdef SQLITE_ENABLE_RTREE
11895   "ENABLE_RTREE",
11896 #endif
11897 #ifdef SQLITE_ENABLE_STAT2
11898   "ENABLE_STAT2",
11899 #endif
11900 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11901   "ENABLE_UNLOCK_NOTIFY",
11902 #endif
11903 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11904   "ENABLE_UPDATE_DELETE_LIMIT",
11905 #endif
11906 #ifdef SQLITE_HAS_CODEC
11907   "HAS_CODEC",
11908 #endif
11909 #ifdef SQLITE_HAVE_ISNAN
11910   "HAVE_ISNAN",
11911 #endif
11912 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11913   "HOMEGROWN_RECURSIVE_MUTEX",
11914 #endif
11915 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11916   "IGNORE_AFP_LOCK_ERRORS",
11917 #endif
11918 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11919   "IGNORE_FLOCK_LOCK_ERRORS",
11920 #endif
11921 #ifdef SQLITE_INT64_TYPE
11922   "INT64_TYPE",
11923 #endif
11924 #ifdef SQLITE_LOCK_TRACE
11925   "LOCK_TRACE",
11926 #endif
11927 #ifdef SQLITE_MEMDEBUG
11928   "MEMDEBUG",
11929 #endif
11930 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11931   "MIXED_ENDIAN_64BIT_FLOAT",
11932 #endif
11933 #ifdef SQLITE_NO_SYNC
11934   "NO_SYNC",
11935 #endif
11936 #ifdef SQLITE_OMIT_ALTERTABLE
11937   "OMIT_ALTERTABLE",
11938 #endif
11939 #ifdef SQLITE_OMIT_ANALYZE
11940   "OMIT_ANALYZE",
11941 #endif
11942 #ifdef SQLITE_OMIT_ATTACH
11943   "OMIT_ATTACH",
11944 #endif
11945 #ifdef SQLITE_OMIT_AUTHORIZATION
11946   "OMIT_AUTHORIZATION",
11947 #endif
11948 #ifdef SQLITE_OMIT_AUTOINCREMENT
11949   "OMIT_AUTOINCREMENT",
11950 #endif
11951 #ifdef SQLITE_OMIT_AUTOINIT
11952   "OMIT_AUTOINIT",
11953 #endif
11954 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11955   "OMIT_AUTOMATIC_INDEX",
11956 #endif
11957 #ifdef SQLITE_OMIT_AUTORESET
11958   "OMIT_AUTORESET",
11959 #endif
11960 #ifdef SQLITE_OMIT_AUTOVACUUM
11961   "OMIT_AUTOVACUUM",
11962 #endif
11963 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11964   "OMIT_BETWEEN_OPTIMIZATION",
11965 #endif
11966 #ifdef SQLITE_OMIT_BLOB_LITERAL
11967   "OMIT_BLOB_LITERAL",
11968 #endif
11969 #ifdef SQLITE_OMIT_BTREECOUNT
11970   "OMIT_BTREECOUNT",
11971 #endif
11972 #ifdef SQLITE_OMIT_BUILTIN_TEST
11973   "OMIT_BUILTIN_TEST",
11974 #endif
11975 #ifdef SQLITE_OMIT_CAST
11976   "OMIT_CAST",
11977 #endif
11978 #ifdef SQLITE_OMIT_CHECK
11979   "OMIT_CHECK",
11980 #endif
11981 /* // redundant
11982 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11983 **   "OMIT_COMPILEOPTION_DIAGS",
11984 ** #endif
11985 */
11986 #ifdef SQLITE_OMIT_COMPLETE
11987   "OMIT_COMPLETE",
11988 #endif
11989 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11990   "OMIT_COMPOUND_SELECT",
11991 #endif
11992 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11993   "OMIT_DATETIME_FUNCS",
11994 #endif
11995 #ifdef SQLITE_OMIT_DECLTYPE
11996   "OMIT_DECLTYPE",
11997 #endif
11998 #ifdef SQLITE_OMIT_DEPRECATED
11999   "OMIT_DEPRECATED",
12000 #endif
12001 #ifdef SQLITE_OMIT_DISKIO
12002   "OMIT_DISKIO",
12003 #endif
12004 #ifdef SQLITE_OMIT_EXPLAIN
12005   "OMIT_EXPLAIN",
12006 #endif
12007 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12008   "OMIT_FLAG_PRAGMAS",
12009 #endif
12010 #ifdef SQLITE_OMIT_FLOATING_POINT
12011   "OMIT_FLOATING_POINT",
12012 #endif
12013 #ifdef SQLITE_OMIT_FOREIGN_KEY
12014   "OMIT_FOREIGN_KEY",
12015 #endif
12016 #ifdef SQLITE_OMIT_GET_TABLE
12017   "OMIT_GET_TABLE",
12018 #endif
12019 #ifdef SQLITE_OMIT_INCRBLOB
12020   "OMIT_INCRBLOB",
12021 #endif
12022 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12023   "OMIT_INTEGRITY_CHECK",
12024 #endif
12025 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12026   "OMIT_LIKE_OPTIMIZATION",
12027 #endif
12028 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12029   "OMIT_LOAD_EXTENSION",
12030 #endif
12031 #ifdef SQLITE_OMIT_LOCALTIME
12032   "OMIT_LOCALTIME",
12033 #endif
12034 #ifdef SQLITE_OMIT_LOOKASIDE
12035   "OMIT_LOOKASIDE",
12036 #endif
12037 #ifdef SQLITE_OMIT_MEMORYDB
12038   "OMIT_MEMORYDB",
12039 #endif
12040 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12041   "OMIT_OR_OPTIMIZATION",
12042 #endif
12043 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12044   "OMIT_PAGER_PRAGMAS",
12045 #endif
12046 #ifdef SQLITE_OMIT_PRAGMA
12047   "OMIT_PRAGMA",
12048 #endif
12049 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12050   "OMIT_PROGRESS_CALLBACK",
12051 #endif
12052 #ifdef SQLITE_OMIT_QUICKBALANCE
12053   "OMIT_QUICKBALANCE",
12054 #endif
12055 #ifdef SQLITE_OMIT_REINDEX
12056   "OMIT_REINDEX",
12057 #endif
12058 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12059   "OMIT_SCHEMA_PRAGMAS",
12060 #endif
12061 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12062   "OMIT_SCHEMA_VERSION_PRAGMAS",
12063 #endif
12064 #ifdef SQLITE_OMIT_SHARED_CACHE
12065   "OMIT_SHARED_CACHE",
12066 #endif
12067 #ifdef SQLITE_OMIT_SUBQUERY
12068   "OMIT_SUBQUERY",
12069 #endif
12070 #ifdef SQLITE_OMIT_TCL_VARIABLE
12071   "OMIT_TCL_VARIABLE",
12072 #endif
12073 #ifdef SQLITE_OMIT_TEMPDB
12074   "OMIT_TEMPDB",
12075 #endif
12076 #ifdef SQLITE_OMIT_TRACE
12077   "OMIT_TRACE",
12078 #endif
12079 #ifdef SQLITE_OMIT_TRIGGER
12080   "OMIT_TRIGGER",
12081 #endif
12082 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12083   "OMIT_TRUNCATE_OPTIMIZATION",
12084 #endif
12085 #ifdef SQLITE_OMIT_UTF16
12086   "OMIT_UTF16",
12087 #endif
12088 #ifdef SQLITE_OMIT_VACUUM
12089   "OMIT_VACUUM",
12090 #endif
12091 #ifdef SQLITE_OMIT_VIEW
12092   "OMIT_VIEW",
12093 #endif
12094 #ifdef SQLITE_OMIT_VIRTUALTABLE
12095   "OMIT_VIRTUALTABLE",
12096 #endif
12097 #ifdef SQLITE_OMIT_WAL
12098   "OMIT_WAL",
12099 #endif
12100 #ifdef SQLITE_OMIT_WSD
12101   "OMIT_WSD",
12102 #endif
12103 #ifdef SQLITE_OMIT_XFER_OPT
12104   "OMIT_XFER_OPT",
12105 #endif
12106 #ifdef SQLITE_PERFORMANCE_TRACE
12107   "PERFORMANCE_TRACE",
12108 #endif
12109 #ifdef SQLITE_PROXY_DEBUG
12110   "PROXY_DEBUG",
12111 #endif
12112 #ifdef SQLITE_SECURE_DELETE
12113   "SECURE_DELETE",
12114 #endif
12115 #ifdef SQLITE_SMALL_STACK
12116   "SMALL_STACK",
12117 #endif
12118 #ifdef SQLITE_SOUNDEX
12119   "SOUNDEX",
12120 #endif
12121 #ifdef SQLITE_TCL
12122   "TCL",
12123 #endif
12124 #ifdef SQLITE_TEMP_STORE
12125   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12126 #endif
12127 #ifdef SQLITE_TEST
12128   "TEST",
12129 #endif
12130 #ifdef SQLITE_THREADSAFE
12131   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12132 #endif
12133 #ifdef SQLITE_USE_ALLOCA
12134   "USE_ALLOCA",
12135 #endif
12136 #ifdef SQLITE_ZERO_MALLOC
12137   "ZERO_MALLOC"
12138 #endif
12139 };
12140
12141 /*
12142 ** Given the name of a compile-time option, return true if that option
12143 ** was used and false if not.
12144 **
12145 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12146 ** is not required for a match.
12147 */
12148 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12149   int i, n;
12150   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12151   n = sqlite3Strlen30(zOptName);
12152
12153   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12154   ** linear search is adequate.  No need for a binary search. */
12155   for(i=0; i<ArraySize(azCompileOpt); i++){
12156     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12157        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12158   }
12159   return 0;
12160 }
12161
12162 /*
12163 ** Return the N-th compile-time option string.  If N is out of range,
12164 ** return a NULL pointer.
12165 */
12166 SQLITE_API const char *sqlite3_compileoption_get(int N){
12167   if( N>=0 && N<ArraySize(azCompileOpt) ){
12168     return azCompileOpt[N];
12169   }
12170   return 0;
12171 }
12172
12173 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12174
12175 /************** End of ctime.c ***********************************************/
12176 /************** Begin file status.c ******************************************/
12177 /*
12178 ** 2008 June 18
12179 **
12180 ** The author disclaims copyright to this source code.  In place of
12181 ** a legal notice, here is a blessing:
12182 **
12183 **    May you do good and not evil.
12184 **    May you find forgiveness for yourself and forgive others.
12185 **    May you share freely, never taking more than you give.
12186 **
12187 *************************************************************************
12188 **
12189 ** This module implements the sqlite3_status() interface and related
12190 ** functionality.
12191 */
12192 /************** Include vdbeInt.h in the middle of status.c ******************/
12193 /************** Begin file vdbeInt.h *****************************************/
12194 /*
12195 ** 2003 September 6
12196 **
12197 ** The author disclaims copyright to this source code.  In place of
12198 ** a legal notice, here is a blessing:
12199 **
12200 **    May you do good and not evil.
12201 **    May you find forgiveness for yourself and forgive others.
12202 **    May you share freely, never taking more than you give.
12203 **
12204 *************************************************************************
12205 ** This is the header file for information that is private to the
12206 ** VDBE.  This information used to all be at the top of the single
12207 ** source code file "vdbe.c".  When that file became too big (over
12208 ** 6000 lines long) it was split up into several smaller files and
12209 ** this header information was factored out.
12210 */
12211 #ifndef _VDBEINT_H_
12212 #define _VDBEINT_H_
12213
12214 /*
12215 ** SQL is translated into a sequence of instructions to be
12216 ** executed by a virtual machine.  Each instruction is an instance
12217 ** of the following structure.
12218 */
12219 typedef struct VdbeOp Op;
12220
12221 /*
12222 ** Boolean values
12223 */
12224 typedef unsigned char Bool;
12225
12226 /*
12227 ** A cursor is a pointer into a single BTree within a database file.
12228 ** The cursor can seek to a BTree entry with a particular key, or
12229 ** loop over all entries of the Btree.  You can also insert new BTree
12230 ** entries or retrieve the key or data from the entry that the cursor
12231 ** is currently pointing to.
12232 ** 
12233 ** Every cursor that the virtual machine has open is represented by an
12234 ** instance of the following structure.
12235 */
12236 struct VdbeCursor {
12237   BtCursor *pCursor;    /* The cursor structure of the backend */
12238   Btree *pBt;           /* Separate file holding temporary table */
12239   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12240   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12241   int pseudoTableReg;   /* Register holding pseudotable content. */
12242   int nField;           /* Number of fields in the header */
12243   Bool zeroed;          /* True if zeroed out and ready for reuse */
12244   Bool rowidIsValid;    /* True if lastRowid is valid */
12245   Bool atFirst;         /* True if pointing to first entry */
12246   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12247   Bool nullRow;         /* True if pointing to a row with no data */
12248   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12249   Bool isTable;         /* True if a table requiring integer keys */
12250   Bool isIndex;         /* True if an index containing keys only - no data */
12251   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12252   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12253   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12254   i64 seqCount;         /* Sequence counter */
12255   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12256   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12257
12258   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12259   ** OP_IsUnique opcode on this cursor. */
12260   int seekResult;
12261
12262   /* Cached information about the header for the data record that the
12263   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12264   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12265   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12266   ** the cache is out of date.
12267   **
12268   ** aRow might point to (ephemeral) data for the current row, or it might
12269   ** be NULL.
12270   */
12271   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12272   int payloadSize;      /* Total number of bytes in the record */
12273   u32 *aType;           /* Type values for all entries in the record */
12274   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12275   u8 *aRow;             /* Data for the current row, if all on one page */
12276 };
12277 typedef struct VdbeCursor VdbeCursor;
12278
12279 /*
12280 ** When a sub-program is executed (OP_Program), a structure of this type
12281 ** is allocated to store the current value of the program counter, as
12282 ** well as the current memory cell array and various other frame specific
12283 ** values stored in the Vdbe struct. When the sub-program is finished, 
12284 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12285 ** restoring the state of the VM to as it was before the sub-program
12286 ** began executing.
12287 **
12288 ** The memory for a VdbeFrame object is allocated and managed by a memory
12289 ** cell in the parent (calling) frame. When the memory cell is deleted or
12290 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12291 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12292 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12293 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12294 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12295 ** child frame are released.
12296 **
12297 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12298 ** set to NULL if the currently executing frame is the main program.
12299 */
12300 typedef struct VdbeFrame VdbeFrame;
12301 struct VdbeFrame {
12302   Vdbe *v;                /* VM this frame belongs to */
12303   int pc;                 /* Program Counter in parent (calling) frame */
12304   Op *aOp;                /* Program instructions for parent frame */
12305   int nOp;                /* Size of aOp array */
12306   Mem *aMem;              /* Array of memory cells for parent frame */
12307   int nMem;               /* Number of entries in aMem */
12308   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12309   u16 nCursor;            /* Number of entries in apCsr */
12310   void *token;            /* Copy of SubProgram.token */
12311   int nChildMem;          /* Number of memory cells for child frame */
12312   int nChildCsr;          /* Number of cursors for child frame */
12313   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12314   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12315   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12316 };
12317
12318 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12319
12320 /*
12321 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12322 */
12323 #define CACHE_STALE 0
12324
12325 /*
12326 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12327 ** structures. Each Mem struct may cache multiple representations (string,
12328 ** integer etc.) of the same value.
12329 */
12330 struct Mem {
12331   sqlite3 *db;        /* The associated database connection */
12332   char *z;            /* String or BLOB value */
12333   double r;           /* Real value */
12334   union {
12335     i64 i;              /* Integer value used when MEM_Int is set in flags */
12336     int nZero;          /* Used when bit MEM_Zero is set in flags */
12337     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12338     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12339     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12340   } u;
12341   int n;              /* Number of characters in string value, excluding '\0' */
12342   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12343   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12344   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12345 #ifdef SQLITE_DEBUG
12346   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12347   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12348 #endif
12349   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12350   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12351 };
12352
12353 /* One or more of the following flags are set to indicate the validOK
12354 ** representations of the value stored in the Mem struct.
12355 **
12356 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12357 ** No other flags may be set in this case.
12358 **
12359 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12360 ** Usually this is encoded in the same unicode encoding as the main
12361 ** database (see below for exceptions). If the MEM_Term flag is also
12362 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12363 ** flags may coexist with the MEM_Str flag.
12364 */
12365 #define MEM_Null      0x0001   /* Value is NULL */
12366 #define MEM_Str       0x0002   /* Value is a string */
12367 #define MEM_Int       0x0004   /* Value is an integer */
12368 #define MEM_Real      0x0008   /* Value is a real number */
12369 #define MEM_Blob      0x0010   /* Value is a BLOB */
12370 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12371 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12372 #define MEM_Invalid   0x0080   /* Value is undefined */
12373 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12374
12375 /* Whenever Mem contains a valid string or blob representation, one of
12376 ** the following flags must be set to determine the memory management
12377 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12378 ** string is \000 or \u0000 terminated
12379 */
12380 #define MEM_Term      0x0200   /* String rep is nul terminated */
12381 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12382 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12383 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12384 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12385 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12386 #ifdef SQLITE_OMIT_INCRBLOB
12387   #undef MEM_Zero
12388   #define MEM_Zero 0x0000
12389 #endif
12390
12391 /*
12392 ** Clear any existing type flags from a Mem and replace them with f
12393 */
12394 #define MemSetTypeFlag(p, f) \
12395    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12396
12397 /*
12398 ** Return true if a memory cell is not marked as invalid.  This macro
12399 ** is for use inside assert() statements only.
12400 */
12401 #ifdef SQLITE_DEBUG
12402 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12403 #endif
12404
12405
12406 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12407 ** additional information about auxiliary information bound to arguments
12408 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12409 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12410 ** that can be associated with a constant argument to a function.  This
12411 ** allows functions such as "regexp" to compile their constant regular
12412 ** expression argument once and reused the compiled code for multiple
12413 ** invocations.
12414 */
12415 struct VdbeFunc {
12416   FuncDef *pFunc;               /* The definition of the function */
12417   int nAux;                     /* Number of entries allocated for apAux[] */
12418   struct AuxData {
12419     void *pAux;                   /* Aux data for the i-th argument */
12420     void (*xDelete)(void *);      /* Destructor for the aux data */
12421   } apAux[1];                   /* One slot for each function argument */
12422 };
12423
12424 /*
12425 ** The "context" argument for a installable function.  A pointer to an
12426 ** instance of this structure is the first argument to the routines used
12427 ** implement the SQL functions.
12428 **
12429 ** There is a typedef for this structure in sqlite.h.  So all routines,
12430 ** even the public interface to SQLite, can use a pointer to this structure.
12431 ** But this file is the only place where the internal details of this
12432 ** structure are known.
12433 **
12434 ** This structure is defined inside of vdbeInt.h because it uses substructures
12435 ** (Mem) which are only defined there.
12436 */
12437 struct sqlite3_context {
12438   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12439   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12440   Mem s;                /* The return value is stored here */
12441   Mem *pMem;            /* Memory cell used to store aggregate context */
12442   int isError;          /* Error code returned by the function. */
12443   CollSeq *pColl;       /* Collating sequence */
12444 };
12445
12446 /*
12447 ** An instance of the virtual machine.  This structure contains the complete
12448 ** state of the virtual machine.
12449 **
12450 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12451 ** is really a pointer to an instance of this structure.
12452 **
12453 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12454 ** any virtual table method invocations made by the vdbe program. It is
12455 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12456 ** variable is used for two purposes: to allow xDestroy methods to execute
12457 ** "DROP TABLE" statements and to prevent some nasty side effects of
12458 ** malloc failure when SQLite is invoked recursively by a virtual table 
12459 ** method function.
12460 */
12461 struct Vdbe {
12462   sqlite3 *db;            /* The database connection that owns this statement */
12463   Op *aOp;                /* Space to hold the virtual machine's program */
12464   Mem *aMem;              /* The memory locations */
12465   Mem **apArg;            /* Arguments to currently executing user function */
12466   Mem *aColName;          /* Column names to return */
12467   Mem *pResultSet;        /* Pointer to an array of results */
12468   int nMem;               /* Number of memory locations currently allocated */
12469   int nOp;                /* Number of instructions in the program */
12470   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12471   int nLabel;             /* Number of labels used */
12472   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12473   int *aLabel;            /* Space to hold the labels */
12474   u16 nResColumn;         /* Number of columns in one row of the result set */
12475   u16 nCursor;            /* Number of slots in apCsr[] */
12476   u32 magic;              /* Magic number for sanity checking */
12477   char *zErrMsg;          /* Error message written here */
12478   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12479   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12480   Mem *aVar;              /* Values for the OP_Variable opcode. */
12481   char **azVar;           /* Name of variables */
12482   ynVar nVar;             /* Number of entries in aVar[] */
12483   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12484   int pc;                 /* The program counter */
12485   int rc;                 /* Value to return */
12486   u8 errorAction;         /* Recovery action to do in case of an error */
12487   u8 okVar;               /* True if azVar[] has been initialized */
12488   u8 explain;             /* True if EXPLAIN present on SQL command */
12489   u8 changeCntOn;         /* True to update the change-counter */
12490   u8 expired;             /* True if the VM needs to be recompiled */
12491   u8 runOnlyOnce;         /* Automatically expire on reset */
12492   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12493   u8 inVtabMethod;        /* See comments above */
12494   u8 usesStmtJournal;     /* True if uses a statement journal */
12495   u8 readOnly;            /* True for read-only statements */
12496   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12497   int nChange;            /* Number of db changes made since last reset */
12498   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
12499   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
12500   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12501   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12502 #ifndef SQLITE_OMIT_TRACE
12503   i64 startTime;          /* Time when query started - used for profiling */
12504 #endif
12505   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12506   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12507   char *zSql;             /* Text of the SQL statement that generated this */
12508   void *pFree;            /* Free this when deleting the vdbe */
12509 #ifdef SQLITE_DEBUG
12510   FILE *trace;            /* Write an execution trace here, if not NULL */
12511 #endif
12512   VdbeFrame *pFrame;      /* Parent frame */
12513   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12514   int nFrame;             /* Number of frames in pFrame list */
12515   u32 expmask;            /* Binding to these vars invalidates VM */
12516   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12517 };
12518
12519 /*
12520 ** The following are allowed values for Vdbe.magic
12521 */
12522 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12523 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12524 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12525 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12526
12527 /*
12528 ** Function prototypes
12529 */
12530 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12531 void sqliteVdbePopStack(Vdbe*,int);
12532 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12533 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12534 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12535 #endif
12536 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12537 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12538 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12539 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12540 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12541
12542 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12543 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12544 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12545 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12546 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12547 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12548 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12549 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12550 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12551 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12552 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12553 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12554 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12555 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12556 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12557 #ifdef SQLITE_OMIT_FLOATING_POINT
12558 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12559 #else
12560 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12561 #endif
12562 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12563 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12564 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12565 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12566 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12567 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12568 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12569 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12570 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12571 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12572 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12573 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12574 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12575 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12576 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12577 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12578 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12579 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12580 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12581 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12582 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12583
12584 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12585 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
12586 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
12587 #else
12588 # define sqlite3VdbeEnter(X)
12589 # define sqlite3VdbeLeave(X)
12590 #endif
12591
12592 #ifdef SQLITE_DEBUG
12593 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12594 #endif
12595
12596 #ifndef SQLITE_OMIT_FOREIGN_KEY
12597 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12598 #else
12599 # define sqlite3VdbeCheckFk(p,i) 0
12600 #endif
12601
12602 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12603 #ifdef SQLITE_DEBUG
12604 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12605 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12606 #endif
12607 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12608
12609 #ifndef SQLITE_OMIT_INCRBLOB
12610 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12611 #else
12612   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12613 #endif
12614
12615 #endif /* !defined(_VDBEINT_H_) */
12616
12617 /************** End of vdbeInt.h *********************************************/
12618 /************** Continuing where we left off in status.c *********************/
12619
12620 /*
12621 ** Variables in which to record status information.
12622 */
12623 typedef struct sqlite3StatType sqlite3StatType;
12624 static SQLITE_WSD struct sqlite3StatType {
12625   int nowValue[10];         /* Current value */
12626   int mxValue[10];          /* Maximum value */
12627 } sqlite3Stat = { {0,}, {0,} };
12628
12629
12630 /* The "wsdStat" macro will resolve to the status information
12631 ** state vector.  If writable static data is unsupported on the target,
12632 ** we have to locate the state vector at run-time.  In the more common
12633 ** case where writable static data is supported, wsdStat can refer directly
12634 ** to the "sqlite3Stat" state vector declared above.
12635 */
12636 #ifdef SQLITE_OMIT_WSD
12637 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12638 # define wsdStat x[0]
12639 #else
12640 # define wsdStatInit
12641 # define wsdStat sqlite3Stat
12642 #endif
12643
12644 /*
12645 ** Return the current value of a status parameter.
12646 */
12647 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12648   wsdStatInit;
12649   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12650   return wsdStat.nowValue[op];
12651 }
12652
12653 /*
12654 ** Add N to the value of a status record.  It is assumed that the
12655 ** caller holds appropriate locks.
12656 */
12657 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12658   wsdStatInit;
12659   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12660   wsdStat.nowValue[op] += N;
12661   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12662     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12663   }
12664 }
12665
12666 /*
12667 ** Set the value of a status to X.
12668 */
12669 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12670   wsdStatInit;
12671   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12672   wsdStat.nowValue[op] = X;
12673   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12674     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12675   }
12676 }
12677
12678 /*
12679 ** Query status information.
12680 **
12681 ** This implementation assumes that reading or writing an aligned
12682 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12683 ** then this routine is not threadsafe.
12684 */
12685 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12686   wsdStatInit;
12687   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12688     return SQLITE_MISUSE_BKPT;
12689   }
12690   *pCurrent = wsdStat.nowValue[op];
12691   *pHighwater = wsdStat.mxValue[op];
12692   if( resetFlag ){
12693     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12694   }
12695   return SQLITE_OK;
12696 }
12697
12698 /*
12699 ** Query status information for a single database connection
12700 */
12701 SQLITE_API int sqlite3_db_status(
12702   sqlite3 *db,          /* The database connection whose status is desired */
12703   int op,               /* Status verb */
12704   int *pCurrent,        /* Write current value here */
12705   int *pHighwater,      /* Write high-water mark here */
12706   int resetFlag         /* Reset high-water mark if true */
12707 ){
12708   int rc = SQLITE_OK;   /* Return code */
12709   sqlite3_mutex_enter(db->mutex);
12710   switch( op ){
12711     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12712       *pCurrent = db->lookaside.nOut;
12713       *pHighwater = db->lookaside.mxOut;
12714       if( resetFlag ){
12715         db->lookaside.mxOut = db->lookaside.nOut;
12716       }
12717       break;
12718     }
12719
12720     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12721     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12722     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12723       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12724       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12725       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12726       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12727       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12728       *pCurrent = 0;
12729       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12730       if( resetFlag ){
12731         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12732       }
12733       break;
12734     }
12735
12736     /* 
12737     ** Return an approximation for the amount of memory currently used
12738     ** by all pagers associated with the given database connection.  The
12739     ** highwater mark is meaningless and is returned as zero.
12740     */
12741     case SQLITE_DBSTATUS_CACHE_USED: {
12742       int totalUsed = 0;
12743       int i;
12744       sqlite3BtreeEnterAll(db);
12745       for(i=0; i<db->nDb; i++){
12746         Btree *pBt = db->aDb[i].pBt;
12747         if( pBt ){
12748           Pager *pPager = sqlite3BtreePager(pBt);
12749           totalUsed += sqlite3PagerMemUsed(pPager);
12750         }
12751       }
12752       sqlite3BtreeLeaveAll(db);
12753       *pCurrent = totalUsed;
12754       *pHighwater = 0;
12755       break;
12756     }
12757
12758     /*
12759     ** *pCurrent gets an accurate estimate of the amount of memory used
12760     ** to store the schema for all databases (main, temp, and any ATTACHed
12761     ** databases.  *pHighwater is set to zero.
12762     */
12763     case SQLITE_DBSTATUS_SCHEMA_USED: {
12764       int i;                      /* Used to iterate through schemas */
12765       int nByte = 0;              /* Used to accumulate return value */
12766
12767       sqlite3BtreeEnterAll(db);
12768       db->pnBytesFreed = &nByte;
12769       for(i=0; i<db->nDb; i++){
12770         Schema *pSchema = db->aDb[i].pSchema;
12771         if( ALWAYS(pSchema!=0) ){
12772           HashElem *p;
12773
12774           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12775               pSchema->tblHash.count 
12776             + pSchema->trigHash.count
12777             + pSchema->idxHash.count
12778             + pSchema->fkeyHash.count
12779           );
12780           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12781           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12782           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12783           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12784
12785           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12786             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12787           }
12788           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12789             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12790           }
12791         }
12792       }
12793       db->pnBytesFreed = 0;
12794       sqlite3BtreeLeaveAll(db);
12795
12796       *pHighwater = 0;
12797       *pCurrent = nByte;
12798       break;
12799     }
12800
12801     /*
12802     ** *pCurrent gets an accurate estimate of the amount of memory used
12803     ** to store all prepared statements.
12804     ** *pHighwater is set to zero.
12805     */
12806     case SQLITE_DBSTATUS_STMT_USED: {
12807       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12808       int nByte = 0;              /* Used to accumulate return value */
12809
12810       db->pnBytesFreed = &nByte;
12811       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12812         sqlite3VdbeDeleteObject(db, pVdbe);
12813       }
12814       db->pnBytesFreed = 0;
12815
12816       *pHighwater = 0;
12817       *pCurrent = nByte;
12818
12819       break;
12820     }
12821
12822     default: {
12823       rc = SQLITE_ERROR;
12824     }
12825   }
12826   sqlite3_mutex_leave(db->mutex);
12827   return rc;
12828 }
12829
12830 /************** End of status.c **********************************************/
12831 /************** Begin file date.c ********************************************/
12832 /*
12833 ** 2003 October 31
12834 **
12835 ** The author disclaims copyright to this source code.  In place of
12836 ** a legal notice, here is a blessing:
12837 **
12838 **    May you do good and not evil.
12839 **    May you find forgiveness for yourself and forgive others.
12840 **    May you share freely, never taking more than you give.
12841 **
12842 *************************************************************************
12843 ** This file contains the C functions that implement date and time
12844 ** functions for SQLite.  
12845 **
12846 ** There is only one exported symbol in this file - the function
12847 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12848 ** All other code has file scope.
12849 **
12850 ** SQLite processes all times and dates as Julian Day numbers.  The
12851 ** dates and times are stored as the number of days since noon
12852 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12853 ** calendar system. 
12854 **
12855 ** 1970-01-01 00:00:00 is JD 2440587.5
12856 ** 2000-01-01 00:00:00 is JD 2451544.5
12857 **
12858 ** This implemention requires years to be expressed as a 4-digit number
12859 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12860 ** be represented, even though julian day numbers allow a much wider
12861 ** range of dates.
12862 **
12863 ** The Gregorian calendar system is used for all dates and times,
12864 ** even those that predate the Gregorian calendar.  Historians usually
12865 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12866 ** dates afterwards, depending on locale.  Beware of this difference.
12867 **
12868 ** The conversion algorithms are implemented based on descriptions
12869 ** in the following text:
12870 **
12871 **      Jean Meeus
12872 **      Astronomical Algorithms, 2nd Edition, 1998
12873 **      ISBM 0-943396-61-1
12874 **      Willmann-Bell, Inc
12875 **      Richmond, Virginia (USA)
12876 */
12877 #include <time.h>
12878
12879 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12880
12881 /*
12882 ** On recent Windows platforms, the localtime_s() function is available
12883 ** as part of the "Secure CRT". It is essentially equivalent to 
12884 ** localtime_r() available under most POSIX platforms, except that the 
12885 ** order of the parameters is reversed.
12886 **
12887 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12888 **
12889 ** If the user has not indicated to use localtime_r() or localtime_s()
12890 ** already, check for an MSVC build environment that provides 
12891 ** localtime_s().
12892 */
12893 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12894      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12895 #define HAVE_LOCALTIME_S 1
12896 #endif
12897
12898 /*
12899 ** A structure for holding a single date and time.
12900 */
12901 typedef struct DateTime DateTime;
12902 struct DateTime {
12903   sqlite3_int64 iJD; /* The julian day number times 86400000 */
12904   int Y, M, D;       /* Year, month, and day */
12905   int h, m;          /* Hour and minutes */
12906   int tz;            /* Timezone offset in minutes */
12907   double s;          /* Seconds */
12908   char validYMD;     /* True (1) if Y,M,D are valid */
12909   char validHMS;     /* True (1) if h,m,s are valid */
12910   char validJD;      /* True (1) if iJD is valid */
12911   char validTZ;      /* True (1) if tz is valid */
12912 };
12913
12914
12915 /*
12916 ** Convert zDate into one or more integers.  Additional arguments
12917 ** come in groups of 5 as follows:
12918 **
12919 **       N       number of digits in the integer
12920 **       min     minimum allowed value of the integer
12921 **       max     maximum allowed value of the integer
12922 **       nextC   first character after the integer
12923 **       pVal    where to write the integers value.
12924 **
12925 ** Conversions continue until one with nextC==0 is encountered.
12926 ** The function returns the number of successful conversions.
12927 */
12928 static int getDigits(const char *zDate, ...){
12929   va_list ap;
12930   int val;
12931   int N;
12932   int min;
12933   int max;
12934   int nextC;
12935   int *pVal;
12936   int cnt = 0;
12937   va_start(ap, zDate);
12938   do{
12939     N = va_arg(ap, int);
12940     min = va_arg(ap, int);
12941     max = va_arg(ap, int);
12942     nextC = va_arg(ap, int);
12943     pVal = va_arg(ap, int*);
12944     val = 0;
12945     while( N-- ){
12946       if( !sqlite3Isdigit(*zDate) ){
12947         goto end_getDigits;
12948       }
12949       val = val*10 + *zDate - '0';
12950       zDate++;
12951     }
12952     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12953       goto end_getDigits;
12954     }
12955     *pVal = val;
12956     zDate++;
12957     cnt++;
12958   }while( nextC );
12959 end_getDigits:
12960   va_end(ap);
12961   return cnt;
12962 }
12963
12964 /*
12965 ** Parse a timezone extension on the end of a date-time.
12966 ** The extension is of the form:
12967 **
12968 **        (+/-)HH:MM
12969 **
12970 ** Or the "zulu" notation:
12971 **
12972 **        Z
12973 **
12974 ** If the parse is successful, write the number of minutes
12975 ** of change in p->tz and return 0.  If a parser error occurs,
12976 ** return non-zero.
12977 **
12978 ** A missing specifier is not considered an error.
12979 */
12980 static int parseTimezone(const char *zDate, DateTime *p){
12981   int sgn = 0;
12982   int nHr, nMn;
12983   int c;
12984   while( sqlite3Isspace(*zDate) ){ zDate++; }
12985   p->tz = 0;
12986   c = *zDate;
12987   if( c=='-' ){
12988     sgn = -1;
12989   }else if( c=='+' ){
12990     sgn = +1;
12991   }else if( c=='Z' || c=='z' ){
12992     zDate++;
12993     goto zulu_time;
12994   }else{
12995     return c!=0;
12996   }
12997   zDate++;
12998   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12999     return 1;
13000   }
13001   zDate += 5;
13002   p->tz = sgn*(nMn + nHr*60);
13003 zulu_time:
13004   while( sqlite3Isspace(*zDate) ){ zDate++; }
13005   return *zDate!=0;
13006 }
13007
13008 /*
13009 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13010 ** The HH, MM, and SS must each be exactly 2 digits.  The
13011 ** fractional seconds FFFF can be one or more digits.
13012 **
13013 ** Return 1 if there is a parsing error and 0 on success.
13014 */
13015 static int parseHhMmSs(const char *zDate, DateTime *p){
13016   int h, m, s;
13017   double ms = 0.0;
13018   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13019     return 1;
13020   }
13021   zDate += 5;
13022   if( *zDate==':' ){
13023     zDate++;
13024     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13025       return 1;
13026     }
13027     zDate += 2;
13028     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13029       double rScale = 1.0;
13030       zDate++;
13031       while( sqlite3Isdigit(*zDate) ){
13032         ms = ms*10.0 + *zDate - '0';
13033         rScale *= 10.0;
13034         zDate++;
13035       }
13036       ms /= rScale;
13037     }
13038   }else{
13039     s = 0;
13040   }
13041   p->validJD = 0;
13042   p->validHMS = 1;
13043   p->h = h;
13044   p->m = m;
13045   p->s = s + ms;
13046   if( parseTimezone(zDate, p) ) return 1;
13047   p->validTZ = (p->tz!=0)?1:0;
13048   return 0;
13049 }
13050
13051 /*
13052 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13053 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13054 **
13055 ** Reference:  Meeus page 61
13056 */
13057 static void computeJD(DateTime *p){
13058   int Y, M, D, A, B, X1, X2;
13059
13060   if( p->validJD ) return;
13061   if( p->validYMD ){
13062     Y = p->Y;
13063     M = p->M;
13064     D = p->D;
13065   }else{
13066     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13067     M = 1;
13068     D = 1;
13069   }
13070   if( M<=2 ){
13071     Y--;
13072     M += 12;
13073   }
13074   A = Y/100;
13075   B = 2 - A + (A/4);
13076   X1 = 36525*(Y+4716)/100;
13077   X2 = 306001*(M+1)/10000;
13078   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13079   p->validJD = 1;
13080   if( p->validHMS ){
13081     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13082     if( p->validTZ ){
13083       p->iJD -= p->tz*60000;
13084       p->validYMD = 0;
13085       p->validHMS = 0;
13086       p->validTZ = 0;
13087     }
13088   }
13089 }
13090
13091 /*
13092 ** Parse dates of the form
13093 **
13094 **     YYYY-MM-DD HH:MM:SS.FFF
13095 **     YYYY-MM-DD HH:MM:SS
13096 **     YYYY-MM-DD HH:MM
13097 **     YYYY-MM-DD
13098 **
13099 ** Write the result into the DateTime structure and return 0
13100 ** on success and 1 if the input string is not a well-formed
13101 ** date.
13102 */
13103 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13104   int Y, M, D, neg;
13105
13106   if( zDate[0]=='-' ){
13107     zDate++;
13108     neg = 1;
13109   }else{
13110     neg = 0;
13111   }
13112   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13113     return 1;
13114   }
13115   zDate += 10;
13116   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13117   if( parseHhMmSs(zDate, p)==0 ){
13118     /* We got the time */
13119   }else if( *zDate==0 ){
13120     p->validHMS = 0;
13121   }else{
13122     return 1;
13123   }
13124   p->validJD = 0;
13125   p->validYMD = 1;
13126   p->Y = neg ? -Y : Y;
13127   p->M = M;
13128   p->D = D;
13129   if( p->validTZ ){
13130     computeJD(p);
13131   }
13132   return 0;
13133 }
13134
13135 /*
13136 ** Set the time to the current time reported by the VFS
13137 */
13138 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13139   sqlite3 *db = sqlite3_context_db_handle(context);
13140   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13141   p->validJD = 1;
13142 }
13143
13144 /*
13145 ** Attempt to parse the given string into a Julian Day Number.  Return
13146 ** the number of errors.
13147 **
13148 ** The following are acceptable forms for the input string:
13149 **
13150 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13151 **      DDDD.DD 
13152 **      now
13153 **
13154 ** In the first form, the +/-HH:MM is always optional.  The fractional
13155 ** seconds extension (the ".FFF") is optional.  The seconds portion
13156 ** (":SS.FFF") is option.  The year and date can be omitted as long
13157 ** as there is a time string.  The time string can be omitted as long
13158 ** as there is a year and date.
13159 */
13160 static int parseDateOrTime(
13161   sqlite3_context *context, 
13162   const char *zDate, 
13163   DateTime *p
13164 ){
13165   double r;
13166   if( parseYyyyMmDd(zDate,p)==0 ){
13167     return 0;
13168   }else if( parseHhMmSs(zDate, p)==0 ){
13169     return 0;
13170   }else if( sqlite3StrICmp(zDate,"now")==0){
13171     setDateTimeToCurrent(context, p);
13172     return 0;
13173   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13174     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13175     p->validJD = 1;
13176     return 0;
13177   }
13178   return 1;
13179 }
13180
13181 /*
13182 ** Compute the Year, Month, and Day from the julian day number.
13183 */
13184 static void computeYMD(DateTime *p){
13185   int Z, A, B, C, D, E, X1;
13186   if( p->validYMD ) return;
13187   if( !p->validJD ){
13188     p->Y = 2000;
13189     p->M = 1;
13190     p->D = 1;
13191   }else{
13192     Z = (int)((p->iJD + 43200000)/86400000);
13193     A = (int)((Z - 1867216.25)/36524.25);
13194     A = Z + 1 + A - (A/4);
13195     B = A + 1524;
13196     C = (int)((B - 122.1)/365.25);
13197     D = (36525*C)/100;
13198     E = (int)((B-D)/30.6001);
13199     X1 = (int)(30.6001*E);
13200     p->D = B - D - X1;
13201     p->M = E<14 ? E-1 : E-13;
13202     p->Y = p->M>2 ? C - 4716 : C - 4715;
13203   }
13204   p->validYMD = 1;
13205 }
13206
13207 /*
13208 ** Compute the Hour, Minute, and Seconds from the julian day number.
13209 */
13210 static void computeHMS(DateTime *p){
13211   int s;
13212   if( p->validHMS ) return;
13213   computeJD(p);
13214   s = (int)((p->iJD + 43200000) % 86400000);
13215   p->s = s/1000.0;
13216   s = (int)p->s;
13217   p->s -= s;
13218   p->h = s/3600;
13219   s -= p->h*3600;
13220   p->m = s/60;
13221   p->s += s - p->m*60;
13222   p->validHMS = 1;
13223 }
13224
13225 /*
13226 ** Compute both YMD and HMS
13227 */
13228 static void computeYMD_HMS(DateTime *p){
13229   computeYMD(p);
13230   computeHMS(p);
13231 }
13232
13233 /*
13234 ** Clear the YMD and HMS and the TZ
13235 */
13236 static void clearYMD_HMS_TZ(DateTime *p){
13237   p->validYMD = 0;
13238   p->validHMS = 0;
13239   p->validTZ = 0;
13240 }
13241
13242 #ifndef SQLITE_OMIT_LOCALTIME
13243 /*
13244 ** Compute the difference (in milliseconds)
13245 ** between localtime and UTC (a.k.a. GMT)
13246 ** for the time value p where p is in UTC.
13247 */
13248 static sqlite3_int64 localtimeOffset(DateTime *p){
13249   DateTime x, y;
13250   time_t t;
13251   x = *p;
13252   computeYMD_HMS(&x);
13253   if( x.Y<1971 || x.Y>=2038 ){
13254     x.Y = 2000;
13255     x.M = 1;
13256     x.D = 1;
13257     x.h = 0;
13258     x.m = 0;
13259     x.s = 0.0;
13260   } else {
13261     int s = (int)(x.s + 0.5);
13262     x.s = s;
13263   }
13264   x.tz = 0;
13265   x.validJD = 0;
13266   computeJD(&x);
13267   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13268 #ifdef HAVE_LOCALTIME_R
13269   {
13270     struct tm sLocal;
13271     localtime_r(&t, &sLocal);
13272     y.Y = sLocal.tm_year + 1900;
13273     y.M = sLocal.tm_mon + 1;
13274     y.D = sLocal.tm_mday;
13275     y.h = sLocal.tm_hour;
13276     y.m = sLocal.tm_min;
13277     y.s = sLocal.tm_sec;
13278   }
13279 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13280   {
13281     struct tm sLocal;
13282     localtime_s(&sLocal, &t);
13283     y.Y = sLocal.tm_year + 1900;
13284     y.M = sLocal.tm_mon + 1;
13285     y.D = sLocal.tm_mday;
13286     y.h = sLocal.tm_hour;
13287     y.m = sLocal.tm_min;
13288     y.s = sLocal.tm_sec;
13289   }
13290 #else
13291   {
13292     struct tm *pTm;
13293     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13294     pTm = localtime(&t);
13295     y.Y = pTm->tm_year + 1900;
13296     y.M = pTm->tm_mon + 1;
13297     y.D = pTm->tm_mday;
13298     y.h = pTm->tm_hour;
13299     y.m = pTm->tm_min;
13300     y.s = pTm->tm_sec;
13301     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13302   }
13303 #endif
13304   y.validYMD = 1;
13305   y.validHMS = 1;
13306   y.validJD = 0;
13307   y.validTZ = 0;
13308   computeJD(&y);
13309   return y.iJD - x.iJD;
13310 }
13311 #endif /* SQLITE_OMIT_LOCALTIME */
13312
13313 /*
13314 ** Process a modifier to a date-time stamp.  The modifiers are
13315 ** as follows:
13316 **
13317 **     NNN days
13318 **     NNN hours
13319 **     NNN minutes
13320 **     NNN.NNNN seconds
13321 **     NNN months
13322 **     NNN years
13323 **     start of month
13324 **     start of year
13325 **     start of week
13326 **     start of day
13327 **     weekday N
13328 **     unixepoch
13329 **     localtime
13330 **     utc
13331 **
13332 ** Return 0 on success and 1 if there is any kind of error.
13333 */
13334 static int parseModifier(const char *zMod, DateTime *p){
13335   int rc = 1;
13336   int n;
13337   double r;
13338   char *z, zBuf[30];
13339   z = zBuf;
13340   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13341     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13342   }
13343   z[n] = 0;
13344   switch( z[0] ){
13345 #ifndef SQLITE_OMIT_LOCALTIME
13346     case 'l': {
13347       /*    localtime
13348       **
13349       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13350       ** show local time.
13351       */
13352       if( strcmp(z, "localtime")==0 ){
13353         computeJD(p);
13354         p->iJD += localtimeOffset(p);
13355         clearYMD_HMS_TZ(p);
13356         rc = 0;
13357       }
13358       break;
13359     }
13360 #endif
13361     case 'u': {
13362       /*
13363       **    unixepoch
13364       **
13365       ** Treat the current value of p->iJD as the number of
13366       ** seconds since 1970.  Convert to a real julian day number.
13367       */
13368       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13369         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13370         clearYMD_HMS_TZ(p);
13371         rc = 0;
13372       }
13373 #ifndef SQLITE_OMIT_LOCALTIME
13374       else if( strcmp(z, "utc")==0 ){
13375         sqlite3_int64 c1;
13376         computeJD(p);
13377         c1 = localtimeOffset(p);
13378         p->iJD -= c1;
13379         clearYMD_HMS_TZ(p);
13380         p->iJD += c1 - localtimeOffset(p);
13381         rc = 0;
13382       }
13383 #endif
13384       break;
13385     }
13386     case 'w': {
13387       /*
13388       **    weekday N
13389       **
13390       ** Move the date to the same time on the next occurrence of
13391       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13392       ** date is already on the appropriate weekday, this is a no-op.
13393       */
13394       if( strncmp(z, "weekday ", 8)==0
13395                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13396                && (n=(int)r)==r && n>=0 && r<7 ){
13397         sqlite3_int64 Z;
13398         computeYMD_HMS(p);
13399         p->validTZ = 0;
13400         p->validJD = 0;
13401         computeJD(p);
13402         Z = ((p->iJD + 129600000)/86400000) % 7;
13403         if( Z>n ) Z -= 7;
13404         p->iJD += (n - Z)*86400000;
13405         clearYMD_HMS_TZ(p);
13406         rc = 0;
13407       }
13408       break;
13409     }
13410     case 's': {
13411       /*
13412       **    start of TTTTT
13413       **
13414       ** Move the date backwards to the beginning of the current day,
13415       ** or month or year.
13416       */
13417       if( strncmp(z, "start of ", 9)!=0 ) break;
13418       z += 9;
13419       computeYMD(p);
13420       p->validHMS = 1;
13421       p->h = p->m = 0;
13422       p->s = 0.0;
13423       p->validTZ = 0;
13424       p->validJD = 0;
13425       if( strcmp(z,"month")==0 ){
13426         p->D = 1;
13427         rc = 0;
13428       }else if( strcmp(z,"year")==0 ){
13429         computeYMD(p);
13430         p->M = 1;
13431         p->D = 1;
13432         rc = 0;
13433       }else if( strcmp(z,"day")==0 ){
13434         rc = 0;
13435       }
13436       break;
13437     }
13438     case '+':
13439     case '-':
13440     case '0':
13441     case '1':
13442     case '2':
13443     case '3':
13444     case '4':
13445     case '5':
13446     case '6':
13447     case '7':
13448     case '8':
13449     case '9': {
13450       double rRounder;
13451       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13452       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13453         rc = 1;
13454         break;
13455       }
13456       if( z[n]==':' ){
13457         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13458         ** specified number of hours, minutes, seconds, and fractional seconds
13459         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13460         ** omitted.
13461         */
13462         const char *z2 = z;
13463         DateTime tx;
13464         sqlite3_int64 day;
13465         if( !sqlite3Isdigit(*z2) ) z2++;
13466         memset(&tx, 0, sizeof(tx));
13467         if( parseHhMmSs(z2, &tx) ) break;
13468         computeJD(&tx);
13469         tx.iJD -= 43200000;
13470         day = tx.iJD/86400000;
13471         tx.iJD -= day*86400000;
13472         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13473         computeJD(p);
13474         clearYMD_HMS_TZ(p);
13475         p->iJD += tx.iJD;
13476         rc = 0;
13477         break;
13478       }
13479       z += n;
13480       while( sqlite3Isspace(*z) ) z++;
13481       n = sqlite3Strlen30(z);
13482       if( n>10 || n<3 ) break;
13483       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13484       computeJD(p);
13485       rc = 0;
13486       rRounder = r<0 ? -0.5 : +0.5;
13487       if( n==3 && strcmp(z,"day")==0 ){
13488         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13489       }else if( n==4 && strcmp(z,"hour")==0 ){
13490         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13491       }else if( n==6 && strcmp(z,"minute")==0 ){
13492         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13493       }else if( n==6 && strcmp(z,"second")==0 ){
13494         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13495       }else if( n==5 && strcmp(z,"month")==0 ){
13496         int x, y;
13497         computeYMD_HMS(p);
13498         p->M += (int)r;
13499         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13500         p->Y += x;
13501         p->M -= x*12;
13502         p->validJD = 0;
13503         computeJD(p);
13504         y = (int)r;
13505         if( y!=r ){
13506           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13507         }
13508       }else if( n==4 && strcmp(z,"year")==0 ){
13509         int y = (int)r;
13510         computeYMD_HMS(p);
13511         p->Y += y;
13512         p->validJD = 0;
13513         computeJD(p);
13514         if( y!=r ){
13515           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13516         }
13517       }else{
13518         rc = 1;
13519       }
13520       clearYMD_HMS_TZ(p);
13521       break;
13522     }
13523     default: {
13524       break;
13525     }
13526   }
13527   return rc;
13528 }
13529
13530 /*
13531 ** Process time function arguments.  argv[0] is a date-time stamp.
13532 ** argv[1] and following are modifiers.  Parse them all and write
13533 ** the resulting time into the DateTime structure p.  Return 0
13534 ** on success and 1 if there are any errors.
13535 **
13536 ** If there are zero parameters (if even argv[0] is undefined)
13537 ** then assume a default value of "now" for argv[0].
13538 */
13539 static int isDate(
13540   sqlite3_context *context, 
13541   int argc, 
13542   sqlite3_value **argv, 
13543   DateTime *p
13544 ){
13545   int i;
13546   const unsigned char *z;
13547   int eType;
13548   memset(p, 0, sizeof(*p));
13549   if( argc==0 ){
13550     setDateTimeToCurrent(context, p);
13551   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13552                    || eType==SQLITE_INTEGER ){
13553     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13554     p->validJD = 1;
13555   }else{
13556     z = sqlite3_value_text(argv[0]);
13557     if( !z || parseDateOrTime(context, (char*)z, p) ){
13558       return 1;
13559     }
13560   }
13561   for(i=1; i<argc; i++){
13562     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13563       return 1;
13564     }
13565   }
13566   return 0;
13567 }
13568
13569
13570 /*
13571 ** The following routines implement the various date and time functions
13572 ** of SQLite.
13573 */
13574
13575 /*
13576 **    julianday( TIMESTRING, MOD, MOD, ...)
13577 **
13578 ** Return the julian day number of the date specified in the arguments
13579 */
13580 static void juliandayFunc(
13581   sqlite3_context *context,
13582   int argc,
13583   sqlite3_value **argv
13584 ){
13585   DateTime x;
13586   if( isDate(context, argc, argv, &x)==0 ){
13587     computeJD(&x);
13588     sqlite3_result_double(context, x.iJD/86400000.0);
13589   }
13590 }
13591
13592 /*
13593 **    datetime( TIMESTRING, MOD, MOD, ...)
13594 **
13595 ** Return YYYY-MM-DD HH:MM:SS
13596 */
13597 static void datetimeFunc(
13598   sqlite3_context *context,
13599   int argc,
13600   sqlite3_value **argv
13601 ){
13602   DateTime x;
13603   if( isDate(context, argc, argv, &x)==0 ){
13604     char zBuf[100];
13605     computeYMD_HMS(&x);
13606     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13607                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13608     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13609   }
13610 }
13611
13612 /*
13613 **    time( TIMESTRING, MOD, MOD, ...)
13614 **
13615 ** Return HH:MM:SS
13616 */
13617 static void timeFunc(
13618   sqlite3_context *context,
13619   int argc,
13620   sqlite3_value **argv
13621 ){
13622   DateTime x;
13623   if( isDate(context, argc, argv, &x)==0 ){
13624     char zBuf[100];
13625     computeHMS(&x);
13626     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13627     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13628   }
13629 }
13630
13631 /*
13632 **    date( TIMESTRING, MOD, MOD, ...)
13633 **
13634 ** Return YYYY-MM-DD
13635 */
13636 static void dateFunc(
13637   sqlite3_context *context,
13638   int argc,
13639   sqlite3_value **argv
13640 ){
13641   DateTime x;
13642   if( isDate(context, argc, argv, &x)==0 ){
13643     char zBuf[100];
13644     computeYMD(&x);
13645     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13646     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13647   }
13648 }
13649
13650 /*
13651 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13652 **
13653 ** Return a string described by FORMAT.  Conversions as follows:
13654 **
13655 **   %d  day of month
13656 **   %f  ** fractional seconds  SS.SSS
13657 **   %H  hour 00-24
13658 **   %j  day of year 000-366
13659 **   %J  ** Julian day number
13660 **   %m  month 01-12
13661 **   %M  minute 00-59
13662 **   %s  seconds since 1970-01-01
13663 **   %S  seconds 00-59
13664 **   %w  day of week 0-6  sunday==0
13665 **   %W  week of year 00-53
13666 **   %Y  year 0000-9999
13667 **   %%  %
13668 */
13669 static void strftimeFunc(
13670   sqlite3_context *context,
13671   int argc,
13672   sqlite3_value **argv
13673 ){
13674   DateTime x;
13675   u64 n;
13676   size_t i,j;
13677   char *z;
13678   sqlite3 *db;
13679   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13680   char zBuf[100];
13681   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13682   db = sqlite3_context_db_handle(context);
13683   for(i=0, n=1; zFmt[i]; i++, n++){
13684     if( zFmt[i]=='%' ){
13685       switch( zFmt[i+1] ){
13686         case 'd':
13687         case 'H':
13688         case 'm':
13689         case 'M':
13690         case 'S':
13691         case 'W':
13692           n++;
13693           /* fall thru */
13694         case 'w':
13695         case '%':
13696           break;
13697         case 'f':
13698           n += 8;
13699           break;
13700         case 'j':
13701           n += 3;
13702           break;
13703         case 'Y':
13704           n += 8;
13705           break;
13706         case 's':
13707         case 'J':
13708           n += 50;
13709           break;
13710         default:
13711           return;  /* ERROR.  return a NULL */
13712       }
13713       i++;
13714     }
13715   }
13716   testcase( n==sizeof(zBuf)-1 );
13717   testcase( n==sizeof(zBuf) );
13718   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13719   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13720   if( n<sizeof(zBuf) ){
13721     z = zBuf;
13722   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13723     sqlite3_result_error_toobig(context);
13724     return;
13725   }else{
13726     z = sqlite3DbMallocRaw(db, (int)n);
13727     if( z==0 ){
13728       sqlite3_result_error_nomem(context);
13729       return;
13730     }
13731   }
13732   computeJD(&x);
13733   computeYMD_HMS(&x);
13734   for(i=j=0; zFmt[i]; i++){
13735     if( zFmt[i]!='%' ){
13736       z[j++] = zFmt[i];
13737     }else{
13738       i++;
13739       switch( zFmt[i] ){
13740         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13741         case 'f': {
13742           double s = x.s;
13743           if( s>59.999 ) s = 59.999;
13744           sqlite3_snprintf(7, &z[j],"%06.3f", s);
13745           j += sqlite3Strlen30(&z[j]);
13746           break;
13747         }
13748         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13749         case 'W': /* Fall thru */
13750         case 'j': {
13751           int nDay;             /* Number of days since 1st day of year */
13752           DateTime y = x;
13753           y.validJD = 0;
13754           y.M = 1;
13755           y.D = 1;
13756           computeJD(&y);
13757           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13758           if( zFmt[i]=='W' ){
13759             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13760             wd = (int)(((x.iJD+43200000)/86400000)%7);
13761             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13762             j += 2;
13763           }else{
13764             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13765             j += 3;
13766           }
13767           break;
13768         }
13769         case 'J': {
13770           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13771           j+=sqlite3Strlen30(&z[j]);
13772           break;
13773         }
13774         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13775         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13776         case 's': {
13777           sqlite3_snprintf(30,&z[j],"%lld",
13778                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
13779           j += sqlite3Strlen30(&z[j]);
13780           break;
13781         }
13782         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13783         case 'w': {
13784           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13785           break;
13786         }
13787         case 'Y': {
13788           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13789           break;
13790         }
13791         default:   z[j++] = '%'; break;
13792       }
13793     }
13794   }
13795   z[j] = 0;
13796   sqlite3_result_text(context, z, -1,
13797                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13798 }
13799
13800 /*
13801 ** current_time()
13802 **
13803 ** This function returns the same value as time('now').
13804 */
13805 static void ctimeFunc(
13806   sqlite3_context *context,
13807   int NotUsed,
13808   sqlite3_value **NotUsed2
13809 ){
13810   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13811   timeFunc(context, 0, 0);
13812 }
13813
13814 /*
13815 ** current_date()
13816 **
13817 ** This function returns the same value as date('now').
13818 */
13819 static void cdateFunc(
13820   sqlite3_context *context,
13821   int NotUsed,
13822   sqlite3_value **NotUsed2
13823 ){
13824   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13825   dateFunc(context, 0, 0);
13826 }
13827
13828 /*
13829 ** current_timestamp()
13830 **
13831 ** This function returns the same value as datetime('now').
13832 */
13833 static void ctimestampFunc(
13834   sqlite3_context *context,
13835   int NotUsed,
13836   sqlite3_value **NotUsed2
13837 ){
13838   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13839   datetimeFunc(context, 0, 0);
13840 }
13841 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13842
13843 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13844 /*
13845 ** If the library is compiled to omit the full-scale date and time
13846 ** handling (to get a smaller binary), the following minimal version
13847 ** of the functions current_time(), current_date() and current_timestamp()
13848 ** are included instead. This is to support column declarations that
13849 ** include "DEFAULT CURRENT_TIME" etc.
13850 **
13851 ** This function uses the C-library functions time(), gmtime()
13852 ** and strftime(). The format string to pass to strftime() is supplied
13853 ** as the user-data for the function.
13854 */
13855 static void currentTimeFunc(
13856   sqlite3_context *context,
13857   int argc,
13858   sqlite3_value **argv
13859 ){
13860   time_t t;
13861   char *zFormat = (char *)sqlite3_user_data(context);
13862   sqlite3 *db;
13863   sqlite3_int64 iT;
13864   char zBuf[20];
13865
13866   UNUSED_PARAMETER(argc);
13867   UNUSED_PARAMETER(argv);
13868
13869   db = sqlite3_context_db_handle(context);
13870   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13871   t = iT/1000 - 10000*(sqlite3_int64)21086676;
13872 #ifdef HAVE_GMTIME_R
13873   {
13874     struct tm sNow;
13875     gmtime_r(&t, &sNow);
13876     strftime(zBuf, 20, zFormat, &sNow);
13877   }
13878 #else
13879   {
13880     struct tm *pTm;
13881     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13882     pTm = gmtime(&t);
13883     strftime(zBuf, 20, zFormat, pTm);
13884     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13885   }
13886 #endif
13887
13888   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13889 }
13890 #endif
13891
13892 /*
13893 ** This function registered all of the above C functions as SQL
13894 ** functions.  This should be the only routine in this file with
13895 ** external linkage.
13896 */
13897 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13898   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13899 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13900     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13901     FUNCTION(date,             -1, 0, 0, dateFunc      ),
13902     FUNCTION(time,             -1, 0, 0, timeFunc      ),
13903     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13904     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13905     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13906     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13907     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13908 #else
13909     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13910     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13911     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13912 #endif
13913   };
13914   int i;
13915   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13916   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13917
13918   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13919     sqlite3FuncDefInsert(pHash, &aFunc[i]);
13920   }
13921 }
13922
13923 /************** End of date.c ************************************************/
13924 /************** Begin file os.c **********************************************/
13925 /*
13926 ** 2005 November 29
13927 **
13928 ** The author disclaims copyright to this source code.  In place of
13929 ** a legal notice, here is a blessing:
13930 **
13931 **    May you do good and not evil.
13932 **    May you find forgiveness for yourself and forgive others.
13933 **    May you share freely, never taking more than you give.
13934 **
13935 ******************************************************************************
13936 **
13937 ** This file contains OS interface code that is common to all
13938 ** architectures.
13939 */
13940 #define _SQLITE_OS_C_ 1
13941 #undef _SQLITE_OS_C_
13942
13943 /*
13944 ** The default SQLite sqlite3_vfs implementations do not allocate
13945 ** memory (actually, os_unix.c allocates a small amount of memory
13946 ** from within OsOpen()), but some third-party implementations may.
13947 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13948 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13949 **
13950 ** The following functions are instrumented for malloc() failure 
13951 ** testing:
13952 **
13953 **     sqlite3OsOpen()
13954 **     sqlite3OsRead()
13955 **     sqlite3OsWrite()
13956 **     sqlite3OsSync()
13957 **     sqlite3OsLock()
13958 **
13959 */
13960 #if defined(SQLITE_TEST)
13961 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13962   #define DO_OS_MALLOC_TEST(x)                                       \
13963   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13964     void *pTstAlloc = sqlite3Malloc(10);                             \
13965     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13966     sqlite3_free(pTstAlloc);                                         \
13967   }
13968 #else
13969   #define DO_OS_MALLOC_TEST(x)
13970 #endif
13971
13972 /*
13973 ** The following routines are convenience wrappers around methods
13974 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13975 ** of this would be completely automatic if SQLite were coded using
13976 ** C++ instead of plain old C.
13977 */
13978 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13979   int rc = SQLITE_OK;
13980   if( pId->pMethods ){
13981     rc = pId->pMethods->xClose(pId);
13982     pId->pMethods = 0;
13983   }
13984   return rc;
13985 }
13986 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13987   DO_OS_MALLOC_TEST(id);
13988   return id->pMethods->xRead(id, pBuf, amt, offset);
13989 }
13990 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13991   DO_OS_MALLOC_TEST(id);
13992   return id->pMethods->xWrite(id, pBuf, amt, offset);
13993 }
13994 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13995   return id->pMethods->xTruncate(id, size);
13996 }
13997 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13998   DO_OS_MALLOC_TEST(id);
13999   return id->pMethods->xSync(id, flags);
14000 }
14001 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14002   DO_OS_MALLOC_TEST(id);
14003   return id->pMethods->xFileSize(id, pSize);
14004 }
14005 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14006   DO_OS_MALLOC_TEST(id);
14007   return id->pMethods->xLock(id, lockType);
14008 }
14009 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14010   return id->pMethods->xUnlock(id, lockType);
14011 }
14012 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14013   DO_OS_MALLOC_TEST(id);
14014   return id->pMethods->xCheckReservedLock(id, pResOut);
14015 }
14016 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14017   return id->pMethods->xFileControl(id, op, pArg);
14018 }
14019 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14020   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14021   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14022 }
14023 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14024   return id->pMethods->xDeviceCharacteristics(id);
14025 }
14026 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14027   return id->pMethods->xShmLock(id, offset, n, flags);
14028 }
14029 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14030   id->pMethods->xShmBarrier(id);
14031 }
14032 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14033   return id->pMethods->xShmUnmap(id, deleteFlag);
14034 }
14035 SQLITE_PRIVATE int sqlite3OsShmMap(
14036   sqlite3_file *id,               /* Database file handle */
14037   int iPage,
14038   int pgsz,
14039   int bExtend,                    /* True to extend file if necessary */
14040   void volatile **pp              /* OUT: Pointer to mapping */
14041 ){
14042   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14043 }
14044
14045 /*
14046 ** The next group of routines are convenience wrappers around the
14047 ** VFS methods.
14048 */
14049 SQLITE_PRIVATE int sqlite3OsOpen(
14050   sqlite3_vfs *pVfs, 
14051   const char *zPath, 
14052   sqlite3_file *pFile, 
14053   int flags, 
14054   int *pFlagsOut
14055 ){
14056   int rc;
14057   DO_OS_MALLOC_TEST(0);
14058   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14059   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14060   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14061   ** reaching the VFS. */
14062   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14063   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14064   return rc;
14065 }
14066 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14067   return pVfs->xDelete(pVfs, zPath, dirSync);
14068 }
14069 SQLITE_PRIVATE int sqlite3OsAccess(
14070   sqlite3_vfs *pVfs, 
14071   const char *zPath, 
14072   int flags, 
14073   int *pResOut
14074 ){
14075   DO_OS_MALLOC_TEST(0);
14076   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14077 }
14078 SQLITE_PRIVATE int sqlite3OsFullPathname(
14079   sqlite3_vfs *pVfs, 
14080   const char *zPath, 
14081   int nPathOut, 
14082   char *zPathOut
14083 ){
14084   zPathOut[0] = 0;
14085   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14086 }
14087 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14088 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14089   return pVfs->xDlOpen(pVfs, zPath);
14090 }
14091 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14092   pVfs->xDlError(pVfs, nByte, zBufOut);
14093 }
14094 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14095   return pVfs->xDlSym(pVfs, pHdle, zSym);
14096 }
14097 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14098   pVfs->xDlClose(pVfs, pHandle);
14099 }
14100 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14101 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14102   return pVfs->xRandomness(pVfs, nByte, zBufOut);
14103 }
14104 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14105   return pVfs->xSleep(pVfs, nMicro);
14106 }
14107 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14108   int rc;
14109   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14110   ** method to get the current date and time if that method is available
14111   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14112   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14113   ** unavailable.
14114   */
14115   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14116     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14117   }else{
14118     double r;
14119     rc = pVfs->xCurrentTime(pVfs, &r);
14120     *pTimeOut = (sqlite3_int64)(r*86400000.0);
14121   }
14122   return rc;
14123 }
14124
14125 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14126   sqlite3_vfs *pVfs, 
14127   const char *zFile, 
14128   sqlite3_file **ppFile, 
14129   int flags,
14130   int *pOutFlags
14131 ){
14132   int rc = SQLITE_NOMEM;
14133   sqlite3_file *pFile;
14134   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14135   if( pFile ){
14136     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14137     if( rc!=SQLITE_OK ){
14138       sqlite3_free(pFile);
14139     }else{
14140       *ppFile = pFile;
14141     }
14142   }
14143   return rc;
14144 }
14145 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14146   int rc = SQLITE_OK;
14147   assert( pFile );
14148   rc = sqlite3OsClose(pFile);
14149   sqlite3_free(pFile);
14150   return rc;
14151 }
14152
14153 /*
14154 ** This function is a wrapper around the OS specific implementation of
14155 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14156 ** ability to simulate a malloc failure, so that the handling of an
14157 ** error in sqlite3_os_init() by the upper layers can be tested.
14158 */
14159 SQLITE_PRIVATE int sqlite3OsInit(void){
14160   void *p = sqlite3_malloc(10);
14161   if( p==0 ) return SQLITE_NOMEM;
14162   sqlite3_free(p);
14163   return sqlite3_os_init();
14164 }
14165
14166 /*
14167 ** The list of all registered VFS implementations.
14168 */
14169 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14170 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14171
14172 /*
14173 ** Locate a VFS by name.  If no name is given, simply return the
14174 ** first VFS on the list.
14175 */
14176 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14177   sqlite3_vfs *pVfs = 0;
14178 #if SQLITE_THREADSAFE
14179   sqlite3_mutex *mutex;
14180 #endif
14181 #ifndef SQLITE_OMIT_AUTOINIT
14182   int rc = sqlite3_initialize();
14183   if( rc ) return 0;
14184 #endif
14185 #if SQLITE_THREADSAFE
14186   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14187 #endif
14188   sqlite3_mutex_enter(mutex);
14189   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14190     if( zVfs==0 ) break;
14191     if( strcmp(zVfs, pVfs->zName)==0 ) break;
14192   }
14193   sqlite3_mutex_leave(mutex);
14194   return pVfs;
14195 }
14196
14197 /*
14198 ** Unlink a VFS from the linked list
14199 */
14200 static void vfsUnlink(sqlite3_vfs *pVfs){
14201   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14202   if( pVfs==0 ){
14203     /* No-op */
14204   }else if( vfsList==pVfs ){
14205     vfsList = pVfs->pNext;
14206   }else if( vfsList ){
14207     sqlite3_vfs *p = vfsList;
14208     while( p->pNext && p->pNext!=pVfs ){
14209       p = p->pNext;
14210     }
14211     if( p->pNext==pVfs ){
14212       p->pNext = pVfs->pNext;
14213     }
14214   }
14215 }
14216
14217 /*
14218 ** Register a VFS with the system.  It is harmless to register the same
14219 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
14220 ** true.
14221 */
14222 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14223   sqlite3_mutex *mutex = 0;
14224 #ifndef SQLITE_OMIT_AUTOINIT
14225   int rc = sqlite3_initialize();
14226   if( rc ) return rc;
14227 #endif
14228   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14229   sqlite3_mutex_enter(mutex);
14230   vfsUnlink(pVfs);
14231   if( makeDflt || vfsList==0 ){
14232     pVfs->pNext = vfsList;
14233     vfsList = pVfs;
14234   }else{
14235     pVfs->pNext = vfsList->pNext;
14236     vfsList->pNext = pVfs;
14237   }
14238   assert(vfsList);
14239   sqlite3_mutex_leave(mutex);
14240   return SQLITE_OK;
14241 }
14242
14243 /*
14244 ** Unregister a VFS so that it is no longer accessible.
14245 */
14246 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14247 #if SQLITE_THREADSAFE
14248   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14249 #endif
14250   sqlite3_mutex_enter(mutex);
14251   vfsUnlink(pVfs);
14252   sqlite3_mutex_leave(mutex);
14253   return SQLITE_OK;
14254 }
14255
14256 /************** End of os.c **************************************************/
14257 /************** Begin file fault.c *******************************************/
14258 /*
14259 ** 2008 Jan 22
14260 **
14261 ** The author disclaims copyright to this source code.  In place of
14262 ** a legal notice, here is a blessing:
14263 **
14264 **    May you do good and not evil.
14265 **    May you find forgiveness for yourself and forgive others.
14266 **    May you share freely, never taking more than you give.
14267 **
14268 *************************************************************************
14269 **
14270 ** This file contains code to support the concept of "benign" 
14271 ** malloc failures (when the xMalloc() or xRealloc() method of the
14272 ** sqlite3_mem_methods structure fails to allocate a block of memory
14273 ** and returns 0). 
14274 **
14275 ** Most malloc failures are non-benign. After they occur, SQLite
14276 ** abandons the current operation and returns an error code (usually
14277 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14278 ** fatal. For example, if a malloc fails while resizing a hash table, this 
14279 ** is completely recoverable simply by not carrying out the resize. The 
14280 ** hash table will continue to function normally.  So a malloc failure 
14281 ** during a hash table resize is a benign fault.
14282 */
14283
14284
14285 #ifndef SQLITE_OMIT_BUILTIN_TEST
14286
14287 /*
14288 ** Global variables.
14289 */
14290 typedef struct BenignMallocHooks BenignMallocHooks;
14291 static SQLITE_WSD struct BenignMallocHooks {
14292   void (*xBenignBegin)(void);
14293   void (*xBenignEnd)(void);
14294 } sqlite3Hooks = { 0, 0 };
14295
14296 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14297 ** structure.  If writable static data is unsupported on the target,
14298 ** we have to locate the state vector at run-time.  In the more common
14299 ** case where writable static data is supported, wsdHooks can refer directly
14300 ** to the "sqlite3Hooks" state vector declared above.
14301 */
14302 #ifdef SQLITE_OMIT_WSD
14303 # define wsdHooksInit \
14304   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14305 # define wsdHooks x[0]
14306 #else
14307 # define wsdHooksInit
14308 # define wsdHooks sqlite3Hooks
14309 #endif
14310
14311
14312 /*
14313 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14314 ** sqlite3EndBenignMalloc() are called, respectively.
14315 */
14316 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14317   void (*xBenignBegin)(void),
14318   void (*xBenignEnd)(void)
14319 ){
14320   wsdHooksInit;
14321   wsdHooks.xBenignBegin = xBenignBegin;
14322   wsdHooks.xBenignEnd = xBenignEnd;
14323 }
14324
14325 /*
14326 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14327 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14328 ** indicates that subsequent malloc failures are non-benign.
14329 */
14330 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14331   wsdHooksInit;
14332   if( wsdHooks.xBenignBegin ){
14333     wsdHooks.xBenignBegin();
14334   }
14335 }
14336 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14337   wsdHooksInit;
14338   if( wsdHooks.xBenignEnd ){
14339     wsdHooks.xBenignEnd();
14340   }
14341 }
14342
14343 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14344
14345 /************** End of fault.c ***********************************************/
14346 /************** Begin file mem0.c ********************************************/
14347 /*
14348 ** 2008 October 28
14349 **
14350 ** The author disclaims copyright to this source code.  In place of
14351 ** a legal notice, here is a blessing:
14352 **
14353 **    May you do good and not evil.
14354 **    May you find forgiveness for yourself and forgive others.
14355 **    May you share freely, never taking more than you give.
14356 **
14357 *************************************************************************
14358 **
14359 ** This file contains a no-op memory allocation drivers for use when
14360 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14361 ** here always fail.  SQLite will not operate with these drivers.  These
14362 ** are merely placeholders.  Real drivers must be substituted using
14363 ** sqlite3_config() before SQLite will operate.
14364 */
14365
14366 /*
14367 ** This version of the memory allocator is the default.  It is
14368 ** used when no other memory allocator is specified using compile-time
14369 ** macros.
14370 */
14371 #ifdef SQLITE_ZERO_MALLOC
14372
14373 /*
14374 ** No-op versions of all memory allocation routines
14375 */
14376 static void *sqlite3MemMalloc(int nByte){ return 0; }
14377 static void sqlite3MemFree(void *pPrior){ return; }
14378 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14379 static int sqlite3MemSize(void *pPrior){ return 0; }
14380 static int sqlite3MemRoundup(int n){ return n; }
14381 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14382 static void sqlite3MemShutdown(void *NotUsed){ return; }
14383
14384 /*
14385 ** This routine is the only routine in this file with external linkage.
14386 **
14387 ** Populate the low-level memory allocation function pointers in
14388 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14389 */
14390 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14391   static const sqlite3_mem_methods defaultMethods = {
14392      sqlite3MemMalloc,
14393      sqlite3MemFree,
14394      sqlite3MemRealloc,
14395      sqlite3MemSize,
14396      sqlite3MemRoundup,
14397      sqlite3MemInit,
14398      sqlite3MemShutdown,
14399      0
14400   };
14401   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14402 }
14403
14404 #endif /* SQLITE_ZERO_MALLOC */
14405
14406 /************** End of mem0.c ************************************************/
14407 /************** Begin file mem1.c ********************************************/
14408 /*
14409 ** 2007 August 14
14410 **
14411 ** The author disclaims copyright to this source code.  In place of
14412 ** a legal notice, here is a blessing:
14413 **
14414 **    May you do good and not evil.
14415 **    May you find forgiveness for yourself and forgive others.
14416 **    May you share freely, never taking more than you give.
14417 **
14418 *************************************************************************
14419 **
14420 ** This file contains low-level memory allocation drivers for when
14421 ** SQLite will use the standard C-library malloc/realloc/free interface
14422 ** to obtain the memory it needs.
14423 **
14424 ** This file contains implementations of the low-level memory allocation
14425 ** routines specified in the sqlite3_mem_methods object.
14426 */
14427
14428 /*
14429 ** This version of the memory allocator is the default.  It is
14430 ** used when no other memory allocator is specified using compile-time
14431 ** macros.
14432 */
14433 #ifdef SQLITE_SYSTEM_MALLOC
14434
14435 /*
14436 ** Like malloc(), but remember the size of the allocation
14437 ** so that we can find it later using sqlite3MemSize().
14438 **
14439 ** For this low-level routine, we are guaranteed that nByte>0 because
14440 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14441 ** routines.
14442 */
14443 static void *sqlite3MemMalloc(int nByte){
14444   sqlite3_int64 *p;
14445   assert( nByte>0 );
14446   nByte = ROUND8(nByte);
14447   p = malloc( nByte+8 );
14448   if( p ){
14449     p[0] = nByte;
14450     p++;
14451   }else{
14452     testcase( sqlite3GlobalConfig.xLog!=0 );
14453     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14454   }
14455   return (void *)p;
14456 }
14457
14458 /*
14459 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14460 ** or sqlite3MemRealloc().
14461 **
14462 ** For this low-level routine, we already know that pPrior!=0 since
14463 ** cases where pPrior==0 will have been intecepted and dealt with
14464 ** by higher-level routines.
14465 */
14466 static void sqlite3MemFree(void *pPrior){
14467   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14468   assert( pPrior!=0 );
14469   p--;
14470   free(p);
14471 }
14472
14473 /*
14474 ** Report the allocated size of a prior return from xMalloc()
14475 ** or xRealloc().
14476 */
14477 static int sqlite3MemSize(void *pPrior){
14478   sqlite3_int64 *p;
14479   if( pPrior==0 ) return 0;
14480   p = (sqlite3_int64*)pPrior;
14481   p--;
14482   return (int)p[0];
14483 }
14484
14485 /*
14486 ** Like realloc().  Resize an allocation previously obtained from
14487 ** sqlite3MemMalloc().
14488 **
14489 ** For this low-level interface, we know that pPrior!=0.  Cases where
14490 ** pPrior==0 while have been intercepted by higher-level routine and
14491 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14492 ** cases where nByte<=0 will have been intercepted by higher-level
14493 ** routines and redirected to xFree.
14494 */
14495 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14496   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14497   assert( pPrior!=0 && nByte>0 );
14498   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14499   p--;
14500   p = realloc(p, nByte+8 );
14501   if( p ){
14502     p[0] = nByte;
14503     p++;
14504   }else{
14505     testcase( sqlite3GlobalConfig.xLog!=0 );
14506     sqlite3_log(SQLITE_NOMEM,
14507       "failed memory resize %u to %u bytes",
14508       sqlite3MemSize(pPrior), nByte);
14509   }
14510   return (void*)p;
14511 }
14512
14513 /*
14514 ** Round up a request size to the next valid allocation size.
14515 */
14516 static int sqlite3MemRoundup(int n){
14517   return ROUND8(n);
14518 }
14519
14520 /*
14521 ** Initialize this module.
14522 */
14523 static int sqlite3MemInit(void *NotUsed){
14524   UNUSED_PARAMETER(NotUsed);
14525   return SQLITE_OK;
14526 }
14527
14528 /*
14529 ** Deinitialize this module.
14530 */
14531 static void sqlite3MemShutdown(void *NotUsed){
14532   UNUSED_PARAMETER(NotUsed);
14533   return;
14534 }
14535
14536 /*
14537 ** This routine is the only routine in this file with external linkage.
14538 **
14539 ** Populate the low-level memory allocation function pointers in
14540 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14541 */
14542 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14543   static const sqlite3_mem_methods defaultMethods = {
14544      sqlite3MemMalloc,
14545      sqlite3MemFree,
14546      sqlite3MemRealloc,
14547      sqlite3MemSize,
14548      sqlite3MemRoundup,
14549      sqlite3MemInit,
14550      sqlite3MemShutdown,
14551      0
14552   };
14553   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14554 }
14555
14556 #endif /* SQLITE_SYSTEM_MALLOC */
14557
14558 /************** End of mem1.c ************************************************/
14559 /************** Begin file mem2.c ********************************************/
14560 /*
14561 ** 2007 August 15
14562 **
14563 ** The author disclaims copyright to this source code.  In place of
14564 ** a legal notice, here is a blessing:
14565 **
14566 **    May you do good and not evil.
14567 **    May you find forgiveness for yourself and forgive others.
14568 **    May you share freely, never taking more than you give.
14569 **
14570 *************************************************************************
14571 **
14572 ** This file contains low-level memory allocation drivers for when
14573 ** SQLite will use the standard C-library malloc/realloc/free interface
14574 ** to obtain the memory it needs while adding lots of additional debugging
14575 ** information to each allocation in order to help detect and fix memory
14576 ** leaks and memory usage errors.
14577 **
14578 ** This file contains implementations of the low-level memory allocation
14579 ** routines specified in the sqlite3_mem_methods object.
14580 */
14581
14582 /*
14583 ** This version of the memory allocator is used only if the
14584 ** SQLITE_MEMDEBUG macro is defined
14585 */
14586 #ifdef SQLITE_MEMDEBUG
14587
14588 /*
14589 ** The backtrace functionality is only available with GLIBC
14590 */
14591 #ifdef __GLIBC__
14592   extern int backtrace(void**,int);
14593   extern void backtrace_symbols_fd(void*const*,int,int);
14594 #else
14595 # define backtrace(A,B) 1
14596 # define backtrace_symbols_fd(A,B,C)
14597 #endif
14598
14599 /*
14600 ** Each memory allocation looks like this:
14601 **
14602 **  ------------------------------------------------------------------------
14603 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14604 **  ------------------------------------------------------------------------
14605 **
14606 ** The application code sees only a pointer to the allocation.  We have
14607 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14608 ** MemBlockHdr tells us the size of the allocation and the number of
14609 ** backtrace pointers.  There is also a guard word at the end of the
14610 ** MemBlockHdr.
14611 */
14612 struct MemBlockHdr {
14613   i64 iSize;                          /* Size of this allocation */
14614   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14615   char nBacktrace;                    /* Number of backtraces on this alloc */
14616   char nBacktraceSlots;               /* Available backtrace slots */
14617   u8 nTitle;                          /* Bytes of title; includes '\0' */
14618   u8 eType;                           /* Allocation type code */
14619   int iForeGuard;                     /* Guard word for sanity */
14620 };
14621
14622 /*
14623 ** Guard words
14624 */
14625 #define FOREGUARD 0x80F5E153
14626 #define REARGUARD 0xE4676B53
14627
14628 /*
14629 ** Number of malloc size increments to track.
14630 */
14631 #define NCSIZE  1000
14632
14633 /*
14634 ** All of the static variables used by this module are collected
14635 ** into a single structure named "mem".  This is to keep the
14636 ** static variables organized and to reduce namespace pollution
14637 ** when this module is combined with other in the amalgamation.
14638 */
14639 static struct {
14640   
14641   /*
14642   ** Mutex to control access to the memory allocation subsystem.
14643   */
14644   sqlite3_mutex *mutex;
14645
14646   /*
14647   ** Head and tail of a linked list of all outstanding allocations
14648   */
14649   struct MemBlockHdr *pFirst;
14650   struct MemBlockHdr *pLast;
14651   
14652   /*
14653   ** The number of levels of backtrace to save in new allocations.
14654   */
14655   int nBacktrace;
14656   void (*xBacktrace)(int, int, void **);
14657
14658   /*
14659   ** Title text to insert in front of each block
14660   */
14661   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14662   char zTitle[100];  /* The title text */
14663
14664   /* 
14665   ** sqlite3MallocDisallow() increments the following counter.
14666   ** sqlite3MallocAllow() decrements it.
14667   */
14668   int disallow; /* Do not allow memory allocation */
14669
14670   /*
14671   ** Gather statistics on the sizes of memory allocations.
14672   ** nAlloc[i] is the number of allocation attempts of i*8
14673   ** bytes.  i==NCSIZE is the number of allocation attempts for
14674   ** sizes more than NCSIZE*8 bytes.
14675   */
14676   int nAlloc[NCSIZE];      /* Total number of allocations */
14677   int nCurrent[NCSIZE];    /* Current number of allocations */
14678   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14679
14680 } mem;
14681
14682
14683 /*
14684 ** Adjust memory usage statistics
14685 */
14686 static void adjustStats(int iSize, int increment){
14687   int i = ROUND8(iSize)/8;
14688   if( i>NCSIZE-1 ){
14689     i = NCSIZE - 1;
14690   }
14691   if( increment>0 ){
14692     mem.nAlloc[i]++;
14693     mem.nCurrent[i]++;
14694     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14695       mem.mxCurrent[i] = mem.nCurrent[i];
14696     }
14697   }else{
14698     mem.nCurrent[i]--;
14699     assert( mem.nCurrent[i]>=0 );
14700   }
14701 }
14702
14703 /*
14704 ** Given an allocation, find the MemBlockHdr for that allocation.
14705 **
14706 ** This routine checks the guards at either end of the allocation and
14707 ** if they are incorrect it asserts.
14708 */
14709 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14710   struct MemBlockHdr *p;
14711   int *pInt;
14712   u8 *pU8;
14713   int nReserve;
14714
14715   p = (struct MemBlockHdr*)pAllocation;
14716   p--;
14717   assert( p->iForeGuard==(int)FOREGUARD );
14718   nReserve = ROUND8(p->iSize);
14719   pInt = (int*)pAllocation;
14720   pU8 = (u8*)pAllocation;
14721   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14722   /* This checks any of the "extra" bytes allocated due
14723   ** to rounding up to an 8 byte boundary to ensure 
14724   ** they haven't been overwritten.
14725   */
14726   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14727   return p;
14728 }
14729
14730 /*
14731 ** Return the number of bytes currently allocated at address p.
14732 */
14733 static int sqlite3MemSize(void *p){
14734   struct MemBlockHdr *pHdr;
14735   if( !p ){
14736     return 0;
14737   }
14738   pHdr = sqlite3MemsysGetHeader(p);
14739   return pHdr->iSize;
14740 }
14741
14742 /*
14743 ** Initialize the memory allocation subsystem.
14744 */
14745 static int sqlite3MemInit(void *NotUsed){
14746   UNUSED_PARAMETER(NotUsed);
14747   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14748   if( !sqlite3GlobalConfig.bMemstat ){
14749     /* If memory status is enabled, then the malloc.c wrapper will already
14750     ** hold the STATIC_MEM mutex when the routines here are invoked. */
14751     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14752   }
14753   return SQLITE_OK;
14754 }
14755
14756 /*
14757 ** Deinitialize the memory allocation subsystem.
14758 */
14759 static void sqlite3MemShutdown(void *NotUsed){
14760   UNUSED_PARAMETER(NotUsed);
14761   mem.mutex = 0;
14762 }
14763
14764 /*
14765 ** Round up a request size to the next valid allocation size.
14766 */
14767 static int sqlite3MemRoundup(int n){
14768   return ROUND8(n);
14769 }
14770
14771 /*
14772 ** Fill a buffer with pseudo-random bytes.  This is used to preset
14773 ** the content of a new memory allocation to unpredictable values and
14774 ** to clear the content of a freed allocation to unpredictable values.
14775 */
14776 static void randomFill(char *pBuf, int nByte){
14777   unsigned int x, y, r;
14778   x = SQLITE_PTR_TO_INT(pBuf);
14779   y = nByte | 1;
14780   while( nByte >= 4 ){
14781     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14782     y = y*1103515245 + 12345;
14783     r = x ^ y;
14784     *(int*)pBuf = r;
14785     pBuf += 4;
14786     nByte -= 4;
14787   }
14788   while( nByte-- > 0 ){
14789     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14790     y = y*1103515245 + 12345;
14791     r = x ^ y;
14792     *(pBuf++) = r & 0xff;
14793   }
14794 }
14795
14796 /*
14797 ** Allocate nByte bytes of memory.
14798 */
14799 static void *sqlite3MemMalloc(int nByte){
14800   struct MemBlockHdr *pHdr;
14801   void **pBt;
14802   char *z;
14803   int *pInt;
14804   void *p = 0;
14805   int totalSize;
14806   int nReserve;
14807   sqlite3_mutex_enter(mem.mutex);
14808   assert( mem.disallow==0 );
14809   nReserve = ROUND8(nByte);
14810   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14811                mem.nBacktrace*sizeof(void*) + mem.nTitle;
14812   p = malloc(totalSize);
14813   if( p ){
14814     z = p;
14815     pBt = (void**)&z[mem.nTitle];
14816     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14817     pHdr->pNext = 0;
14818     pHdr->pPrev = mem.pLast;
14819     if( mem.pLast ){
14820       mem.pLast->pNext = pHdr;
14821     }else{
14822       mem.pFirst = pHdr;
14823     }
14824     mem.pLast = pHdr;
14825     pHdr->iForeGuard = FOREGUARD;
14826     pHdr->eType = MEMTYPE_HEAP;
14827     pHdr->nBacktraceSlots = mem.nBacktrace;
14828     pHdr->nTitle = mem.nTitle;
14829     if( mem.nBacktrace ){
14830       void *aAddr[40];
14831       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14832       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14833       assert(pBt[0]);
14834       if( mem.xBacktrace ){
14835         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14836       }
14837     }else{
14838       pHdr->nBacktrace = 0;
14839     }
14840     if( mem.nTitle ){
14841       memcpy(z, mem.zTitle, mem.nTitle);
14842     }
14843     pHdr->iSize = nByte;
14844     adjustStats(nByte, +1);
14845     pInt = (int*)&pHdr[1];
14846     pInt[nReserve/sizeof(int)] = REARGUARD;
14847     randomFill((char*)pInt, nByte);
14848     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14849     p = (void*)pInt;
14850   }
14851   sqlite3_mutex_leave(mem.mutex);
14852   return p; 
14853 }
14854
14855 /*
14856 ** Free memory.
14857 */
14858 static void sqlite3MemFree(void *pPrior){
14859   struct MemBlockHdr *pHdr;
14860   void **pBt;
14861   char *z;
14862   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14863        || mem.mutex!=0 );
14864   pHdr = sqlite3MemsysGetHeader(pPrior);
14865   pBt = (void**)pHdr;
14866   pBt -= pHdr->nBacktraceSlots;
14867   sqlite3_mutex_enter(mem.mutex);
14868   if( pHdr->pPrev ){
14869     assert( pHdr->pPrev->pNext==pHdr );
14870     pHdr->pPrev->pNext = pHdr->pNext;
14871   }else{
14872     assert( mem.pFirst==pHdr );
14873     mem.pFirst = pHdr->pNext;
14874   }
14875   if( pHdr->pNext ){
14876     assert( pHdr->pNext->pPrev==pHdr );
14877     pHdr->pNext->pPrev = pHdr->pPrev;
14878   }else{
14879     assert( mem.pLast==pHdr );
14880     mem.pLast = pHdr->pPrev;
14881   }
14882   z = (char*)pBt;
14883   z -= pHdr->nTitle;
14884   adjustStats(pHdr->iSize, -1);
14885   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14886                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14887   free(z);
14888   sqlite3_mutex_leave(mem.mutex);  
14889 }
14890
14891 /*
14892 ** Change the size of an existing memory allocation.
14893 **
14894 ** For this debugging implementation, we *always* make a copy of the
14895 ** allocation into a new place in memory.  In this way, if the 
14896 ** higher level code is using pointer to the old allocation, it is 
14897 ** much more likely to break and we are much more liking to find
14898 ** the error.
14899 */
14900 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14901   struct MemBlockHdr *pOldHdr;
14902   void *pNew;
14903   assert( mem.disallow==0 );
14904   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14905   pOldHdr = sqlite3MemsysGetHeader(pPrior);
14906   pNew = sqlite3MemMalloc(nByte);
14907   if( pNew ){
14908     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14909     if( nByte>pOldHdr->iSize ){
14910       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14911     }
14912     sqlite3MemFree(pPrior);
14913   }
14914   return pNew;
14915 }
14916
14917 /*
14918 ** Populate the low-level memory allocation function pointers in
14919 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14920 */
14921 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14922   static const sqlite3_mem_methods defaultMethods = {
14923      sqlite3MemMalloc,
14924      sqlite3MemFree,
14925      sqlite3MemRealloc,
14926      sqlite3MemSize,
14927      sqlite3MemRoundup,
14928      sqlite3MemInit,
14929      sqlite3MemShutdown,
14930      0
14931   };
14932   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14933 }
14934
14935 /*
14936 ** Set the "type" of an allocation.
14937 */
14938 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14939   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14940     struct MemBlockHdr *pHdr;
14941     pHdr = sqlite3MemsysGetHeader(p);
14942     assert( pHdr->iForeGuard==FOREGUARD );
14943     pHdr->eType = eType;
14944   }
14945 }
14946
14947 /*
14948 ** Return TRUE if the mask of type in eType matches the type of the
14949 ** allocation p.  Also return true if p==NULL.
14950 **
14951 ** This routine is designed for use within an assert() statement, to
14952 ** verify the type of an allocation.  For example:
14953 **
14954 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14955 */
14956 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14957   int rc = 1;
14958   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14959     struct MemBlockHdr *pHdr;
14960     pHdr = sqlite3MemsysGetHeader(p);
14961     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14962     if( (pHdr->eType&eType)==0 ){
14963       rc = 0;
14964     }
14965   }
14966   return rc;
14967 }
14968
14969 /*
14970 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14971 ** allocation p.  Also return true if p==NULL.
14972 **
14973 ** This routine is designed for use within an assert() statement, to
14974 ** verify the type of an allocation.  For example:
14975 **
14976 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14977 */
14978 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14979   int rc = 1;
14980   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14981     struct MemBlockHdr *pHdr;
14982     pHdr = sqlite3MemsysGetHeader(p);
14983     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14984     if( (pHdr->eType&eType)!=0 ){
14985       rc = 0;
14986     }
14987   }
14988   return rc;
14989 }
14990
14991 /*
14992 ** Set the number of backtrace levels kept for each allocation.
14993 ** A value of zero turns off backtracing.  The number is always rounded
14994 ** up to a multiple of 2.
14995 */
14996 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14997   if( depth<0 ){ depth = 0; }
14998   if( depth>20 ){ depth = 20; }
14999   depth = (depth+1)&0xfe;
15000   mem.nBacktrace = depth;
15001 }
15002
15003 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15004   mem.xBacktrace = xBacktrace;
15005 }
15006
15007 /*
15008 ** Set the title string for subsequent allocations.
15009 */
15010 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15011   unsigned int n = sqlite3Strlen30(zTitle) + 1;
15012   sqlite3_mutex_enter(mem.mutex);
15013   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15014   memcpy(mem.zTitle, zTitle, n);
15015   mem.zTitle[n] = 0;
15016   mem.nTitle = ROUND8(n);
15017   sqlite3_mutex_leave(mem.mutex);
15018 }
15019
15020 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15021   struct MemBlockHdr *pHdr;
15022   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15023     void **pBt = (void**)pHdr;
15024     pBt -= pHdr->nBacktraceSlots;
15025     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15026   }
15027 }
15028
15029 /*
15030 ** Open the file indicated and write a log of all unfreed memory 
15031 ** allocations into that log.
15032 */
15033 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15034   FILE *out;
15035   struct MemBlockHdr *pHdr;
15036   void **pBt;
15037   int i;
15038   out = fopen(zFilename, "w");
15039   if( out==0 ){
15040     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15041                     zFilename);
15042     return;
15043   }
15044   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15045     char *z = (char*)pHdr;
15046     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15047     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
15048             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15049     if( pHdr->nBacktrace ){
15050       fflush(out);
15051       pBt = (void**)pHdr;
15052       pBt -= pHdr->nBacktraceSlots;
15053       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15054       fprintf(out, "\n");
15055     }
15056   }
15057   fprintf(out, "COUNTS:\n");
15058   for(i=0; i<NCSIZE-1; i++){
15059     if( mem.nAlloc[i] ){
15060       fprintf(out, "   %5d: %10d %10d %10d\n", 
15061             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15062     }
15063   }
15064   if( mem.nAlloc[NCSIZE-1] ){
15065     fprintf(out, "   %5d: %10d %10d %10d\n",
15066              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15067              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15068   }
15069   fclose(out);
15070 }
15071
15072 /*
15073 ** Return the number of times sqlite3MemMalloc() has been called.
15074 */
15075 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15076   int i;
15077   int nTotal = 0;
15078   for(i=0; i<NCSIZE; i++){
15079     nTotal += mem.nAlloc[i];
15080   }
15081   return nTotal;
15082 }
15083
15084
15085 #endif /* SQLITE_MEMDEBUG */
15086
15087 /************** End of mem2.c ************************************************/
15088 /************** Begin file mem3.c ********************************************/
15089 /*
15090 ** 2007 October 14
15091 **
15092 ** The author disclaims copyright to this source code.  In place of
15093 ** a legal notice, here is a blessing:
15094 **
15095 **    May you do good and not evil.
15096 **    May you find forgiveness for yourself and forgive others.
15097 **    May you share freely, never taking more than you give.
15098 **
15099 *************************************************************************
15100 ** This file contains the C functions that implement a memory
15101 ** allocation subsystem for use by SQLite. 
15102 **
15103 ** This version of the memory allocation subsystem omits all
15104 ** use of malloc(). The SQLite user supplies a block of memory
15105 ** before calling sqlite3_initialize() from which allocations
15106 ** are made and returned by the xMalloc() and xRealloc() 
15107 ** implementations. Once sqlite3_initialize() has been called,
15108 ** the amount of memory available to SQLite is fixed and cannot
15109 ** be changed.
15110 **
15111 ** This version of the memory allocation subsystem is included
15112 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15113 */
15114
15115 /*
15116 ** This version of the memory allocator is only built into the library
15117 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15118 ** mean that the library will use a memory-pool by default, just that
15119 ** it is available. The mempool allocator is activated by calling
15120 ** sqlite3_config().
15121 */
15122 #ifdef SQLITE_ENABLE_MEMSYS3
15123
15124 /*
15125 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15126 */
15127 #define MX_SMALL 10
15128
15129
15130 /*
15131 ** Number of freelist hash slots
15132 */
15133 #define N_HASH  61
15134
15135 /*
15136 ** A memory allocation (also called a "chunk") consists of two or 
15137 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
15138 ** a header that is not returned to the user.
15139 **
15140 ** A chunk is two or more blocks that is either checked out or
15141 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
15142 ** size of the allocation in blocks if the allocation is free.
15143 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15144 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
15145 ** is true if the previous chunk is checked out and false if the
15146 ** previous chunk is free.  The u.hdr.prevSize field is the size of
15147 ** the previous chunk in blocks if the previous chunk is on the
15148 ** freelist. If the previous chunk is checked out, then
15149 ** u.hdr.prevSize can be part of the data for that chunk and should
15150 ** not be read or written.
15151 **
15152 ** We often identify a chunk by its index in mem3.aPool[].  When
15153 ** this is done, the chunk index refers to the second block of
15154 ** the chunk.  In this way, the first chunk has an index of 1.
15155 ** A chunk index of 0 means "no such chunk" and is the equivalent
15156 ** of a NULL pointer.
15157 **
15158 ** The second block of free chunks is of the form u.list.  The
15159 ** two fields form a double-linked list of chunks of related sizes.
15160 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
15161 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15162 **
15163 ** The second block of a chunk is user data if the chunk is checked 
15164 ** out.  If a chunk is checked out, the user data may extend into
15165 ** the u.hdr.prevSize value of the following chunk.
15166 */
15167 typedef struct Mem3Block Mem3Block;
15168 struct Mem3Block {
15169   union {
15170     struct {
15171       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15172       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15173     } hdr;
15174     struct {
15175       u32 next;       /* Index in mem3.aPool[] of next free chunk */
15176       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15177     } list;
15178   } u;
15179 };
15180
15181 /*
15182 ** All of the static variables used by this module are collected
15183 ** into a single structure named "mem3".  This is to keep the
15184 ** static variables organized and to reduce namespace pollution
15185 ** when this module is combined with other in the amalgamation.
15186 */
15187 static SQLITE_WSD struct Mem3Global {
15188   /*
15189   ** Memory available for allocation. nPool is the size of the array
15190   ** (in Mem3Blocks) pointed to by aPool less 2.
15191   */
15192   u32 nPool;
15193   Mem3Block *aPool;
15194
15195   /*
15196   ** True if we are evaluating an out-of-memory callback.
15197   */
15198   int alarmBusy;
15199   
15200   /*
15201   ** Mutex to control access to the memory allocation subsystem.
15202   */
15203   sqlite3_mutex *mutex;
15204   
15205   /*
15206   ** The minimum amount of free space that we have seen.
15207   */
15208   u32 mnMaster;
15209
15210   /*
15211   ** iMaster is the index of the master chunk.  Most new allocations
15212   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15213   ** of the current master.  iMaster is 0 if there is not master chunk.
15214   ** The master chunk is not in either the aiHash[] or aiSmall[].
15215   */
15216   u32 iMaster;
15217   u32 szMaster;
15218
15219   /*
15220   ** Array of lists of free blocks according to the block size 
15221   ** for smaller chunks, or a hash on the block size for larger
15222   ** chunks.
15223   */
15224   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15225   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15226 } mem3 = { 97535575 };
15227
15228 #define mem3 GLOBAL(struct Mem3Global, mem3)
15229
15230 /*
15231 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15232 ** on.  *pRoot is the list that i is a member of.
15233 */
15234 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15235   u32 next = mem3.aPool[i].u.list.next;
15236   u32 prev = mem3.aPool[i].u.list.prev;
15237   assert( sqlite3_mutex_held(mem3.mutex) );
15238   if( prev==0 ){
15239     *pRoot = next;
15240   }else{
15241     mem3.aPool[prev].u.list.next = next;
15242   }
15243   if( next ){
15244     mem3.aPool[next].u.list.prev = prev;
15245   }
15246   mem3.aPool[i].u.list.next = 0;
15247   mem3.aPool[i].u.list.prev = 0;
15248 }
15249
15250 /*
15251 ** Unlink the chunk at index i from 
15252 ** whatever list is currently a member of.
15253 */
15254 static void memsys3Unlink(u32 i){
15255   u32 size, hash;
15256   assert( sqlite3_mutex_held(mem3.mutex) );
15257   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15258   assert( i>=1 );
15259   size = mem3.aPool[i-1].u.hdr.size4x/4;
15260   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15261   assert( size>=2 );
15262   if( size <= MX_SMALL ){
15263     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15264   }else{
15265     hash = size % N_HASH;
15266     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15267   }
15268 }
15269
15270 /*
15271 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15272 ** at *pRoot.
15273 */
15274 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15275   assert( sqlite3_mutex_held(mem3.mutex) );
15276   mem3.aPool[i].u.list.next = *pRoot;
15277   mem3.aPool[i].u.list.prev = 0;
15278   if( *pRoot ){
15279     mem3.aPool[*pRoot].u.list.prev = i;
15280   }
15281   *pRoot = i;
15282 }
15283
15284 /*
15285 ** Link the chunk at index i into either the appropriate
15286 ** small chunk list, or into the large chunk hash table.
15287 */
15288 static void memsys3Link(u32 i){
15289   u32 size, hash;
15290   assert( sqlite3_mutex_held(mem3.mutex) );
15291   assert( i>=1 );
15292   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15293   size = mem3.aPool[i-1].u.hdr.size4x/4;
15294   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15295   assert( size>=2 );
15296   if( size <= MX_SMALL ){
15297     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15298   }else{
15299     hash = size % N_HASH;
15300     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15301   }
15302 }
15303
15304 /*
15305 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15306 ** will already be held (obtained by code in malloc.c) if
15307 ** sqlite3GlobalConfig.bMemStat is true.
15308 */
15309 static void memsys3Enter(void){
15310   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15311     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15312   }
15313   sqlite3_mutex_enter(mem3.mutex);
15314 }
15315 static void memsys3Leave(void){
15316   sqlite3_mutex_leave(mem3.mutex);
15317 }
15318
15319 /*
15320 ** Called when we are unable to satisfy an allocation of nBytes.
15321 */
15322 static void memsys3OutOfMemory(int nByte){
15323   if( !mem3.alarmBusy ){
15324     mem3.alarmBusy = 1;
15325     assert( sqlite3_mutex_held(mem3.mutex) );
15326     sqlite3_mutex_leave(mem3.mutex);
15327     sqlite3_release_memory(nByte);
15328     sqlite3_mutex_enter(mem3.mutex);
15329     mem3.alarmBusy = 0;
15330   }
15331 }
15332
15333
15334 /*
15335 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15336 ** size parameters for check-out and return a pointer to the 
15337 ** user portion of the chunk.
15338 */
15339 static void *memsys3Checkout(u32 i, u32 nBlock){
15340   u32 x;
15341   assert( sqlite3_mutex_held(mem3.mutex) );
15342   assert( i>=1 );
15343   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15344   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15345   x = mem3.aPool[i-1].u.hdr.size4x;
15346   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15347   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15348   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15349   return &mem3.aPool[i];
15350 }
15351
15352 /*
15353 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15354 ** Return a pointer to the new allocation.  Or, if the master chunk
15355 ** is not large enough, return 0.
15356 */
15357 static void *memsys3FromMaster(u32 nBlock){
15358   assert( sqlite3_mutex_held(mem3.mutex) );
15359   assert( mem3.szMaster>=nBlock );
15360   if( nBlock>=mem3.szMaster-1 ){
15361     /* Use the entire master */
15362     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15363     mem3.iMaster = 0;
15364     mem3.szMaster = 0;
15365     mem3.mnMaster = 0;
15366     return p;
15367   }else{
15368     /* Split the master block.  Return the tail. */
15369     u32 newi, x;
15370     newi = mem3.iMaster + mem3.szMaster - nBlock;
15371     assert( newi > mem3.iMaster+1 );
15372     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15373     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15374     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15375     mem3.szMaster -= nBlock;
15376     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15377     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15378     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15379     if( mem3.szMaster < mem3.mnMaster ){
15380       mem3.mnMaster = mem3.szMaster;
15381     }
15382     return (void*)&mem3.aPool[newi];
15383   }
15384 }
15385
15386 /*
15387 ** *pRoot is the head of a list of free chunks of the same size
15388 ** or same size hash.  In other words, *pRoot is an entry in either
15389 ** mem3.aiSmall[] or mem3.aiHash[].  
15390 **
15391 ** This routine examines all entries on the given list and tries
15392 ** to coalesce each entries with adjacent free chunks.  
15393 **
15394 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15395 ** the current mem3.iMaster with the new larger chunk.  In order for
15396 ** this mem3.iMaster replacement to work, the master chunk must be
15397 ** linked into the hash tables.  That is not the normal state of
15398 ** affairs, of course.  The calling routine must link the master
15399 ** chunk before invoking this routine, then must unlink the (possibly
15400 ** changed) master chunk once this routine has finished.
15401 */
15402 static void memsys3Merge(u32 *pRoot){
15403   u32 iNext, prev, size, i, x;
15404
15405   assert( sqlite3_mutex_held(mem3.mutex) );
15406   for(i=*pRoot; i>0; i=iNext){
15407     iNext = mem3.aPool[i].u.list.next;
15408     size = mem3.aPool[i-1].u.hdr.size4x;
15409     assert( (size&1)==0 );
15410     if( (size&2)==0 ){
15411       memsys3UnlinkFromList(i, pRoot);
15412       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15413       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15414       if( prev==iNext ){
15415         iNext = mem3.aPool[prev].u.list.next;
15416       }
15417       memsys3Unlink(prev);
15418       size = i + size/4 - prev;
15419       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15420       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15421       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15422       memsys3Link(prev);
15423       i = prev;
15424     }else{
15425       size /= 4;
15426     }
15427     if( size>mem3.szMaster ){
15428       mem3.iMaster = i;
15429       mem3.szMaster = size;
15430     }
15431   }
15432 }
15433
15434 /*
15435 ** Return a block of memory of at least nBytes in size.
15436 ** Return NULL if unable.
15437 **
15438 ** This function assumes that the necessary mutexes, if any, are
15439 ** already held by the caller. Hence "Unsafe".
15440 */
15441 static void *memsys3MallocUnsafe(int nByte){
15442   u32 i;
15443   u32 nBlock;
15444   u32 toFree;
15445
15446   assert( sqlite3_mutex_held(mem3.mutex) );
15447   assert( sizeof(Mem3Block)==8 );
15448   if( nByte<=12 ){
15449     nBlock = 2;
15450   }else{
15451     nBlock = (nByte + 11)/8;
15452   }
15453   assert( nBlock>=2 );
15454
15455   /* STEP 1:
15456   ** Look for an entry of the correct size in either the small
15457   ** chunk table or in the large chunk hash table.  This is
15458   ** successful most of the time (about 9 times out of 10).
15459   */
15460   if( nBlock <= MX_SMALL ){
15461     i = mem3.aiSmall[nBlock-2];
15462     if( i>0 ){
15463       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15464       return memsys3Checkout(i, nBlock);
15465     }
15466   }else{
15467     int hash = nBlock % N_HASH;
15468     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15469       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15470         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15471         return memsys3Checkout(i, nBlock);
15472       }
15473     }
15474   }
15475
15476   /* STEP 2:
15477   ** Try to satisfy the allocation by carving a piece off of the end
15478   ** of the master chunk.  This step usually works if step 1 fails.
15479   */
15480   if( mem3.szMaster>=nBlock ){
15481     return memsys3FromMaster(nBlock);
15482   }
15483
15484
15485   /* STEP 3:  
15486   ** Loop through the entire memory pool.  Coalesce adjacent free
15487   ** chunks.  Recompute the master chunk as the largest free chunk.
15488   ** Then try again to satisfy the allocation by carving a piece off
15489   ** of the end of the master chunk.  This step happens very
15490   ** rarely (we hope!)
15491   */
15492   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15493     memsys3OutOfMemory(toFree);
15494     if( mem3.iMaster ){
15495       memsys3Link(mem3.iMaster);
15496       mem3.iMaster = 0;
15497       mem3.szMaster = 0;
15498     }
15499     for(i=0; i<N_HASH; i++){
15500       memsys3Merge(&mem3.aiHash[i]);
15501     }
15502     for(i=0; i<MX_SMALL-1; i++){
15503       memsys3Merge(&mem3.aiSmall[i]);
15504     }
15505     if( mem3.szMaster ){
15506       memsys3Unlink(mem3.iMaster);
15507       if( mem3.szMaster>=nBlock ){
15508         return memsys3FromMaster(nBlock);
15509       }
15510     }
15511   }
15512
15513   /* If none of the above worked, then we fail. */
15514   return 0;
15515 }
15516
15517 /*
15518 ** Free an outstanding memory allocation.
15519 **
15520 ** This function assumes that the necessary mutexes, if any, are
15521 ** already held by the caller. Hence "Unsafe".
15522 */
15523 void memsys3FreeUnsafe(void *pOld){
15524   Mem3Block *p = (Mem3Block*)pOld;
15525   int i;
15526   u32 size, x;
15527   assert( sqlite3_mutex_held(mem3.mutex) );
15528   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15529   i = p - mem3.aPool;
15530   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15531   size = mem3.aPool[i-1].u.hdr.size4x/4;
15532   assert( i+size<=mem3.nPool+1 );
15533   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15534   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15535   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15536   memsys3Link(i);
15537
15538   /* Try to expand the master using the newly freed chunk */
15539   if( mem3.iMaster ){
15540     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15541       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15542       mem3.iMaster -= size;
15543       mem3.szMaster += size;
15544       memsys3Unlink(mem3.iMaster);
15545       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15546       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15547       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15548     }
15549     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15550     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15551       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15552       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15553       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15554       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15555     }
15556   }
15557 }
15558
15559 /*
15560 ** Return the size of an outstanding allocation, in bytes.  The
15561 ** size returned omits the 8-byte header overhead.  This only
15562 ** works for chunks that are currently checked out.
15563 */
15564 static int memsys3Size(void *p){
15565   Mem3Block *pBlock;
15566   if( p==0 ) return 0;
15567   pBlock = (Mem3Block*)p;
15568   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15569   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15570 }
15571
15572 /*
15573 ** Round up a request size to the next valid allocation size.
15574 */
15575 static int memsys3Roundup(int n){
15576   if( n<=12 ){
15577     return 12;
15578   }else{
15579     return ((n+11)&~7) - 4;
15580   }
15581 }
15582
15583 /*
15584 ** Allocate nBytes of memory.
15585 */
15586 static void *memsys3Malloc(int nBytes){
15587   sqlite3_int64 *p;
15588   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15589   memsys3Enter();
15590   p = memsys3MallocUnsafe(nBytes);
15591   memsys3Leave();
15592   return (void*)p; 
15593 }
15594
15595 /*
15596 ** Free memory.
15597 */
15598 void memsys3Free(void *pPrior){
15599   assert( pPrior );
15600   memsys3Enter();
15601   memsys3FreeUnsafe(pPrior);
15602   memsys3Leave();
15603 }
15604
15605 /*
15606 ** Change the size of an existing memory allocation
15607 */
15608 void *memsys3Realloc(void *pPrior, int nBytes){
15609   int nOld;
15610   void *p;
15611   if( pPrior==0 ){
15612     return sqlite3_malloc(nBytes);
15613   }
15614   if( nBytes<=0 ){
15615     sqlite3_free(pPrior);
15616     return 0;
15617   }
15618   nOld = memsys3Size(pPrior);
15619   if( nBytes<=nOld && nBytes>=nOld-128 ){
15620     return pPrior;
15621   }
15622   memsys3Enter();
15623   p = memsys3MallocUnsafe(nBytes);
15624   if( p ){
15625     if( nOld<nBytes ){
15626       memcpy(p, pPrior, nOld);
15627     }else{
15628       memcpy(p, pPrior, nBytes);
15629     }
15630     memsys3FreeUnsafe(pPrior);
15631   }
15632   memsys3Leave();
15633   return p;
15634 }
15635
15636 /*
15637 ** Initialize this module.
15638 */
15639 static int memsys3Init(void *NotUsed){
15640   UNUSED_PARAMETER(NotUsed);
15641   if( !sqlite3GlobalConfig.pHeap ){
15642     return SQLITE_ERROR;
15643   }
15644
15645   /* Store a pointer to the memory block in global structure mem3. */
15646   assert( sizeof(Mem3Block)==8 );
15647   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15648   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15649
15650   /* Initialize the master block. */
15651   mem3.szMaster = mem3.nPool;
15652   mem3.mnMaster = mem3.szMaster;
15653   mem3.iMaster = 1;
15654   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15655   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15656   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15657
15658   return SQLITE_OK;
15659 }
15660
15661 /*
15662 ** Deinitialize this module.
15663 */
15664 static void memsys3Shutdown(void *NotUsed){
15665   UNUSED_PARAMETER(NotUsed);
15666   mem3.mutex = 0;
15667   return;
15668 }
15669
15670
15671
15672 /*
15673 ** Open the file indicated and write a log of all unfreed memory 
15674 ** allocations into that log.
15675 */
15676 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15677 #ifdef SQLITE_DEBUG
15678   FILE *out;
15679   u32 i, j;
15680   u32 size;
15681   if( zFilename==0 || zFilename[0]==0 ){
15682     out = stdout;
15683   }else{
15684     out = fopen(zFilename, "w");
15685     if( out==0 ){
15686       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15687                       zFilename);
15688       return;
15689     }
15690   }
15691   memsys3Enter();
15692   fprintf(out, "CHUNKS:\n");
15693   for(i=1; i<=mem3.nPool; i+=size/4){
15694     size = mem3.aPool[i-1].u.hdr.size4x;
15695     if( size/4<=1 ){
15696       fprintf(out, "%p size error\n", &mem3.aPool[i]);
15697       assert( 0 );
15698       break;
15699     }
15700     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15701       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15702       assert( 0 );
15703       break;
15704     }
15705     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15706       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15707       assert( 0 );
15708       break;
15709     }
15710     if( size&1 ){
15711       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15712     }else{
15713       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15714                   i==mem3.iMaster ? " **master**" : "");
15715     }
15716   }
15717   for(i=0; i<MX_SMALL-1; i++){
15718     if( mem3.aiSmall[i]==0 ) continue;
15719     fprintf(out, "small(%2d):", i);
15720     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15721       fprintf(out, " %p(%d)", &mem3.aPool[j],
15722               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15723     }
15724     fprintf(out, "\n"); 
15725   }
15726   for(i=0; i<N_HASH; i++){
15727     if( mem3.aiHash[i]==0 ) continue;
15728     fprintf(out, "hash(%2d):", i);
15729     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15730       fprintf(out, " %p(%d)", &mem3.aPool[j],
15731               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15732     }
15733     fprintf(out, "\n"); 
15734   }
15735   fprintf(out, "master=%d\n", mem3.iMaster);
15736   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15737   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15738   sqlite3_mutex_leave(mem3.mutex);
15739   if( out==stdout ){
15740     fflush(stdout);
15741   }else{
15742     fclose(out);
15743   }
15744 #else
15745   UNUSED_PARAMETER(zFilename);
15746 #endif
15747 }
15748
15749 /*
15750 ** This routine is the only routine in this file with external 
15751 ** linkage.
15752 **
15753 ** Populate the low-level memory allocation function pointers in
15754 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15755 ** arguments specify the block of memory to manage.
15756 **
15757 ** This routine is only called by sqlite3_config(), and therefore
15758 ** is not required to be threadsafe (it is not).
15759 */
15760 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15761   static const sqlite3_mem_methods mempoolMethods = {
15762      memsys3Malloc,
15763      memsys3Free,
15764      memsys3Realloc,
15765      memsys3Size,
15766      memsys3Roundup,
15767      memsys3Init,
15768      memsys3Shutdown,
15769      0
15770   };
15771   return &mempoolMethods;
15772 }
15773
15774 #endif /* SQLITE_ENABLE_MEMSYS3 */
15775
15776 /************** End of mem3.c ************************************************/
15777 /************** Begin file mem5.c ********************************************/
15778 /*
15779 ** 2007 October 14
15780 **
15781 ** The author disclaims copyright to this source code.  In place of
15782 ** a legal notice, here is a blessing:
15783 **
15784 **    May you do good and not evil.
15785 **    May you find forgiveness for yourself and forgive others.
15786 **    May you share freely, never taking more than you give.
15787 **
15788 *************************************************************************
15789 ** This file contains the C functions that implement a memory
15790 ** allocation subsystem for use by SQLite. 
15791 **
15792 ** This version of the memory allocation subsystem omits all
15793 ** use of malloc(). The application gives SQLite a block of memory
15794 ** before calling sqlite3_initialize() from which allocations
15795 ** are made and returned by the xMalloc() and xRealloc() 
15796 ** implementations. Once sqlite3_initialize() has been called,
15797 ** the amount of memory available to SQLite is fixed and cannot
15798 ** be changed.
15799 **
15800 ** This version of the memory allocation subsystem is included
15801 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15802 **
15803 ** This memory allocator uses the following algorithm:
15804 **
15805 **   1.  All memory allocations sizes are rounded up to a power of 2.
15806 **
15807 **   2.  If two adjacent free blocks are the halves of a larger block,
15808 **       then the two blocks are coalesed into the single larger block.
15809 **
15810 **   3.  New memory is allocated from the first available free block.
15811 **
15812 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15813 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15814 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15815 ** 
15816 ** Let n be the size of the largest allocation divided by the minimum
15817 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
15818 ** be the maximum amount of memory ever outstanding at one time.  Let
15819 ** N be the total amount of memory available for allocation.  Robson
15820 ** proved that this memory allocator will never breakdown due to 
15821 ** fragmentation as long as the following constraint holds:
15822 **
15823 **      N >=  M*(1 + log2(n)/2) - n + 1
15824 **
15825 ** The sqlite3_status() logic tracks the maximum values of n and M so
15826 ** that an application can, at any time, verify this constraint.
15827 */
15828
15829 /*
15830 ** This version of the memory allocator is used only when 
15831 ** SQLITE_ENABLE_MEMSYS5 is defined.
15832 */
15833 #ifdef SQLITE_ENABLE_MEMSYS5
15834
15835 /*
15836 ** A minimum allocation is an instance of the following structure.
15837 ** Larger allocations are an array of these structures where the
15838 ** size of the array is a power of 2.
15839 **
15840 ** The size of this object must be a power of two.  That fact is
15841 ** verified in memsys5Init().
15842 */
15843 typedef struct Mem5Link Mem5Link;
15844 struct Mem5Link {
15845   int next;       /* Index of next free chunk */
15846   int prev;       /* Index of previous free chunk */
15847 };
15848
15849 /*
15850 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15851 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15852 ** it is not actually possible to reach this limit.
15853 */
15854 #define LOGMAX 30
15855
15856 /*
15857 ** Masks used for mem5.aCtrl[] elements.
15858 */
15859 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15860 #define CTRL_FREE     0x20    /* True if not checked out */
15861
15862 /*
15863 ** All of the static variables used by this module are collected
15864 ** into a single structure named "mem5".  This is to keep the
15865 ** static variables organized and to reduce namespace pollution
15866 ** when this module is combined with other in the amalgamation.
15867 */
15868 static SQLITE_WSD struct Mem5Global {
15869   /*
15870   ** Memory available for allocation
15871   */
15872   int szAtom;      /* Smallest possible allocation in bytes */
15873   int nBlock;      /* Number of szAtom sized blocks in zPool */
15874   u8 *zPool;       /* Memory available to be allocated */
15875   
15876   /*
15877   ** Mutex to control access to the memory allocation subsystem.
15878   */
15879   sqlite3_mutex *mutex;
15880
15881   /*
15882   ** Performance statistics
15883   */
15884   u64 nAlloc;         /* Total number of calls to malloc */
15885   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15886   u64 totalExcess;    /* Total internal fragmentation */
15887   u32 currentOut;     /* Current checkout, including internal fragmentation */
15888   u32 currentCount;   /* Current number of distinct checkouts */
15889   u32 maxOut;         /* Maximum instantaneous currentOut */
15890   u32 maxCount;       /* Maximum instantaneous currentCount */
15891   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15892   
15893   /*
15894   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15895   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15896   ** and so forth.
15897   */
15898   int aiFreelist[LOGMAX+1];
15899
15900   /*
15901   ** Space for tracking which blocks are checked out and the size
15902   ** of each block.  One byte per block.
15903   */
15904   u8 *aCtrl;
15905
15906 } mem5;
15907
15908 /*
15909 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15910 */
15911 #define mem5 GLOBAL(struct Mem5Global, mem5)
15912
15913 /*
15914 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15915 ** structures, return a pointer to the idx-th such lik.
15916 */
15917 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15918
15919 /*
15920 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15921 ** on.  It should be found on mem5.aiFreelist[iLogsize].
15922 */
15923 static void memsys5Unlink(int i, int iLogsize){
15924   int next, prev;
15925   assert( i>=0 && i<mem5.nBlock );
15926   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15927   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15928
15929   next = MEM5LINK(i)->next;
15930   prev = MEM5LINK(i)->prev;
15931   if( prev<0 ){
15932     mem5.aiFreelist[iLogsize] = next;
15933   }else{
15934     MEM5LINK(prev)->next = next;
15935   }
15936   if( next>=0 ){
15937     MEM5LINK(next)->prev = prev;
15938   }
15939 }
15940
15941 /*
15942 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15943 ** free list.
15944 */
15945 static void memsys5Link(int i, int iLogsize){
15946   int x;
15947   assert( sqlite3_mutex_held(mem5.mutex) );
15948   assert( i>=0 && i<mem5.nBlock );
15949   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15950   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15951
15952   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15953   MEM5LINK(i)->prev = -1;
15954   if( x>=0 ){
15955     assert( x<mem5.nBlock );
15956     MEM5LINK(x)->prev = i;
15957   }
15958   mem5.aiFreelist[iLogsize] = i;
15959 }
15960
15961 /*
15962 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15963 ** will already be held (obtained by code in malloc.c) if
15964 ** sqlite3GlobalConfig.bMemStat is true.
15965 */
15966 static void memsys5Enter(void){
15967   sqlite3_mutex_enter(mem5.mutex);
15968 }
15969 static void memsys5Leave(void){
15970   sqlite3_mutex_leave(mem5.mutex);
15971 }
15972
15973 /*
15974 ** Return the size of an outstanding allocation, in bytes.  The
15975 ** size returned omits the 8-byte header overhead.  This only
15976 ** works for chunks that are currently checked out.
15977 */
15978 static int memsys5Size(void *p){
15979   int iSize = 0;
15980   if( p ){
15981     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15982     assert( i>=0 && i<mem5.nBlock );
15983     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15984   }
15985   return iSize;
15986 }
15987
15988 /*
15989 ** Find the first entry on the freelist iLogsize.  Unlink that
15990 ** entry and return its index. 
15991 */
15992 static int memsys5UnlinkFirst(int iLogsize){
15993   int i;
15994   int iFirst;
15995
15996   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15997   i = iFirst = mem5.aiFreelist[iLogsize];
15998   assert( iFirst>=0 );
15999   while( i>0 ){
16000     if( i<iFirst ) iFirst = i;
16001     i = MEM5LINK(i)->next;
16002   }
16003   memsys5Unlink(iFirst, iLogsize);
16004   return iFirst;
16005 }
16006
16007 /*
16008 ** Return a block of memory of at least nBytes in size.
16009 ** Return NULL if unable.  Return NULL if nBytes==0.
16010 **
16011 ** The caller guarantees that nByte positive.
16012 **
16013 ** The caller has obtained a mutex prior to invoking this
16014 ** routine so there is never any chance that two or more
16015 ** threads can be in this routine at the same time.
16016 */
16017 static void *memsys5MallocUnsafe(int nByte){
16018   int i;           /* Index of a mem5.aPool[] slot */
16019   int iBin;        /* Index into mem5.aiFreelist[] */
16020   int iFullSz;     /* Size of allocation rounded up to power of 2 */
16021   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16022
16023   /* nByte must be a positive */
16024   assert( nByte>0 );
16025
16026   /* Keep track of the maximum allocation request.  Even unfulfilled
16027   ** requests are counted */
16028   if( (u32)nByte>mem5.maxRequest ){
16029     mem5.maxRequest = nByte;
16030   }
16031
16032   /* Abort if the requested allocation size is larger than the largest
16033   ** power of two that we can represent using 32-bit signed integers.
16034   */
16035   if( nByte > 0x40000000 ){
16036     return 0;
16037   }
16038
16039   /* Round nByte up to the next valid power of two */
16040   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16041
16042   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16043   ** block.  If not, then split a block of the next larger power of
16044   ** two in order to create a new free block of size iLogsize.
16045   */
16046   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16047   if( iBin>LOGMAX ){
16048     testcase( sqlite3GlobalConfig.xLog!=0 );
16049     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16050     return 0;
16051   }
16052   i = memsys5UnlinkFirst(iBin);
16053   while( iBin>iLogsize ){
16054     int newSize;
16055
16056     iBin--;
16057     newSize = 1 << iBin;
16058     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16059     memsys5Link(i+newSize, iBin);
16060   }
16061   mem5.aCtrl[i] = iLogsize;
16062
16063   /* Update allocator performance statistics. */
16064   mem5.nAlloc++;
16065   mem5.totalAlloc += iFullSz;
16066   mem5.totalExcess += iFullSz - nByte;
16067   mem5.currentCount++;
16068   mem5.currentOut += iFullSz;
16069   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16070   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16071
16072   /* Return a pointer to the allocated memory. */
16073   return (void*)&mem5.zPool[i*mem5.szAtom];
16074 }
16075
16076 /*
16077 ** Free an outstanding memory allocation.
16078 */
16079 static void memsys5FreeUnsafe(void *pOld){
16080   u32 size, iLogsize;
16081   int iBlock;
16082
16083   /* Set iBlock to the index of the block pointed to by pOld in 
16084   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16085   */
16086   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16087
16088   /* Check that the pointer pOld points to a valid, non-free block. */
16089   assert( iBlock>=0 && iBlock<mem5.nBlock );
16090   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16091   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16092
16093   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16094   size = 1<<iLogsize;
16095   assert( iBlock+size-1<(u32)mem5.nBlock );
16096
16097   mem5.aCtrl[iBlock] |= CTRL_FREE;
16098   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16099   assert( mem5.currentCount>0 );
16100   assert( mem5.currentOut>=(size*mem5.szAtom) );
16101   mem5.currentCount--;
16102   mem5.currentOut -= size*mem5.szAtom;
16103   assert( mem5.currentOut>0 || mem5.currentCount==0 );
16104   assert( mem5.currentCount>0 || mem5.currentOut==0 );
16105
16106   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16107   while( ALWAYS(iLogsize<LOGMAX) ){
16108     int iBuddy;
16109     if( (iBlock>>iLogsize) & 1 ){
16110       iBuddy = iBlock - size;
16111     }else{
16112       iBuddy = iBlock + size;
16113     }
16114     assert( iBuddy>=0 );
16115     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16116     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16117     memsys5Unlink(iBuddy, iLogsize);
16118     iLogsize++;
16119     if( iBuddy<iBlock ){
16120       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16121       mem5.aCtrl[iBlock] = 0;
16122       iBlock = iBuddy;
16123     }else{
16124       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16125       mem5.aCtrl[iBuddy] = 0;
16126     }
16127     size *= 2;
16128   }
16129   memsys5Link(iBlock, iLogsize);
16130 }
16131
16132 /*
16133 ** Allocate nBytes of memory
16134 */
16135 static void *memsys5Malloc(int nBytes){
16136   sqlite3_int64 *p = 0;
16137   if( nBytes>0 ){
16138     memsys5Enter();
16139     p = memsys5MallocUnsafe(nBytes);
16140     memsys5Leave();
16141   }
16142   return (void*)p; 
16143 }
16144
16145 /*
16146 ** Free memory.
16147 **
16148 ** The outer layer memory allocator prevents this routine from
16149 ** being called with pPrior==0.
16150 */
16151 static void memsys5Free(void *pPrior){
16152   assert( pPrior!=0 );
16153   memsys5Enter();
16154   memsys5FreeUnsafe(pPrior);
16155   memsys5Leave();  
16156 }
16157
16158 /*
16159 ** Change the size of an existing memory allocation.
16160 **
16161 ** The outer layer memory allocator prevents this routine from
16162 ** being called with pPrior==0.  
16163 **
16164 ** nBytes is always a value obtained from a prior call to
16165 ** memsys5Round().  Hence nBytes is always a non-negative power
16166 ** of two.  If nBytes==0 that means that an oversize allocation
16167 ** (an allocation larger than 0x40000000) was requested and this
16168 ** routine should return 0 without freeing pPrior.
16169 */
16170 static void *memsys5Realloc(void *pPrior, int nBytes){
16171   int nOld;
16172   void *p;
16173   assert( pPrior!=0 );
16174   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16175   assert( nBytes>=0 );
16176   if( nBytes==0 ){
16177     return 0;
16178   }
16179   nOld = memsys5Size(pPrior);
16180   if( nBytes<=nOld ){
16181     return pPrior;
16182   }
16183   memsys5Enter();
16184   p = memsys5MallocUnsafe(nBytes);
16185   if( p ){
16186     memcpy(p, pPrior, nOld);
16187     memsys5FreeUnsafe(pPrior);
16188   }
16189   memsys5Leave();
16190   return p;
16191 }
16192
16193 /*
16194 ** Round up a request size to the next valid allocation size.  If
16195 ** the allocation is too large to be handled by this allocation system,
16196 ** return 0.
16197 **
16198 ** All allocations must be a power of two and must be expressed by a
16199 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16200 ** or 1073741824 bytes.
16201 */
16202 static int memsys5Roundup(int n){
16203   int iFullSz;
16204   if( n > 0x40000000 ) return 0;
16205   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16206   return iFullSz;
16207 }
16208
16209 /*
16210 ** Return the ceiling of the logarithm base 2 of iValue.
16211 **
16212 ** Examples:   memsys5Log(1) -> 0
16213 **             memsys5Log(2) -> 1
16214 **             memsys5Log(4) -> 2
16215 **             memsys5Log(5) -> 3
16216 **             memsys5Log(8) -> 3
16217 **             memsys5Log(9) -> 4
16218 */
16219 static int memsys5Log(int iValue){
16220   int iLog;
16221   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16222   return iLog;
16223 }
16224
16225 /*
16226 ** Initialize the memory allocator.
16227 **
16228 ** This routine is not threadsafe.  The caller must be holding a mutex
16229 ** to prevent multiple threads from entering at the same time.
16230 */
16231 static int memsys5Init(void *NotUsed){
16232   int ii;            /* Loop counter */
16233   int nByte;         /* Number of bytes of memory available to this allocator */
16234   u8 *zByte;         /* Memory usable by this allocator */
16235   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16236   int iOffset;       /* An offset into mem5.aCtrl[] */
16237
16238   UNUSED_PARAMETER(NotUsed);
16239
16240   /* For the purposes of this routine, disable the mutex */
16241   mem5.mutex = 0;
16242
16243   /* The size of a Mem5Link object must be a power of two.  Verify that
16244   ** this is case.
16245   */
16246   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16247
16248   nByte = sqlite3GlobalConfig.nHeap;
16249   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16250   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16251
16252   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16253   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16254   mem5.szAtom = (1<<nMinLog);
16255   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16256     mem5.szAtom = mem5.szAtom << 1;
16257   }
16258
16259   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16260   mem5.zPool = zByte;
16261   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16262
16263   for(ii=0; ii<=LOGMAX; ii++){
16264     mem5.aiFreelist[ii] = -1;
16265   }
16266
16267   iOffset = 0;
16268   for(ii=LOGMAX; ii>=0; ii--){
16269     int nAlloc = (1<<ii);
16270     if( (iOffset+nAlloc)<=mem5.nBlock ){
16271       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16272       memsys5Link(iOffset, ii);
16273       iOffset += nAlloc;
16274     }
16275     assert((iOffset+nAlloc)>mem5.nBlock);
16276   }
16277
16278   /* If a mutex is required for normal operation, allocate one */
16279   if( sqlite3GlobalConfig.bMemstat==0 ){
16280     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16281   }
16282
16283   return SQLITE_OK;
16284 }
16285
16286 /*
16287 ** Deinitialize this module.
16288 */
16289 static void memsys5Shutdown(void *NotUsed){
16290   UNUSED_PARAMETER(NotUsed);
16291   mem5.mutex = 0;
16292   return;
16293 }
16294
16295 #ifdef SQLITE_TEST
16296 /*
16297 ** Open the file indicated and write a log of all unfreed memory 
16298 ** allocations into that log.
16299 */
16300 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16301   FILE *out;
16302   int i, j, n;
16303   int nMinLog;
16304
16305   if( zFilename==0 || zFilename[0]==0 ){
16306     out = stdout;
16307   }else{
16308     out = fopen(zFilename, "w");
16309     if( out==0 ){
16310       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16311                       zFilename);
16312       return;
16313     }
16314   }
16315   memsys5Enter();
16316   nMinLog = memsys5Log(mem5.szAtom);
16317   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16318     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16319     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16320   }
16321   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16322   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16323   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16324   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16325   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16326   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16327   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16328   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16329   memsys5Leave();
16330   if( out==stdout ){
16331     fflush(stdout);
16332   }else{
16333     fclose(out);
16334   }
16335 }
16336 #endif
16337
16338 /*
16339 ** This routine is the only routine in this file with external 
16340 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16341 ** struct populated with the memsys5 methods.
16342 */
16343 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16344   static const sqlite3_mem_methods memsys5Methods = {
16345      memsys5Malloc,
16346      memsys5Free,
16347      memsys5Realloc,
16348      memsys5Size,
16349      memsys5Roundup,
16350      memsys5Init,
16351      memsys5Shutdown,
16352      0
16353   };
16354   return &memsys5Methods;
16355 }
16356
16357 #endif /* SQLITE_ENABLE_MEMSYS5 */
16358
16359 /************** End of mem5.c ************************************************/
16360 /************** Begin file mutex.c *******************************************/
16361 /*
16362 ** 2007 August 14
16363 **
16364 ** The author disclaims copyright to this source code.  In place of
16365 ** a legal notice, here is a blessing:
16366 **
16367 **    May you do good and not evil.
16368 **    May you find forgiveness for yourself and forgive others.
16369 **    May you share freely, never taking more than you give.
16370 **
16371 *************************************************************************
16372 ** This file contains the C functions that implement mutexes.
16373 **
16374 ** This file contains code that is common across all mutex implementations.
16375 */
16376
16377 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16378 /*
16379 ** For debugging purposes, record when the mutex subsystem is initialized
16380 ** and uninitialized so that we can assert() if there is an attempt to
16381 ** allocate a mutex while the system is uninitialized.
16382 */
16383 static SQLITE_WSD int mutexIsInit = 0;
16384 #endif /* SQLITE_DEBUG */
16385
16386
16387 #ifndef SQLITE_MUTEX_OMIT
16388 /*
16389 ** Initialize the mutex system.
16390 */
16391 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16392   int rc = SQLITE_OK;
16393   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16394     /* If the xMutexAlloc method has not been set, then the user did not
16395     ** install a mutex implementation via sqlite3_config() prior to 
16396     ** sqlite3_initialize() being called. This block copies pointers to
16397     ** the default implementation into the sqlite3GlobalConfig structure.
16398     */
16399     sqlite3_mutex_methods const *pFrom;
16400     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16401
16402     if( sqlite3GlobalConfig.bCoreMutex ){
16403       pFrom = sqlite3DefaultMutex();
16404     }else{
16405       pFrom = sqlite3NoopMutex();
16406     }
16407     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16408     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16409            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16410     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16411   }
16412   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16413
16414 #ifdef SQLITE_DEBUG
16415   GLOBAL(int, mutexIsInit) = 1;
16416 #endif
16417
16418   return rc;
16419 }
16420
16421 /*
16422 ** Shutdown the mutex system. This call frees resources allocated by
16423 ** sqlite3MutexInit().
16424 */
16425 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16426   int rc = SQLITE_OK;
16427   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16428     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16429   }
16430
16431 #ifdef SQLITE_DEBUG
16432   GLOBAL(int, mutexIsInit) = 0;
16433 #endif
16434
16435   return rc;
16436 }
16437
16438 /*
16439 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16440 */
16441 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16442 #ifndef SQLITE_OMIT_AUTOINIT
16443   if( sqlite3_initialize() ) return 0;
16444 #endif
16445   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16446 }
16447
16448 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16449   if( !sqlite3GlobalConfig.bCoreMutex ){
16450     return 0;
16451   }
16452   assert( GLOBAL(int, mutexIsInit) );
16453   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16454 }
16455
16456 /*
16457 ** Free a dynamic mutex.
16458 */
16459 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16460   if( p ){
16461     sqlite3GlobalConfig.mutex.xMutexFree(p);
16462   }
16463 }
16464
16465 /*
16466 ** Obtain the mutex p. If some other thread already has the mutex, block
16467 ** until it can be obtained.
16468 */
16469 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16470   if( p ){
16471     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16472   }
16473 }
16474
16475 /*
16476 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16477 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16478 */
16479 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16480   int rc = SQLITE_OK;
16481   if( p ){
16482     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16483   }
16484   return rc;
16485 }
16486
16487 /*
16488 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16489 ** entered by the same thread.  The behavior is undefined if the mutex 
16490 ** is not currently entered. If a NULL pointer is passed as an argument
16491 ** this function is a no-op.
16492 */
16493 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16494   if( p ){
16495     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16496   }
16497 }
16498
16499 #ifndef NDEBUG
16500 /*
16501 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16502 ** intended for use inside assert() statements.
16503 */
16504 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16505   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16506 }
16507 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16508   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16509 }
16510 #endif
16511
16512 #endif /* SQLITE_MUTEX_OMIT */
16513
16514 /************** End of mutex.c ***********************************************/
16515 /************** Begin file mutex_noop.c **************************************/
16516 /*
16517 ** 2008 October 07
16518 **
16519 ** The author disclaims copyright to this source code.  In place of
16520 ** a legal notice, here is a blessing:
16521 **
16522 **    May you do good and not evil.
16523 **    May you find forgiveness for yourself and forgive others.
16524 **    May you share freely, never taking more than you give.
16525 **
16526 *************************************************************************
16527 ** This file contains the C functions that implement mutexes.
16528 **
16529 ** This implementation in this file does not provide any mutual
16530 ** exclusion and is thus suitable for use only in applications
16531 ** that use SQLite in a single thread.  The routines defined
16532 ** here are place-holders.  Applications can substitute working
16533 ** mutex routines at start-time using the
16534 **
16535 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16536 **
16537 ** interface.
16538 **
16539 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16540 ** that does error checking on mutexes to make sure they are being
16541 ** called correctly.
16542 */
16543
16544 #ifndef SQLITE_MUTEX_OMIT
16545
16546 #ifndef SQLITE_DEBUG
16547 /*
16548 ** Stub routines for all mutex methods.
16549 **
16550 ** This routines provide no mutual exclusion or error checking.
16551 */
16552 static int noopMutexInit(void){ return SQLITE_OK; }
16553 static int noopMutexEnd(void){ return SQLITE_OK; }
16554 static sqlite3_mutex *noopMutexAlloc(int id){ 
16555   UNUSED_PARAMETER(id);
16556   return (sqlite3_mutex*)8; 
16557 }
16558 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16559 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16560 static int noopMutexTry(sqlite3_mutex *p){
16561   UNUSED_PARAMETER(p);
16562   return SQLITE_OK;
16563 }
16564 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16565
16566 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16567   static const sqlite3_mutex_methods sMutex = {
16568     noopMutexInit,
16569     noopMutexEnd,
16570     noopMutexAlloc,
16571     noopMutexFree,
16572     noopMutexEnter,
16573     noopMutexTry,
16574     noopMutexLeave,
16575
16576     0,
16577     0,
16578   };
16579
16580   return &sMutex;
16581 }
16582 #endif /* !SQLITE_DEBUG */
16583
16584 #ifdef SQLITE_DEBUG
16585 /*
16586 ** In this implementation, error checking is provided for testing
16587 ** and debugging purposes.  The mutexes still do not provide any
16588 ** mutual exclusion.
16589 */
16590
16591 /*
16592 ** The mutex object
16593 */
16594 typedef struct sqlite3_debug_mutex {
16595   int id;     /* The mutex type */
16596   int cnt;    /* Number of entries without a matching leave */
16597 } sqlite3_debug_mutex;
16598
16599 /*
16600 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16601 ** intended for use inside assert() statements.
16602 */
16603 static int debugMutexHeld(sqlite3_mutex *pX){
16604   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16605   return p==0 || p->cnt>0;
16606 }
16607 static int debugMutexNotheld(sqlite3_mutex *pX){
16608   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16609   return p==0 || p->cnt==0;
16610 }
16611
16612 /*
16613 ** Initialize and deinitialize the mutex subsystem.
16614 */
16615 static int debugMutexInit(void){ return SQLITE_OK; }
16616 static int debugMutexEnd(void){ return SQLITE_OK; }
16617
16618 /*
16619 ** The sqlite3_mutex_alloc() routine allocates a new
16620 ** mutex and returns a pointer to it.  If it returns NULL
16621 ** that means that a mutex could not be allocated. 
16622 */
16623 static sqlite3_mutex *debugMutexAlloc(int id){
16624   static sqlite3_debug_mutex aStatic[6];
16625   sqlite3_debug_mutex *pNew = 0;
16626   switch( id ){
16627     case SQLITE_MUTEX_FAST:
16628     case SQLITE_MUTEX_RECURSIVE: {
16629       pNew = sqlite3Malloc(sizeof(*pNew));
16630       if( pNew ){
16631         pNew->id = id;
16632         pNew->cnt = 0;
16633       }
16634       break;
16635     }
16636     default: {
16637       assert( id-2 >= 0 );
16638       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16639       pNew = &aStatic[id-2];
16640       pNew->id = id;
16641       break;
16642     }
16643   }
16644   return (sqlite3_mutex*)pNew;
16645 }
16646
16647 /*
16648 ** This routine deallocates a previously allocated mutex.
16649 */
16650 static void debugMutexFree(sqlite3_mutex *pX){
16651   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16652   assert( p->cnt==0 );
16653   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16654   sqlite3_free(p);
16655 }
16656
16657 /*
16658 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16659 ** to enter a mutex.  If another thread is already within the mutex,
16660 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16661 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16662 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16663 ** be entered multiple times by the same thread.  In such cases the,
16664 ** mutex must be exited an equal number of times before another thread
16665 ** can enter.  If the same thread tries to enter any other kind of mutex
16666 ** more than once, the behavior is undefined.
16667 */
16668 static void debugMutexEnter(sqlite3_mutex *pX){
16669   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16670   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16671   p->cnt++;
16672 }
16673 static int debugMutexTry(sqlite3_mutex *pX){
16674   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16675   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16676   p->cnt++;
16677   return SQLITE_OK;
16678 }
16679
16680 /*
16681 ** The sqlite3_mutex_leave() routine exits a mutex that was
16682 ** previously entered by the same thread.  The behavior
16683 ** is undefined if the mutex is not currently entered or
16684 ** is not currently allocated.  SQLite will never do either.
16685 */
16686 static void debugMutexLeave(sqlite3_mutex *pX){
16687   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16688   assert( debugMutexHeld(pX) );
16689   p->cnt--;
16690   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16691 }
16692
16693 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16694   static const sqlite3_mutex_methods sMutex = {
16695     debugMutexInit,
16696     debugMutexEnd,
16697     debugMutexAlloc,
16698     debugMutexFree,
16699     debugMutexEnter,
16700     debugMutexTry,
16701     debugMutexLeave,
16702
16703     debugMutexHeld,
16704     debugMutexNotheld
16705   };
16706
16707   return &sMutex;
16708 }
16709 #endif /* SQLITE_DEBUG */
16710
16711 /*
16712 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16713 ** is used regardless of the run-time threadsafety setting.
16714 */
16715 #ifdef SQLITE_MUTEX_NOOP
16716 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16717   return sqlite3NoopMutex();
16718 }
16719 #endif /* SQLITE_MUTEX_NOOP */
16720 #endif /* SQLITE_MUTEX_OMIT */
16721
16722 /************** End of mutex_noop.c ******************************************/
16723 /************** Begin file mutex_os2.c ***************************************/
16724 /*
16725 ** 2007 August 28
16726 **
16727 ** The author disclaims copyright to this source code.  In place of
16728 ** a legal notice, here is a blessing:
16729 **
16730 **    May you do good and not evil.
16731 **    May you find forgiveness for yourself and forgive others.
16732 **    May you share freely, never taking more than you give.
16733 **
16734 *************************************************************************
16735 ** This file contains the C functions that implement mutexes for OS/2
16736 */
16737
16738 /*
16739 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16740 ** See the mutex.h file for details.
16741 */
16742 #ifdef SQLITE_MUTEX_OS2
16743
16744 /********************** OS/2 Mutex Implementation **********************
16745 **
16746 ** This implementation of mutexes is built using the OS/2 API.
16747 */
16748
16749 /*
16750 ** The mutex object
16751 ** Each recursive mutex is an instance of the following structure.
16752 */
16753 struct sqlite3_mutex {
16754   HMTX mutex;       /* Mutex controlling the lock */
16755   int  id;          /* Mutex type */
16756 #ifdef SQLITE_DEBUG
16757  int   trace;       /* True to trace changes */
16758 #endif
16759 };
16760
16761 #ifdef SQLITE_DEBUG
16762 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
16763 #else
16764 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
16765 #endif
16766
16767 /*
16768 ** Initialize and deinitialize the mutex subsystem.
16769 */
16770 static int os2MutexInit(void){ return SQLITE_OK; }
16771 static int os2MutexEnd(void){ return SQLITE_OK; }
16772
16773 /*
16774 ** The sqlite3_mutex_alloc() routine allocates a new
16775 ** mutex and returns a pointer to it.  If it returns NULL
16776 ** that means that a mutex could not be allocated. 
16777 ** SQLite will unwind its stack and return an error.  The argument
16778 ** to sqlite3_mutex_alloc() is one of these integer constants:
16779 **
16780 ** <ul>
16781 ** <li>  SQLITE_MUTEX_FAST
16782 ** <li>  SQLITE_MUTEX_RECURSIVE
16783 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16784 ** <li>  SQLITE_MUTEX_STATIC_MEM
16785 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16786 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16787 ** <li>  SQLITE_MUTEX_STATIC_LRU
16788 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16789 ** </ul>
16790 **
16791 ** The first two constants cause sqlite3_mutex_alloc() to create
16792 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16793 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16794 ** The mutex implementation does not need to make a distinction
16795 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16796 ** not want to.  But SQLite will only request a recursive mutex in
16797 ** cases where it really needs one.  If a faster non-recursive mutex
16798 ** implementation is available on the host platform, the mutex subsystem
16799 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16800 **
16801 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16802 ** a pointer to a static preexisting mutex.  Six static mutexes are
16803 ** used by the current version of SQLite.  Future versions of SQLite
16804 ** may add additional static mutexes.  Static mutexes are for internal
16805 ** use by SQLite only.  Applications that use SQLite mutexes should
16806 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16807 ** SQLITE_MUTEX_RECURSIVE.
16808 **
16809 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16810 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16811 ** returns a different mutex on every call.  But for the static
16812 ** mutex types, the same mutex is returned on every call that has
16813 ** the same type number.
16814 */
16815 static sqlite3_mutex *os2MutexAlloc(int iType){
16816   sqlite3_mutex *p = NULL;
16817   switch( iType ){
16818     case SQLITE_MUTEX_FAST:
16819     case SQLITE_MUTEX_RECURSIVE: {
16820       p = sqlite3MallocZero( sizeof(*p) );
16821       if( p ){
16822         p->id = iType;
16823         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16824           sqlite3_free( p );
16825           p = NULL;
16826         }
16827       }
16828       break;
16829     }
16830     default: {
16831       static volatile int isInit = 0;
16832       static sqlite3_mutex staticMutexes[6] = {
16833         SQLITE3_MUTEX_INITIALIZER,
16834         SQLITE3_MUTEX_INITIALIZER,
16835         SQLITE3_MUTEX_INITIALIZER,
16836         SQLITE3_MUTEX_INITIALIZER,
16837         SQLITE3_MUTEX_INITIALIZER,
16838         SQLITE3_MUTEX_INITIALIZER,
16839       };
16840       if ( !isInit ){
16841         APIRET rc;
16842         PTIB ptib;
16843         PPIB ppib;
16844         HMTX mutex;
16845         char name[32];
16846         DosGetInfoBlocks( &ptib, &ppib );
16847         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16848                           ppib->pib_ulpid );
16849         while( !isInit ){
16850           mutex = 0;
16851           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16852           if( rc == NO_ERROR ){
16853             unsigned int i;
16854             if( !isInit ){
16855               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16856                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16857               }
16858               isInit = 1;
16859             }
16860             DosCloseMutexSem( mutex );
16861           }else if( rc == ERROR_DUPLICATE_NAME ){
16862             DosSleep( 1 );
16863           }else{
16864             return p;
16865           }
16866         }
16867       }
16868       assert( iType-2 >= 0 );
16869       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16870       p = &staticMutexes[iType-2];
16871       p->id = iType;
16872       break;
16873     }
16874   }
16875   return p;
16876 }
16877
16878
16879 /*
16880 ** This routine deallocates a previously allocated mutex.
16881 ** SQLite is careful to deallocate every mutex that it allocates.
16882 */
16883 static void os2MutexFree(sqlite3_mutex *p){
16884 #ifdef SQLITE_DEBUG
16885   TID tid;
16886   PID pid;
16887   ULONG ulCount;
16888   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16889   assert( ulCount==0 );
16890   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16891 #endif
16892   DosCloseMutexSem( p->mutex );
16893   sqlite3_free( p );
16894 }
16895
16896 #ifdef SQLITE_DEBUG
16897 /*
16898 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16899 ** intended for use inside assert() statements.
16900 */
16901 static int os2MutexHeld(sqlite3_mutex *p){
16902   TID tid;
16903   PID pid;
16904   ULONG ulCount;
16905   PTIB ptib;
16906   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16907   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
16908     return 0;
16909   DosGetInfoBlocks(&ptib, NULL);
16910   return tid==ptib->tib_ptib2->tib2_ultid;
16911 }
16912 static int os2MutexNotheld(sqlite3_mutex *p){
16913   TID tid;
16914   PID pid;
16915   ULONG ulCount;
16916   PTIB ptib;
16917   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16918   if( ulCount==0 )
16919     return 1;
16920   DosGetInfoBlocks(&ptib, NULL);
16921   return tid!=ptib->tib_ptib2->tib2_ultid;
16922 }
16923 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
16924   TID   tid;
16925   PID   pid;
16926   ULONG ulCount;
16927   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16928   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
16929 }
16930 #endif
16931
16932 /*
16933 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16934 ** to enter a mutex.  If another thread is already within the mutex,
16935 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16936 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16937 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16938 ** be entered multiple times by the same thread.  In such cases the,
16939 ** mutex must be exited an equal number of times before another thread
16940 ** can enter.  If the same thread tries to enter any other kind of mutex
16941 ** more than once, the behavior is undefined.
16942 */
16943 static void os2MutexEnter(sqlite3_mutex *p){
16944   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16945   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16946 #ifdef SQLITE_DEBUG
16947   if( p->trace ) os2MutexTrace(p, "enter");
16948 #endif
16949 }
16950 static int os2MutexTry(sqlite3_mutex *p){
16951   int rc = SQLITE_BUSY;
16952   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16953   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
16954     rc = SQLITE_OK;
16955 #ifdef SQLITE_DEBUG
16956     if( p->trace ) os2MutexTrace(p, "try");
16957 #endif
16958   }
16959   return rc;
16960 }
16961
16962 /*
16963 ** The sqlite3_mutex_leave() routine exits a mutex that was
16964 ** previously entered by the same thread.  The behavior
16965 ** is undefined if the mutex is not currently entered or
16966 ** is not currently allocated.  SQLite will never do either.
16967 */
16968 static void os2MutexLeave(sqlite3_mutex *p){
16969   assert( os2MutexHeld(p) );
16970   DosReleaseMutexSem(p->mutex);
16971 #ifdef SQLITE_DEBUG
16972   if( p->trace ) os2MutexTrace(p, "leave");
16973 #endif
16974 }
16975
16976 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16977   static const sqlite3_mutex_methods sMutex = {
16978     os2MutexInit,
16979     os2MutexEnd,
16980     os2MutexAlloc,
16981     os2MutexFree,
16982     os2MutexEnter,
16983     os2MutexTry,
16984     os2MutexLeave,
16985 #ifdef SQLITE_DEBUG
16986     os2MutexHeld,
16987     os2MutexNotheld
16988 #else
16989     0,
16990     0
16991 #endif
16992   };
16993
16994   return &sMutex;
16995 }
16996 #endif /* SQLITE_MUTEX_OS2 */
16997
16998 /************** End of mutex_os2.c *******************************************/
16999 /************** Begin file mutex_unix.c **************************************/
17000 /*
17001 ** 2007 August 28
17002 **
17003 ** The author disclaims copyright to this source code.  In place of
17004 ** a legal notice, here is a blessing:
17005 **
17006 **    May you do good and not evil.
17007 **    May you find forgiveness for yourself and forgive others.
17008 **    May you share freely, never taking more than you give.
17009 **
17010 *************************************************************************
17011 ** This file contains the C functions that implement mutexes for pthreads
17012 */
17013
17014 /*
17015 ** The code in this file is only used if we are compiling threadsafe
17016 ** under unix with pthreads.
17017 **
17018 ** Note that this implementation requires a version of pthreads that
17019 ** supports recursive mutexes.
17020 */
17021 #ifdef SQLITE_MUTEX_PTHREADS
17022
17023 #include <pthread.h>
17024
17025 /*
17026 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17027 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17028 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17029 */
17030 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17031 # define SQLITE_MUTEX_NREF 1
17032 #else
17033 # define SQLITE_MUTEX_NREF 0
17034 #endif
17035
17036 /*
17037 ** Each recursive mutex is an instance of the following structure.
17038 */
17039 struct sqlite3_mutex {
17040   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17041 #if SQLITE_MUTEX_NREF
17042   int id;                    /* Mutex type */
17043   volatile int nRef;         /* Number of entrances */
17044   volatile pthread_t owner;  /* Thread that is within this mutex */
17045   int trace;                 /* True to trace changes */
17046 #endif
17047 };
17048 #if SQLITE_MUTEX_NREF
17049 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17050 #else
17051 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17052 #endif
17053
17054 /*
17055 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17056 ** intended for use only inside assert() statements.  On some platforms,
17057 ** there might be race conditions that can cause these routines to
17058 ** deliver incorrect results.  In particular, if pthread_equal() is
17059 ** not an atomic operation, then these routines might delivery
17060 ** incorrect results.  On most platforms, pthread_equal() is a 
17061 ** comparison of two integers and is therefore atomic.  But we are
17062 ** told that HPUX is not such a platform.  If so, then these routines
17063 ** will not always work correctly on HPUX.
17064 **
17065 ** On those platforms where pthread_equal() is not atomic, SQLite
17066 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17067 ** make sure no assert() statements are evaluated and hence these
17068 ** routines are never called.
17069 */
17070 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17071 static int pthreadMutexHeld(sqlite3_mutex *p){
17072   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17073 }
17074 static int pthreadMutexNotheld(sqlite3_mutex *p){
17075   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17076 }
17077 #endif
17078
17079 /*
17080 ** Initialize and deinitialize the mutex subsystem.
17081 */
17082 static int pthreadMutexInit(void){ return SQLITE_OK; }
17083 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17084
17085 /*
17086 ** The sqlite3_mutex_alloc() routine allocates a new
17087 ** mutex and returns a pointer to it.  If it returns NULL
17088 ** that means that a mutex could not be allocated.  SQLite
17089 ** will unwind its stack and return an error.  The argument
17090 ** to sqlite3_mutex_alloc() is one of these integer constants:
17091 **
17092 ** <ul>
17093 ** <li>  SQLITE_MUTEX_FAST
17094 ** <li>  SQLITE_MUTEX_RECURSIVE
17095 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17096 ** <li>  SQLITE_MUTEX_STATIC_MEM
17097 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17098 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17099 ** <li>  SQLITE_MUTEX_STATIC_LRU
17100 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17101 ** </ul>
17102 **
17103 ** The first two constants cause sqlite3_mutex_alloc() to create
17104 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17105 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17106 ** The mutex implementation does not need to make a distinction
17107 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17108 ** not want to.  But SQLite will only request a recursive mutex in
17109 ** cases where it really needs one.  If a faster non-recursive mutex
17110 ** implementation is available on the host platform, the mutex subsystem
17111 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17112 **
17113 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17114 ** a pointer to a static preexisting mutex.  Six static mutexes are
17115 ** used by the current version of SQLite.  Future versions of SQLite
17116 ** may add additional static mutexes.  Static mutexes are for internal
17117 ** use by SQLite only.  Applications that use SQLite mutexes should
17118 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17119 ** SQLITE_MUTEX_RECURSIVE.
17120 **
17121 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17122 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17123 ** returns a different mutex on every call.  But for the static 
17124 ** mutex types, the same mutex is returned on every call that has
17125 ** the same type number.
17126 */
17127 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17128   static sqlite3_mutex staticMutexes[] = {
17129     SQLITE3_MUTEX_INITIALIZER,
17130     SQLITE3_MUTEX_INITIALIZER,
17131     SQLITE3_MUTEX_INITIALIZER,
17132     SQLITE3_MUTEX_INITIALIZER,
17133     SQLITE3_MUTEX_INITIALIZER,
17134     SQLITE3_MUTEX_INITIALIZER
17135   };
17136   sqlite3_mutex *p;
17137   switch( iType ){
17138     case SQLITE_MUTEX_RECURSIVE: {
17139       p = sqlite3MallocZero( sizeof(*p) );
17140       if( p ){
17141 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17142         /* If recursive mutexes are not available, we will have to
17143         ** build our own.  See below. */
17144         pthread_mutex_init(&p->mutex, 0);
17145 #else
17146         /* Use a recursive mutex if it is available */
17147         pthread_mutexattr_t recursiveAttr;
17148         pthread_mutexattr_init(&recursiveAttr);
17149         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17150         pthread_mutex_init(&p->mutex, &recursiveAttr);
17151         pthread_mutexattr_destroy(&recursiveAttr);
17152 #endif
17153 #if SQLITE_MUTEX_NREF
17154         p->id = iType;
17155 #endif
17156       }
17157       break;
17158     }
17159     case SQLITE_MUTEX_FAST: {
17160       p = sqlite3MallocZero( sizeof(*p) );
17161       if( p ){
17162 #if SQLITE_MUTEX_NREF
17163         p->id = iType;
17164 #endif
17165         pthread_mutex_init(&p->mutex, 0);
17166       }
17167       break;
17168     }
17169     default: {
17170       assert( iType-2 >= 0 );
17171       assert( iType-2 < ArraySize(staticMutexes) );
17172       p = &staticMutexes[iType-2];
17173 #if SQLITE_MUTEX_NREF
17174       p->id = iType;
17175 #endif
17176       break;
17177     }
17178   }
17179   return p;
17180 }
17181
17182
17183 /*
17184 ** This routine deallocates a previously
17185 ** allocated mutex.  SQLite is careful to deallocate every
17186 ** mutex that it allocates.
17187 */
17188 static void pthreadMutexFree(sqlite3_mutex *p){
17189   assert( p->nRef==0 );
17190   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17191   pthread_mutex_destroy(&p->mutex);
17192   sqlite3_free(p);
17193 }
17194
17195 /*
17196 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17197 ** to enter a mutex.  If another thread is already within the mutex,
17198 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17199 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17200 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17201 ** be entered multiple times by the same thread.  In such cases the,
17202 ** mutex must be exited an equal number of times before another thread
17203 ** can enter.  If the same thread tries to enter any other kind of mutex
17204 ** more than once, the behavior is undefined.
17205 */
17206 static void pthreadMutexEnter(sqlite3_mutex *p){
17207   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17208
17209 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17210   /* If recursive mutexes are not available, then we have to grow
17211   ** our own.  This implementation assumes that pthread_equal()
17212   ** is atomic - that it cannot be deceived into thinking self
17213   ** and p->owner are equal if p->owner changes between two values
17214   ** that are not equal to self while the comparison is taking place.
17215   ** This implementation also assumes a coherent cache - that 
17216   ** separate processes cannot read different values from the same
17217   ** address at the same time.  If either of these two conditions
17218   ** are not met, then the mutexes will fail and problems will result.
17219   */
17220   {
17221     pthread_t self = pthread_self();
17222     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17223       p->nRef++;
17224     }else{
17225       pthread_mutex_lock(&p->mutex);
17226       assert( p->nRef==0 );
17227       p->owner = self;
17228       p->nRef = 1;
17229     }
17230   }
17231 #else
17232   /* Use the built-in recursive mutexes if they are available.
17233   */
17234   pthread_mutex_lock(&p->mutex);
17235 #if SQLITE_MUTEX_NREF
17236   assert( p->nRef>0 || p->owner==0 );
17237   p->owner = pthread_self();
17238   p->nRef++;
17239 #endif
17240 #endif
17241
17242 #ifdef SQLITE_DEBUG
17243   if( p->trace ){
17244     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17245   }
17246 #endif
17247 }
17248 static int pthreadMutexTry(sqlite3_mutex *p){
17249   int rc;
17250   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17251
17252 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17253   /* If recursive mutexes are not available, then we have to grow
17254   ** our own.  This implementation assumes that pthread_equal()
17255   ** is atomic - that it cannot be deceived into thinking self
17256   ** and p->owner are equal if p->owner changes between two values
17257   ** that are not equal to self while the comparison is taking place.
17258   ** This implementation also assumes a coherent cache - that 
17259   ** separate processes cannot read different values from the same
17260   ** address at the same time.  If either of these two conditions
17261   ** are not met, then the mutexes will fail and problems will result.
17262   */
17263   {
17264     pthread_t self = pthread_self();
17265     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17266       p->nRef++;
17267       rc = SQLITE_OK;
17268     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17269       assert( p->nRef==0 );
17270       p->owner = self;
17271       p->nRef = 1;
17272       rc = SQLITE_OK;
17273     }else{
17274       rc = SQLITE_BUSY;
17275     }
17276   }
17277 #else
17278   /* Use the built-in recursive mutexes if they are available.
17279   */
17280   if( pthread_mutex_trylock(&p->mutex)==0 ){
17281 #if SQLITE_MUTEX_NREF
17282     p->owner = pthread_self();
17283     p->nRef++;
17284 #endif
17285     rc = SQLITE_OK;
17286   }else{
17287     rc = SQLITE_BUSY;
17288   }
17289 #endif
17290
17291 #ifdef SQLITE_DEBUG
17292   if( rc==SQLITE_OK && p->trace ){
17293     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17294   }
17295 #endif
17296   return rc;
17297 }
17298
17299 /*
17300 ** The sqlite3_mutex_leave() routine exits a mutex that was
17301 ** previously entered by the same thread.  The behavior
17302 ** is undefined if the mutex is not currently entered or
17303 ** is not currently allocated.  SQLite will never do either.
17304 */
17305 static void pthreadMutexLeave(sqlite3_mutex *p){
17306   assert( pthreadMutexHeld(p) );
17307 #if SQLITE_MUTEX_NREF
17308   p->nRef--;
17309   if( p->nRef==0 ) p->owner = 0;
17310 #endif
17311   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17312
17313 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17314   if( p->nRef==0 ){
17315     pthread_mutex_unlock(&p->mutex);
17316   }
17317 #else
17318   pthread_mutex_unlock(&p->mutex);
17319 #endif
17320
17321 #ifdef SQLITE_DEBUG
17322   if( p->trace ){
17323     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17324   }
17325 #endif
17326 }
17327
17328 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17329   static const sqlite3_mutex_methods sMutex = {
17330     pthreadMutexInit,
17331     pthreadMutexEnd,
17332     pthreadMutexAlloc,
17333     pthreadMutexFree,
17334     pthreadMutexEnter,
17335     pthreadMutexTry,
17336     pthreadMutexLeave,
17337 #ifdef SQLITE_DEBUG
17338     pthreadMutexHeld,
17339     pthreadMutexNotheld
17340 #else
17341     0,
17342     0
17343 #endif
17344   };
17345
17346   return &sMutex;
17347 }
17348
17349 #endif /* SQLITE_MUTEX_PTHREAD */
17350
17351 /************** End of mutex_unix.c ******************************************/
17352 /************** Begin file mutex_w32.c ***************************************/
17353 /*
17354 ** 2007 August 14
17355 **
17356 ** The author disclaims copyright to this source code.  In place of
17357 ** a legal notice, here is a blessing:
17358 **
17359 **    May you do good and not evil.
17360 **    May you find forgiveness for yourself and forgive others.
17361 **    May you share freely, never taking more than you give.
17362 **
17363 *************************************************************************
17364 ** This file contains the C functions that implement mutexes for win32
17365 */
17366
17367 /*
17368 ** The code in this file is only used if we are compiling multithreaded
17369 ** on a win32 system.
17370 */
17371 #ifdef SQLITE_MUTEX_W32
17372
17373 /*
17374 ** Each recursive mutex is an instance of the following structure.
17375 */
17376 struct sqlite3_mutex {
17377   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17378   int id;                    /* Mutex type */
17379 #ifdef SQLITE_DEBUG
17380   volatile int nRef;         /* Number of enterances */
17381   volatile DWORD owner;      /* Thread holding this mutex */
17382   int trace;                 /* True to trace changes */
17383 #endif
17384 };
17385 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17386 #ifdef SQLITE_DEBUG
17387 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17388 #else
17389 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17390 #endif
17391
17392 /*
17393 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17394 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17395 **
17396 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17397 ** the LockFileEx() API.  But we can still statically link against that
17398 ** API as long as we don't call it win running Win95/98/ME.  A call to
17399 ** this routine is used to determine if the host is Win95/98/ME or
17400 ** WinNT/2K/XP so that we will know whether or not we can safely call
17401 ** the LockFileEx() API.
17402 **
17403 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17404 ** which is only available if your application was compiled with 
17405 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17406 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17407 ** this out as well.
17408 */
17409 #if 0
17410 #if SQLITE_OS_WINCE
17411 # define mutexIsNT()  (1)
17412 #else
17413   static int mutexIsNT(void){
17414     static int osType = 0;
17415     if( osType==0 ){
17416       OSVERSIONINFO sInfo;
17417       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17418       GetVersionEx(&sInfo);
17419       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17420     }
17421     return osType==2;
17422   }
17423 #endif /* SQLITE_OS_WINCE */
17424 #endif
17425
17426 #ifdef SQLITE_DEBUG
17427 /*
17428 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17429 ** intended for use only inside assert() statements.
17430 */
17431 static int winMutexHeld(sqlite3_mutex *p){
17432   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17433 }
17434 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17435   return p->nRef==0 || p->owner!=tid;
17436 }
17437 static int winMutexNotheld(sqlite3_mutex *p){
17438   DWORD tid = GetCurrentThreadId(); 
17439   return winMutexNotheld2(p, tid);
17440 }
17441 #endif
17442
17443
17444 /*
17445 ** Initialize and deinitialize the mutex subsystem.
17446 */
17447 static sqlite3_mutex winMutex_staticMutexes[6] = {
17448   SQLITE3_MUTEX_INITIALIZER,
17449   SQLITE3_MUTEX_INITIALIZER,
17450   SQLITE3_MUTEX_INITIALIZER,
17451   SQLITE3_MUTEX_INITIALIZER,
17452   SQLITE3_MUTEX_INITIALIZER,
17453   SQLITE3_MUTEX_INITIALIZER
17454 };
17455 static int winMutex_isInit = 0;
17456 /* As winMutexInit() and winMutexEnd() are called as part
17457 ** of the sqlite3_initialize and sqlite3_shutdown()
17458 ** processing, the "interlocked" magic is probably not
17459 ** strictly necessary.
17460 */
17461 static long winMutex_lock = 0;
17462
17463 static int winMutexInit(void){ 
17464   /* The first to increment to 1 does actual initialization */
17465   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17466     int i;
17467     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17468       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17469     }
17470     winMutex_isInit = 1;
17471   }else{
17472     /* Someone else is in the process of initing the static mutexes */
17473     while( !winMutex_isInit ){
17474       Sleep(1);
17475     }
17476   }
17477   return SQLITE_OK; 
17478 }
17479
17480 static int winMutexEnd(void){ 
17481   /* The first to decrement to 0 does actual shutdown 
17482   ** (which should be the last to shutdown.) */
17483   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17484     if( winMutex_isInit==1 ){
17485       int i;
17486       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17487         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17488       }
17489       winMutex_isInit = 0;
17490     }
17491   }
17492   return SQLITE_OK; 
17493 }
17494
17495 /*
17496 ** The sqlite3_mutex_alloc() routine allocates a new
17497 ** mutex and returns a pointer to it.  If it returns NULL
17498 ** that means that a mutex could not be allocated.  SQLite
17499 ** will unwind its stack and return an error.  The argument
17500 ** to sqlite3_mutex_alloc() is one of these integer constants:
17501 **
17502 ** <ul>
17503 ** <li>  SQLITE_MUTEX_FAST
17504 ** <li>  SQLITE_MUTEX_RECURSIVE
17505 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17506 ** <li>  SQLITE_MUTEX_STATIC_MEM
17507 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17508 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17509 ** <li>  SQLITE_MUTEX_STATIC_LRU
17510 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17511 ** </ul>
17512 **
17513 ** The first two constants cause sqlite3_mutex_alloc() to create
17514 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17515 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17516 ** The mutex implementation does not need to make a distinction
17517 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17518 ** not want to.  But SQLite will only request a recursive mutex in
17519 ** cases where it really needs one.  If a faster non-recursive mutex
17520 ** implementation is available on the host platform, the mutex subsystem
17521 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17522 **
17523 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17524 ** a pointer to a static preexisting mutex.  Six static mutexes are
17525 ** used by the current version of SQLite.  Future versions of SQLite
17526 ** may add additional static mutexes.  Static mutexes are for internal
17527 ** use by SQLite only.  Applications that use SQLite mutexes should
17528 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17529 ** SQLITE_MUTEX_RECURSIVE.
17530 **
17531 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17532 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17533 ** returns a different mutex on every call.  But for the static 
17534 ** mutex types, the same mutex is returned on every call that has
17535 ** the same type number.
17536 */
17537 static sqlite3_mutex *winMutexAlloc(int iType){
17538   sqlite3_mutex *p;
17539
17540   switch( iType ){
17541     case SQLITE_MUTEX_FAST:
17542     case SQLITE_MUTEX_RECURSIVE: {
17543       p = sqlite3MallocZero( sizeof(*p) );
17544       if( p ){  
17545 #ifdef SQLITE_DEBUG
17546         p->id = iType;
17547 #endif
17548         InitializeCriticalSection(&p->mutex);
17549       }
17550       break;
17551     }
17552     default: {
17553       assert( winMutex_isInit==1 );
17554       assert( iType-2 >= 0 );
17555       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17556       p = &winMutex_staticMutexes[iType-2];
17557 #ifdef SQLITE_DEBUG
17558       p->id = iType;
17559 #endif
17560       break;
17561     }
17562   }
17563   return p;
17564 }
17565
17566
17567 /*
17568 ** This routine deallocates a previously
17569 ** allocated mutex.  SQLite is careful to deallocate every
17570 ** mutex that it allocates.
17571 */
17572 static void winMutexFree(sqlite3_mutex *p){
17573   assert( p );
17574   assert( p->nRef==0 && p->owner==0 );
17575   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17576   DeleteCriticalSection(&p->mutex);
17577   sqlite3_free(p);
17578 }
17579
17580 /*
17581 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17582 ** to enter a mutex.  If another thread is already within the mutex,
17583 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17584 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17585 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17586 ** be entered multiple times by the same thread.  In such cases the,
17587 ** mutex must be exited an equal number of times before another thread
17588 ** can enter.  If the same thread tries to enter any other kind of mutex
17589 ** more than once, the behavior is undefined.
17590 */
17591 static void winMutexEnter(sqlite3_mutex *p){
17592 #ifdef SQLITE_DEBUG
17593   DWORD tid = GetCurrentThreadId(); 
17594   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17595 #endif
17596   EnterCriticalSection(&p->mutex);
17597 #ifdef SQLITE_DEBUG
17598   assert( p->nRef>0 || p->owner==0 );
17599   p->owner = tid; 
17600   p->nRef++;
17601   if( p->trace ){
17602     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17603   }
17604 #endif
17605 }
17606 static int winMutexTry(sqlite3_mutex *p){
17607 #ifndef NDEBUG
17608   DWORD tid = GetCurrentThreadId(); 
17609 #endif
17610   int rc = SQLITE_BUSY;
17611   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17612   /*
17613   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17614   ** is used it is merely an optimization.  So it is OK for it to always
17615   ** fail.  
17616   **
17617   ** The TryEnterCriticalSection() interface is only available on WinNT.
17618   ** And some windows compilers complain if you try to use it without
17619   ** first doing some #defines that prevent SQLite from building on Win98.
17620   ** For that reason, we will omit this optimization for now.  See
17621   ** ticket #2685.
17622   */
17623 #if 0
17624   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17625     p->owner = tid;
17626     p->nRef++;
17627     rc = SQLITE_OK;
17628   }
17629 #else
17630   UNUSED_PARAMETER(p);
17631 #endif
17632 #ifdef SQLITE_DEBUG
17633   if( rc==SQLITE_OK && p->trace ){
17634     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17635   }
17636 #endif
17637   return rc;
17638 }
17639
17640 /*
17641 ** The sqlite3_mutex_leave() routine exits a mutex that was
17642 ** previously entered by the same thread.  The behavior
17643 ** is undefined if the mutex is not currently entered or
17644 ** is not currently allocated.  SQLite will never do either.
17645 */
17646 static void winMutexLeave(sqlite3_mutex *p){
17647 #ifndef NDEBUG
17648   DWORD tid = GetCurrentThreadId();
17649   assert( p->nRef>0 );
17650   assert( p->owner==tid );
17651   p->nRef--;
17652   if( p->nRef==0 ) p->owner = 0;
17653   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17654 #endif
17655   LeaveCriticalSection(&p->mutex);
17656 #ifdef SQLITE_DEBUG
17657   if( p->trace ){
17658     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17659   }
17660 #endif
17661 }
17662
17663 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17664   static const sqlite3_mutex_methods sMutex = {
17665     winMutexInit,
17666     winMutexEnd,
17667     winMutexAlloc,
17668     winMutexFree,
17669     winMutexEnter,
17670     winMutexTry,
17671     winMutexLeave,
17672 #ifdef SQLITE_DEBUG
17673     winMutexHeld,
17674     winMutexNotheld
17675 #else
17676     0,
17677     0
17678 #endif
17679   };
17680
17681   return &sMutex;
17682 }
17683 #endif /* SQLITE_MUTEX_W32 */
17684
17685 /************** End of mutex_w32.c *******************************************/
17686 /************** Begin file malloc.c ******************************************/
17687 /*
17688 ** 2001 September 15
17689 **
17690 ** The author disclaims copyright to this source code.  In place of
17691 ** a legal notice, here is a blessing:
17692 **
17693 **    May you do good and not evil.
17694 **    May you find forgiveness for yourself and forgive others.
17695 **    May you share freely, never taking more than you give.
17696 **
17697 *************************************************************************
17698 **
17699 ** Memory allocation functions used throughout sqlite.
17700 */
17701
17702 /*
17703 ** Attempt to release up to n bytes of non-essential memory currently
17704 ** held by SQLite. An example of non-essential memory is memory used to
17705 ** cache database pages that are not currently in use.
17706 */
17707 SQLITE_API int sqlite3_release_memory(int n){
17708 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17709   return sqlite3PcacheReleaseMemory(n);
17710 #else
17711   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17712   ** is a no-op returning zero if SQLite is not compiled with
17713   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17714   UNUSED_PARAMETER(n);
17715   return 0;
17716 #endif
17717 }
17718
17719 /*
17720 ** An instance of the following object records the location of
17721 ** each unused scratch buffer.
17722 */
17723 typedef struct ScratchFreeslot {
17724   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17725 } ScratchFreeslot;
17726
17727 /*
17728 ** State information local to the memory allocation subsystem.
17729 */
17730 static SQLITE_WSD struct Mem0Global {
17731   sqlite3_mutex *mutex;         /* Mutex to serialize access */
17732
17733   /*
17734   ** The alarm callback and its arguments.  The mem0.mutex lock will
17735   ** be held while the callback is running.  Recursive calls into
17736   ** the memory subsystem are allowed, but no new callbacks will be
17737   ** issued.
17738   */
17739   sqlite3_int64 alarmThreshold;
17740   void (*alarmCallback)(void*, sqlite3_int64,int);
17741   void *alarmArg;
17742
17743   /*
17744   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17745   ** (so that a range test can be used to determine if an allocation
17746   ** being freed came from pScratch) and a pointer to the list of
17747   ** unused scratch allocations.
17748   */
17749   void *pScratchEnd;
17750   ScratchFreeslot *pScratchFree;
17751   u32 nScratchFree;
17752
17753   /*
17754   ** True if heap is nearly "full" where "full" is defined by the
17755   ** sqlite3_soft_heap_limit() setting.
17756   */
17757   int nearlyFull;
17758 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17759
17760 #define mem0 GLOBAL(struct Mem0Global, mem0)
17761
17762 /*
17763 ** This routine runs when the memory allocator sees that the
17764 ** total memory allocation is about to exceed the soft heap
17765 ** limit.
17766 */
17767 static void softHeapLimitEnforcer(
17768   void *NotUsed, 
17769   sqlite3_int64 NotUsed2,
17770   int allocSize
17771 ){
17772   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17773   sqlite3_release_memory(allocSize);
17774 }
17775
17776 /*
17777 ** Change the alarm callback
17778 */
17779 static int sqlite3MemoryAlarm(
17780   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17781   void *pArg,
17782   sqlite3_int64 iThreshold
17783 ){
17784   int nUsed;
17785   sqlite3_mutex_enter(mem0.mutex);
17786   mem0.alarmCallback = xCallback;
17787   mem0.alarmArg = pArg;
17788   mem0.alarmThreshold = iThreshold;
17789   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17790   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17791   sqlite3_mutex_leave(mem0.mutex);
17792   return SQLITE_OK;
17793 }
17794
17795 #ifndef SQLITE_OMIT_DEPRECATED
17796 /*
17797 ** Deprecated external interface.  Internal/core SQLite code
17798 ** should call sqlite3MemoryAlarm.
17799 */
17800 SQLITE_API int sqlite3_memory_alarm(
17801   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17802   void *pArg,
17803   sqlite3_int64 iThreshold
17804 ){
17805   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17806 }
17807 #endif
17808
17809 /*
17810 ** Set the soft heap-size limit for the library. Passing a zero or 
17811 ** negative value indicates no limit.
17812 */
17813 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17814   sqlite3_int64 priorLimit;
17815   sqlite3_int64 excess;
17816 #ifndef SQLITE_OMIT_AUTOINIT
17817   sqlite3_initialize();
17818 #endif
17819   sqlite3_mutex_enter(mem0.mutex);
17820   priorLimit = mem0.alarmThreshold;
17821   sqlite3_mutex_leave(mem0.mutex);
17822   if( n<0 ) return priorLimit;
17823   if( n>0 ){
17824     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17825   }else{
17826     sqlite3MemoryAlarm(0, 0, 0);
17827   }
17828   excess = sqlite3_memory_used() - n;
17829   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17830   return priorLimit;
17831 }
17832 SQLITE_API void sqlite3_soft_heap_limit(int n){
17833   if( n<0 ) n = 0;
17834   sqlite3_soft_heap_limit64(n);
17835 }
17836
17837 /*
17838 ** Initialize the memory allocation subsystem.
17839 */
17840 SQLITE_PRIVATE int sqlite3MallocInit(void){
17841   if( sqlite3GlobalConfig.m.xMalloc==0 ){
17842     sqlite3MemSetDefault();
17843   }
17844   memset(&mem0, 0, sizeof(mem0));
17845   if( sqlite3GlobalConfig.bCoreMutex ){
17846     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17847   }
17848   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17849       && sqlite3GlobalConfig.nScratch>0 ){
17850     int i, n, sz;
17851     ScratchFreeslot *pSlot;
17852     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17853     sqlite3GlobalConfig.szScratch = sz;
17854     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17855     n = sqlite3GlobalConfig.nScratch;
17856     mem0.pScratchFree = pSlot;
17857     mem0.nScratchFree = n;
17858     for(i=0; i<n-1; i++){
17859       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17860       pSlot = pSlot->pNext;
17861     }
17862     pSlot->pNext = 0;
17863     mem0.pScratchEnd = (void*)&pSlot[1];
17864   }else{
17865     mem0.pScratchEnd = 0;
17866     sqlite3GlobalConfig.pScratch = 0;
17867     sqlite3GlobalConfig.szScratch = 0;
17868     sqlite3GlobalConfig.nScratch = 0;
17869   }
17870   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17871       || sqlite3GlobalConfig.nPage<1 ){
17872     sqlite3GlobalConfig.pPage = 0;
17873     sqlite3GlobalConfig.szPage = 0;
17874     sqlite3GlobalConfig.nPage = 0;
17875   }
17876   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17877 }
17878
17879 /*
17880 ** Return true if the heap is currently under memory pressure - in other
17881 ** words if the amount of heap used is close to the limit set by
17882 ** sqlite3_soft_heap_limit().
17883 */
17884 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17885   return mem0.nearlyFull;
17886 }
17887
17888 /*
17889 ** Deinitialize the memory allocation subsystem.
17890 */
17891 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17892   if( sqlite3GlobalConfig.m.xShutdown ){
17893     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17894   }
17895   memset(&mem0, 0, sizeof(mem0));
17896 }
17897
17898 /*
17899 ** Return the amount of memory currently checked out.
17900 */
17901 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17902   int n, mx;
17903   sqlite3_int64 res;
17904   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17905   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17906   return res;
17907 }
17908
17909 /*
17910 ** Return the maximum amount of memory that has ever been
17911 ** checked out since either the beginning of this process
17912 ** or since the most recent reset.
17913 */
17914 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17915   int n, mx;
17916   sqlite3_int64 res;
17917   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17918   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17919   return res;
17920 }
17921
17922 /*
17923 ** Trigger the alarm 
17924 */
17925 static void sqlite3MallocAlarm(int nByte){
17926   void (*xCallback)(void*,sqlite3_int64,int);
17927   sqlite3_int64 nowUsed;
17928   void *pArg;
17929   if( mem0.alarmCallback==0 ) return;
17930   xCallback = mem0.alarmCallback;
17931   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17932   pArg = mem0.alarmArg;
17933   mem0.alarmCallback = 0;
17934   sqlite3_mutex_leave(mem0.mutex);
17935   xCallback(pArg, nowUsed, nByte);
17936   sqlite3_mutex_enter(mem0.mutex);
17937   mem0.alarmCallback = xCallback;
17938   mem0.alarmArg = pArg;
17939 }
17940
17941 /*
17942 ** Do a memory allocation with statistics and alarms.  Assume the
17943 ** lock is already held.
17944 */
17945 static int mallocWithAlarm(int n, void **pp){
17946   int nFull;
17947   void *p;
17948   assert( sqlite3_mutex_held(mem0.mutex) );
17949   nFull = sqlite3GlobalConfig.m.xRoundup(n);
17950   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17951   if( mem0.alarmCallback!=0 ){
17952     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17953     if( nUsed+nFull >= mem0.alarmThreshold ){
17954       mem0.nearlyFull = 1;
17955       sqlite3MallocAlarm(nFull);
17956     }else{
17957       mem0.nearlyFull = 0;
17958     }
17959   }
17960   p = sqlite3GlobalConfig.m.xMalloc(nFull);
17961 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17962   if( p==0 && mem0.alarmCallback ){
17963     sqlite3MallocAlarm(nFull);
17964     p = sqlite3GlobalConfig.m.xMalloc(nFull);
17965   }
17966 #endif
17967   if( p ){
17968     nFull = sqlite3MallocSize(p);
17969     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17970     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17971   }
17972   *pp = p;
17973   return nFull;
17974 }
17975
17976 /*
17977 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
17978 ** assumes the memory subsystem has already been initialized.
17979 */
17980 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17981   void *p;
17982   if( n<=0               /* IMP: R-65312-04917 */ 
17983    || n>=0x7fffff00
17984   ){
17985     /* A memory allocation of a number of bytes which is near the maximum
17986     ** signed integer value might cause an integer overflow inside of the
17987     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17988     ** 255 bytes of overhead.  SQLite itself will never use anything near
17989     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17990     p = 0;
17991   }else if( sqlite3GlobalConfig.bMemstat ){
17992     sqlite3_mutex_enter(mem0.mutex);
17993     mallocWithAlarm(n, &p);
17994     sqlite3_mutex_leave(mem0.mutex);
17995   }else{
17996     p = sqlite3GlobalConfig.m.xMalloc(n);
17997   }
17998   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
17999   return p;
18000 }
18001
18002 /*
18003 ** This version of the memory allocation is for use by the application.
18004 ** First make sure the memory subsystem is initialized, then do the
18005 ** allocation.
18006 */
18007 SQLITE_API void *sqlite3_malloc(int n){
18008 #ifndef SQLITE_OMIT_AUTOINIT
18009   if( sqlite3_initialize() ) return 0;
18010 #endif
18011   return sqlite3Malloc(n);
18012 }
18013
18014 /*
18015 ** Each thread may only have a single outstanding allocation from
18016 ** xScratchMalloc().  We verify this constraint in the single-threaded
18017 ** case by setting scratchAllocOut to 1 when an allocation
18018 ** is outstanding clearing it when the allocation is freed.
18019 */
18020 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18021 static int scratchAllocOut = 0;
18022 #endif
18023
18024
18025 /*
18026 ** Allocate memory that is to be used and released right away.
18027 ** This routine is similar to alloca() in that it is not intended
18028 ** for situations where the memory might be held long-term.  This
18029 ** routine is intended to get memory to old large transient data
18030 ** structures that would not normally fit on the stack of an
18031 ** embedded processor.
18032 */
18033 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18034   void *p;
18035   assert( n>0 );
18036
18037   sqlite3_mutex_enter(mem0.mutex);
18038   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18039     p = mem0.pScratchFree;
18040     mem0.pScratchFree = mem0.pScratchFree->pNext;
18041     mem0.nScratchFree--;
18042     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18043     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18044     sqlite3_mutex_leave(mem0.mutex);
18045   }else{
18046     if( sqlite3GlobalConfig.bMemstat ){
18047       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18048       n = mallocWithAlarm(n, &p);
18049       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18050       sqlite3_mutex_leave(mem0.mutex);
18051     }else{
18052       sqlite3_mutex_leave(mem0.mutex);
18053       p = sqlite3GlobalConfig.m.xMalloc(n);
18054     }
18055     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18056   }
18057   assert( sqlite3_mutex_notheld(mem0.mutex) );
18058
18059
18060 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18061   /* Verify that no more than two scratch allocations per thread
18062   ** are outstanding at one time.  (This is only checked in the
18063   ** single-threaded case since checking in the multi-threaded case
18064   ** would be much more complicated.) */
18065   assert( scratchAllocOut<=1 );
18066   if( p ) scratchAllocOut++;
18067 #endif
18068
18069   return p;
18070 }
18071 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18072   if( p ){
18073
18074 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18075     /* Verify that no more than two scratch allocation per thread
18076     ** is outstanding at one time.  (This is only checked in the
18077     ** single-threaded case since checking in the multi-threaded case
18078     ** would be much more complicated.) */
18079     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18080     scratchAllocOut--;
18081 #endif
18082
18083     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18084       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18085       ScratchFreeslot *pSlot;
18086       pSlot = (ScratchFreeslot*)p;
18087       sqlite3_mutex_enter(mem0.mutex);
18088       pSlot->pNext = mem0.pScratchFree;
18089       mem0.pScratchFree = pSlot;
18090       mem0.nScratchFree++;
18091       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18092       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18093       sqlite3_mutex_leave(mem0.mutex);
18094     }else{
18095       /* Release memory back to the heap */
18096       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18097       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18098       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18099       if( sqlite3GlobalConfig.bMemstat ){
18100         int iSize = sqlite3MallocSize(p);
18101         sqlite3_mutex_enter(mem0.mutex);
18102         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18103         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18104         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18105         sqlite3GlobalConfig.m.xFree(p);
18106         sqlite3_mutex_leave(mem0.mutex);
18107       }else{
18108         sqlite3GlobalConfig.m.xFree(p);
18109       }
18110     }
18111   }
18112 }
18113
18114 /*
18115 ** TRUE if p is a lookaside memory allocation from db
18116 */
18117 #ifndef SQLITE_OMIT_LOOKASIDE
18118 static int isLookaside(sqlite3 *db, void *p){
18119   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18120 }
18121 #else
18122 #define isLookaside(A,B) 0
18123 #endif
18124
18125 /*
18126 ** Return the size of a memory allocation previously obtained from
18127 ** sqlite3Malloc() or sqlite3_malloc().
18128 */
18129 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18130   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18131   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18132   return sqlite3GlobalConfig.m.xSize(p);
18133 }
18134 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18135   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18136   if( db && isLookaside(db, p) ){
18137     return db->lookaside.sz;
18138   }else{
18139     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18140     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18141     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18142     return sqlite3GlobalConfig.m.xSize(p);
18143   }
18144 }
18145
18146 /*
18147 ** Free memory previously obtained from sqlite3Malloc().
18148 */
18149 SQLITE_API void sqlite3_free(void *p){
18150   if( p==0 ) return;  /* IMP: R-49053-54554 */
18151   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18152   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18153   if( sqlite3GlobalConfig.bMemstat ){
18154     sqlite3_mutex_enter(mem0.mutex);
18155     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18156     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18157     sqlite3GlobalConfig.m.xFree(p);
18158     sqlite3_mutex_leave(mem0.mutex);
18159   }else{
18160     sqlite3GlobalConfig.m.xFree(p);
18161   }
18162 }
18163
18164 /*
18165 ** Free memory that might be associated with a particular database
18166 ** connection.
18167 */
18168 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18169   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18170   if( db ){
18171     if( db->pnBytesFreed ){
18172       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18173       return;
18174     }
18175     if( isLookaside(db, p) ){
18176       LookasideSlot *pBuf = (LookasideSlot*)p;
18177       pBuf->pNext = db->lookaside.pFree;
18178       db->lookaside.pFree = pBuf;
18179       db->lookaside.nOut--;
18180       return;
18181     }
18182   }
18183   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18184   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18185   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18186   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18187   sqlite3_free(p);
18188 }
18189
18190 /*
18191 ** Change the size of an existing memory allocation
18192 */
18193 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18194   int nOld, nNew;
18195   void *pNew;
18196   if( pOld==0 ){
18197     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18198   }
18199   if( nBytes<=0 ){
18200     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18201     return 0;
18202   }
18203   if( nBytes>=0x7fffff00 ){
18204     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18205     return 0;
18206   }
18207   nOld = sqlite3MallocSize(pOld);
18208   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18209   ** argument to xRealloc is always a value returned by a prior call to
18210   ** xRoundup. */
18211   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18212   if( nOld==nNew ){
18213     pNew = pOld;
18214   }else if( sqlite3GlobalConfig.bMemstat ){
18215     sqlite3_mutex_enter(mem0.mutex);
18216     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18217     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
18218           mem0.alarmThreshold ){
18219       sqlite3MallocAlarm(nNew-nOld);
18220     }
18221     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18222     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18223     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18224     if( pNew==0 && mem0.alarmCallback ){
18225       sqlite3MallocAlarm(nBytes);
18226       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18227     }
18228     if( pNew ){
18229       nNew = sqlite3MallocSize(pNew);
18230       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18231     }
18232     sqlite3_mutex_leave(mem0.mutex);
18233   }else{
18234     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18235   }
18236   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18237   return pNew;
18238 }
18239
18240 /*
18241 ** The public interface to sqlite3Realloc.  Make sure that the memory
18242 ** subsystem is initialized prior to invoking sqliteRealloc.
18243 */
18244 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18245 #ifndef SQLITE_OMIT_AUTOINIT
18246   if( sqlite3_initialize() ) return 0;
18247 #endif
18248   return sqlite3Realloc(pOld, n);
18249 }
18250
18251
18252 /*
18253 ** Allocate and zero memory.
18254 */ 
18255 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18256   void *p = sqlite3Malloc(n);
18257   if( p ){
18258     memset(p, 0, n);
18259   }
18260   return p;
18261 }
18262
18263 /*
18264 ** Allocate and zero memory.  If the allocation fails, make
18265 ** the mallocFailed flag in the connection pointer.
18266 */
18267 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18268   void *p = sqlite3DbMallocRaw(db, n);
18269   if( p ){
18270     memset(p, 0, n);
18271   }
18272   return p;
18273 }
18274
18275 /*
18276 ** Allocate and zero memory.  If the allocation fails, make
18277 ** the mallocFailed flag in the connection pointer.
18278 **
18279 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18280 ** failure on the same database connection) then always return 0.
18281 ** Hence for a particular database connection, once malloc starts
18282 ** failing, it fails consistently until mallocFailed is reset.
18283 ** This is an important assumption.  There are many places in the
18284 ** code that do things like this:
18285 **
18286 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18287 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18288 **         if( b ) a[10] = 9;
18289 **
18290 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18291 ** that all prior mallocs (ex: "a") worked too.
18292 */
18293 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18294   void *p;
18295   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18296   assert( db==0 || db->pnBytesFreed==0 );
18297 #ifndef SQLITE_OMIT_LOOKASIDE
18298   if( db ){
18299     LookasideSlot *pBuf;
18300     if( db->mallocFailed ){
18301       return 0;
18302     }
18303     if( db->lookaside.bEnabled ){
18304       if( n>db->lookaside.sz ){
18305         db->lookaside.anStat[1]++;
18306       }else if( (pBuf = db->lookaside.pFree)==0 ){
18307         db->lookaside.anStat[2]++;
18308       }else{
18309         db->lookaside.pFree = pBuf->pNext;
18310         db->lookaside.nOut++;
18311         db->lookaside.anStat[0]++;
18312         if( db->lookaside.nOut>db->lookaside.mxOut ){
18313           db->lookaside.mxOut = db->lookaside.nOut;
18314         }
18315         return (void*)pBuf;
18316       }
18317     }
18318   }
18319 #else
18320   if( db && db->mallocFailed ){
18321     return 0;
18322   }
18323 #endif
18324   p = sqlite3Malloc(n);
18325   if( !p && db ){
18326     db->mallocFailed = 1;
18327   }
18328   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18329          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18330   return p;
18331 }
18332
18333 /*
18334 ** Resize the block of memory pointed to by p to n bytes. If the
18335 ** resize fails, set the mallocFailed flag in the connection object.
18336 */
18337 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18338   void *pNew = 0;
18339   assert( db!=0 );
18340   assert( sqlite3_mutex_held(db->mutex) );
18341   if( db->mallocFailed==0 ){
18342     if( p==0 ){
18343       return sqlite3DbMallocRaw(db, n);
18344     }
18345     if( isLookaside(db, p) ){
18346       if( n<=db->lookaside.sz ){
18347         return p;
18348       }
18349       pNew = sqlite3DbMallocRaw(db, n);
18350       if( pNew ){
18351         memcpy(pNew, p, db->lookaside.sz);
18352         sqlite3DbFree(db, p);
18353       }
18354     }else{
18355       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18356       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18357       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18358       pNew = sqlite3_realloc(p, n);
18359       if( !pNew ){
18360         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18361         db->mallocFailed = 1;
18362       }
18363       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18364             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18365     }
18366   }
18367   return pNew;
18368 }
18369
18370 /*
18371 ** Attempt to reallocate p.  If the reallocation fails, then free p
18372 ** and set the mallocFailed flag in the database connection.
18373 */
18374 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18375   void *pNew;
18376   pNew = sqlite3DbRealloc(db, p, n);
18377   if( !pNew ){
18378     sqlite3DbFree(db, p);
18379   }
18380   return pNew;
18381 }
18382
18383 /*
18384 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18385 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18386 ** is because when memory debugging is turned on, these two functions are 
18387 ** called via macros that record the current file and line number in the
18388 ** ThreadData structure.
18389 */
18390 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18391   char *zNew;
18392   size_t n;
18393   if( z==0 ){
18394     return 0;
18395   }
18396   n = sqlite3Strlen30(z) + 1;
18397   assert( (n&0x7fffffff)==n );
18398   zNew = sqlite3DbMallocRaw(db, (int)n);
18399   if( zNew ){
18400     memcpy(zNew, z, n);
18401   }
18402   return zNew;
18403 }
18404 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18405   char *zNew;
18406   if( z==0 ){
18407     return 0;
18408   }
18409   assert( (n&0x7fffffff)==n );
18410   zNew = sqlite3DbMallocRaw(db, n+1);
18411   if( zNew ){
18412     memcpy(zNew, z, n);
18413     zNew[n] = 0;
18414   }
18415   return zNew;
18416 }
18417
18418 /*
18419 ** Create a string from the zFromat argument and the va_list that follows.
18420 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18421 ** point to that string.
18422 */
18423 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18424   va_list ap;
18425   char *z;
18426
18427   va_start(ap, zFormat);
18428   z = sqlite3VMPrintf(db, zFormat, ap);
18429   va_end(ap);
18430   sqlite3DbFree(db, *pz);
18431   *pz = z;
18432 }
18433
18434
18435 /*
18436 ** This function must be called before exiting any API function (i.e. 
18437 ** returning control to the user) that has called sqlite3_malloc or
18438 ** sqlite3_realloc.
18439 **
18440 ** The returned value is normally a copy of the second argument to this
18441 ** function. However, if a malloc() failure has occurred since the previous
18442 ** invocation SQLITE_NOMEM is returned instead. 
18443 **
18444 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18445 ** then the connection error-code (the value returned by sqlite3_errcode())
18446 ** is set to SQLITE_NOMEM.
18447 */
18448 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18449   /* If the db handle is not NULL, then we must hold the connection handle
18450   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18451   ** is unsafe, as is the call to sqlite3Error().
18452   */
18453   assert( !db || sqlite3_mutex_held(db->mutex) );
18454   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18455     sqlite3Error(db, SQLITE_NOMEM, 0);
18456     db->mallocFailed = 0;
18457     rc = SQLITE_NOMEM;
18458   }
18459   return rc & (db ? db->errMask : 0xff);
18460 }
18461
18462 /************** End of malloc.c **********************************************/
18463 /************** Begin file printf.c ******************************************/
18464 /*
18465 ** The "printf" code that follows dates from the 1980's.  It is in
18466 ** the public domain.  The original comments are included here for
18467 ** completeness.  They are very out-of-date but might be useful as
18468 ** an historical reference.  Most of the "enhancements" have been backed
18469 ** out so that the functionality is now the same as standard printf().
18470 **
18471 **************************************************************************
18472 **
18473 ** The following modules is an enhanced replacement for the "printf" subroutines
18474 ** found in the standard C library.  The following enhancements are
18475 ** supported:
18476 **
18477 **      +  Additional functions.  The standard set of "printf" functions
18478 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18479 **         vsprintf.  This module adds the following:
18480 **
18481 **           *  snprintf -- Works like sprintf, but has an extra argument
18482 **                          which is the size of the buffer written to.
18483 **
18484 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18485 **                          obtained from malloc.
18486 **
18487 **           *  xprintf --  Calls a function to dispose of output.
18488 **
18489 **           *  nprintf --  No output, but returns the number of characters
18490 **                          that would have been output by printf.
18491 **
18492 **           *  A v- version (ex: vsnprintf) of every function is also
18493 **              supplied.
18494 **
18495 **      +  A few extensions to the formatting notation are supported:
18496 **
18497 **           *  The "=" flag (similar to "-") causes the output to be
18498 **              be centered in the appropriately sized field.
18499 **
18500 **           *  The %b field outputs an integer in binary notation.
18501 **
18502 **           *  The %c field now accepts a precision.  The character output
18503 **              is repeated by the number of times the precision specifies.
18504 **
18505 **           *  The %' field works like %c, but takes as its character the
18506 **              next character of the format string, instead of the next
18507 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18508 **              signs, the same as  printf("%.78c",'-').
18509 **
18510 **      +  When compiled using GCC on a SPARC, this version of printf is
18511 **         faster than the library printf for SUN OS 4.1.
18512 **
18513 **      +  All functions are fully reentrant.
18514 **
18515 */
18516
18517 /*
18518 ** Conversion types fall into various categories as defined by the
18519 ** following enumeration.
18520 */
18521 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18522 #define etFLOAT       2 /* Floating point.  %f */
18523 #define etEXP         3 /* Exponentional notation. %e and %E */
18524 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18525 #define etSIZE        5 /* Return number of characters processed so far. %n */
18526 #define etSTRING      6 /* Strings. %s */
18527 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18528 #define etPERCENT     8 /* Percent symbol. %% */
18529 #define etCHARX       9 /* Characters. %c */
18530 /* The rest are extensions, not normally found in printf() */
18531 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18532 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18533                           NULL pointers replaced by SQL NULL.  %Q */
18534 #define etTOKEN      12 /* a pointer to a Token structure */
18535 #define etSRCLIST    13 /* a pointer to a SrcList */
18536 #define etPOINTER    14 /* The %p conversion */
18537 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18538 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18539
18540 #define etINVALID     0 /* Any unrecognized conversion type */
18541
18542
18543 /*
18544 ** An "etByte" is an 8-bit unsigned value.
18545 */
18546 typedef unsigned char etByte;
18547
18548 /*
18549 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18550 ** by an instance of the following structure
18551 */
18552 typedef struct et_info {   /* Information about each format field */
18553   char fmttype;            /* The format field code letter */
18554   etByte base;             /* The base for radix conversion */
18555   etByte flags;            /* One or more of FLAG_ constants below */
18556   etByte type;             /* Conversion paradigm */
18557   etByte charset;          /* Offset into aDigits[] of the digits string */
18558   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18559 } et_info;
18560
18561 /*
18562 ** Allowed values for et_info.flags
18563 */
18564 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18565 #define FLAG_INTERN  2     /* True if for internal use only */
18566 #define FLAG_STRING  4     /* Allow infinity precision */
18567
18568
18569 /*
18570 ** The following table is searched linearly, so it is good to put the
18571 ** most frequently used conversion types first.
18572 */
18573 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18574 static const char aPrefix[] = "-x0\000X0";
18575 static const et_info fmtinfo[] = {
18576   {  'd', 10, 1, etRADIX,      0,  0 },
18577   {  's',  0, 4, etSTRING,     0,  0 },
18578   {  'g',  0, 1, etGENERIC,    30, 0 },
18579   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18580   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18581   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18582   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18583   {  'c',  0, 0, etCHARX,      0,  0 },
18584   {  'o',  8, 0, etRADIX,      0,  2 },
18585   {  'u', 10, 0, etRADIX,      0,  0 },
18586   {  'x', 16, 0, etRADIX,      16, 1 },
18587   {  'X', 16, 0, etRADIX,      0,  4 },
18588 #ifndef SQLITE_OMIT_FLOATING_POINT
18589   {  'f',  0, 1, etFLOAT,      0,  0 },
18590   {  'e',  0, 1, etEXP,        30, 0 },
18591   {  'E',  0, 1, etEXP,        14, 0 },
18592   {  'G',  0, 1, etGENERIC,    14, 0 },
18593 #endif
18594   {  'i', 10, 1, etRADIX,      0,  0 },
18595   {  'n',  0, 0, etSIZE,       0,  0 },
18596   {  '%',  0, 0, etPERCENT,    0,  0 },
18597   {  'p', 16, 0, etPOINTER,    0,  1 },
18598
18599 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18600 ** use only */
18601   {  'T',  0, 2, etTOKEN,      0,  0 },
18602   {  'S',  0, 2, etSRCLIST,    0,  0 },
18603   {  'r', 10, 3, etORDINAL,    0,  0 },
18604 };
18605
18606 /*
18607 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18608 ** conversions will work.
18609 */
18610 #ifndef SQLITE_OMIT_FLOATING_POINT
18611 /*
18612 ** "*val" is a double such that 0.1 <= *val < 10.0
18613 ** Return the ascii code for the leading digit of *val, then
18614 ** multiply "*val" by 10.0 to renormalize.
18615 **
18616 ** Example:
18617 **     input:     *val = 3.14159
18618 **     output:    *val = 1.4159    function return = '3'
18619 **
18620 ** The counter *cnt is incremented each time.  After counter exceeds
18621 ** 16 (the number of significant digits in a 64-bit float) '0' is
18622 ** always returned.
18623 */
18624 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18625   int digit;
18626   LONGDOUBLE_TYPE d;
18627   if( (*cnt)++ >= 16 ) return '0';
18628   digit = (int)*val;
18629   d = digit;
18630   digit += '0';
18631   *val = (*val - d)*10.0;
18632   return (char)digit;
18633 }
18634 #endif /* SQLITE_OMIT_FLOATING_POINT */
18635
18636 /*
18637 ** Append N space characters to the given string buffer.
18638 */
18639 static void appendSpace(StrAccum *pAccum, int N){
18640   static const char zSpaces[] = "                             ";
18641   while( N>=(int)sizeof(zSpaces)-1 ){
18642     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18643     N -= sizeof(zSpaces)-1;
18644   }
18645   if( N>0 ){
18646     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18647   }
18648 }
18649
18650 /*
18651 ** On machines with a small stack size, you can redefine the
18652 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18653 */
18654 #ifndef SQLITE_PRINT_BUF_SIZE
18655 # if defined(SQLITE_SMALL_STACK)
18656 #   define SQLITE_PRINT_BUF_SIZE 50
18657 # else
18658 #   define SQLITE_PRINT_BUF_SIZE 350
18659 # endif
18660 #endif
18661 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18662
18663 /*
18664 ** The root program.  All variations call this core.
18665 **
18666 ** INPUTS:
18667 **   func   This is a pointer to a function taking three arguments
18668 **            1. A pointer to anything.  Same as the "arg" parameter.
18669 **            2. A pointer to the list of characters to be output
18670 **               (Note, this list is NOT null terminated.)
18671 **            3. An integer number of characters to be output.
18672 **               (Note: This number might be zero.)
18673 **
18674 **   arg    This is the pointer to anything which will be passed as the
18675 **          first argument to "func".  Use it for whatever you like.
18676 **
18677 **   fmt    This is the format string, as in the usual print.
18678 **
18679 **   ap     This is a pointer to a list of arguments.  Same as in
18680 **          vfprint.
18681 **
18682 ** OUTPUTS:
18683 **          The return value is the total number of characters sent to
18684 **          the function "func".  Returns -1 on a error.
18685 **
18686 ** Note that the order in which automatic variables are declared below
18687 ** seems to make a big difference in determining how fast this beast
18688 ** will run.
18689 */
18690 SQLITE_PRIVATE void sqlite3VXPrintf(
18691   StrAccum *pAccum,                  /* Accumulate results here */
18692   int useExtended,                   /* Allow extended %-conversions */
18693   const char *fmt,                   /* Format string */
18694   va_list ap                         /* arguments */
18695 ){
18696   int c;                     /* Next character in the format string */
18697   char *bufpt;               /* Pointer to the conversion buffer */
18698   int precision;             /* Precision of the current field */
18699   int length;                /* Length of the field */
18700   int idx;                   /* A general purpose loop counter */
18701   int width;                 /* Width of the current field */
18702   etByte flag_leftjustify;   /* True if "-" flag is present */
18703   etByte flag_plussign;      /* True if "+" flag is present */
18704   etByte flag_blanksign;     /* True if " " flag is present */
18705   etByte flag_alternateform; /* True if "#" flag is present */
18706   etByte flag_altform2;      /* True if "!" flag is present */
18707   etByte flag_zeropad;       /* True if field width constant starts with zero */
18708   etByte flag_long;          /* True if "l" flag is present */
18709   etByte flag_longlong;      /* True if the "ll" flag is present */
18710   etByte done;               /* Loop termination flag */
18711   sqlite_uint64 longvalue;   /* Value for integer types */
18712   LONGDOUBLE_TYPE realvalue; /* Value for real types */
18713   const et_info *infop;      /* Pointer to the appropriate info structure */
18714   char buf[etBUFSIZE];       /* Conversion buffer */
18715   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18716   etByte xtype = 0;          /* Conversion paradigm */
18717   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18718 #ifndef SQLITE_OMIT_FLOATING_POINT
18719   int  exp, e2;              /* exponent of real numbers */
18720   double rounder;            /* Used for rounding floating point values */
18721   etByte flag_dp;            /* True if decimal point should be shown */
18722   etByte flag_rtz;           /* True if trailing zeros should be removed */
18723   etByte flag_exp;           /* True to force display of the exponent */
18724   int nsd;                   /* Number of significant digits returned */
18725 #endif
18726
18727   length = 0;
18728   bufpt = 0;
18729   for(; (c=(*fmt))!=0; ++fmt){
18730     if( c!='%' ){
18731       int amt;
18732       bufpt = (char *)fmt;
18733       amt = 1;
18734       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18735       sqlite3StrAccumAppend(pAccum, bufpt, amt);
18736       if( c==0 ) break;
18737     }
18738     if( (c=(*++fmt))==0 ){
18739       sqlite3StrAccumAppend(pAccum, "%", 1);
18740       break;
18741     }
18742     /* Find out what flags are present */
18743     flag_leftjustify = flag_plussign = flag_blanksign = 
18744      flag_alternateform = flag_altform2 = flag_zeropad = 0;
18745     done = 0;
18746     do{
18747       switch( c ){
18748         case '-':   flag_leftjustify = 1;     break;
18749         case '+':   flag_plussign = 1;        break;
18750         case ' ':   flag_blanksign = 1;       break;
18751         case '#':   flag_alternateform = 1;   break;
18752         case '!':   flag_altform2 = 1;        break;
18753         case '0':   flag_zeropad = 1;         break;
18754         default:    done = 1;                 break;
18755       }
18756     }while( !done && (c=(*++fmt))!=0 );
18757     /* Get the field width */
18758     width = 0;
18759     if( c=='*' ){
18760       width = va_arg(ap,int);
18761       if( width<0 ){
18762         flag_leftjustify = 1;
18763         width = -width;
18764       }
18765       c = *++fmt;
18766     }else{
18767       while( c>='0' && c<='9' ){
18768         width = width*10 + c - '0';
18769         c = *++fmt;
18770       }
18771     }
18772     if( width > etBUFSIZE-10 ){
18773       width = etBUFSIZE-10;
18774     }
18775     /* Get the precision */
18776     if( c=='.' ){
18777       precision = 0;
18778       c = *++fmt;
18779       if( c=='*' ){
18780         precision = va_arg(ap,int);
18781         if( precision<0 ) precision = -precision;
18782         c = *++fmt;
18783       }else{
18784         while( c>='0' && c<='9' ){
18785           precision = precision*10 + c - '0';
18786           c = *++fmt;
18787         }
18788       }
18789     }else{
18790       precision = -1;
18791     }
18792     /* Get the conversion type modifier */
18793     if( c=='l' ){
18794       flag_long = 1;
18795       c = *++fmt;
18796       if( c=='l' ){
18797         flag_longlong = 1;
18798         c = *++fmt;
18799       }else{
18800         flag_longlong = 0;
18801       }
18802     }else{
18803       flag_long = flag_longlong = 0;
18804     }
18805     /* Fetch the info entry for the field */
18806     infop = &fmtinfo[0];
18807     xtype = etINVALID;
18808     for(idx=0; idx<ArraySize(fmtinfo); idx++){
18809       if( c==fmtinfo[idx].fmttype ){
18810         infop = &fmtinfo[idx];
18811         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18812           xtype = infop->type;
18813         }else{
18814           return;
18815         }
18816         break;
18817       }
18818     }
18819     zExtra = 0;
18820
18821
18822     /* Limit the precision to prevent overflowing buf[] during conversion */
18823     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18824       precision = etBUFSIZE-40;
18825     }
18826
18827     /*
18828     ** At this point, variables are initialized as follows:
18829     **
18830     **   flag_alternateform          TRUE if a '#' is present.
18831     **   flag_altform2               TRUE if a '!' is present.
18832     **   flag_plussign               TRUE if a '+' is present.
18833     **   flag_leftjustify            TRUE if a '-' is present or if the
18834     **                               field width was negative.
18835     **   flag_zeropad                TRUE if the width began with 0.
18836     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18837     **                               the conversion character.
18838     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18839     **                               the conversion character.
18840     **   flag_blanksign              TRUE if a ' ' is present.
18841     **   width                       The specified field width.  This is
18842     **                               always non-negative.  Zero is the default.
18843     **   precision                   The specified precision.  The default
18844     **                               is -1.
18845     **   xtype                       The class of the conversion.
18846     **   infop                       Pointer to the appropriate info struct.
18847     */
18848     switch( xtype ){
18849       case etPOINTER:
18850         flag_longlong = sizeof(char*)==sizeof(i64);
18851         flag_long = sizeof(char*)==sizeof(long int);
18852         /* Fall through into the next case */
18853       case etORDINAL:
18854       case etRADIX:
18855         if( infop->flags & FLAG_SIGNED ){
18856           i64 v;
18857           if( flag_longlong ){
18858             v = va_arg(ap,i64);
18859           }else if( flag_long ){
18860             v = va_arg(ap,long int);
18861           }else{
18862             v = va_arg(ap,int);
18863           }
18864           if( v<0 ){
18865             if( v==SMALLEST_INT64 ){
18866               longvalue = ((u64)1)<<63;
18867             }else{
18868               longvalue = -v;
18869             }
18870             prefix = '-';
18871           }else{
18872             longvalue = v;
18873             if( flag_plussign )        prefix = '+';
18874             else if( flag_blanksign )  prefix = ' ';
18875             else                       prefix = 0;
18876           }
18877         }else{
18878           if( flag_longlong ){
18879             longvalue = va_arg(ap,u64);
18880           }else if( flag_long ){
18881             longvalue = va_arg(ap,unsigned long int);
18882           }else{
18883             longvalue = va_arg(ap,unsigned int);
18884           }
18885           prefix = 0;
18886         }
18887         if( longvalue==0 ) flag_alternateform = 0;
18888         if( flag_zeropad && precision<width-(prefix!=0) ){
18889           precision = width-(prefix!=0);
18890         }
18891         bufpt = &buf[etBUFSIZE-1];
18892         if( xtype==etORDINAL ){
18893           static const char zOrd[] = "thstndrd";
18894           int x = (int)(longvalue % 10);
18895           if( x>=4 || (longvalue/10)%10==1 ){
18896             x = 0;
18897           }
18898           buf[etBUFSIZE-3] = zOrd[x*2];
18899           buf[etBUFSIZE-2] = zOrd[x*2+1];
18900           bufpt -= 2;
18901         }
18902         {
18903           register const char *cset;      /* Use registers for speed */
18904           register int base;
18905           cset = &aDigits[infop->charset];
18906           base = infop->base;
18907           do{                                           /* Convert to ascii */
18908             *(--bufpt) = cset[longvalue%base];
18909             longvalue = longvalue/base;
18910           }while( longvalue>0 );
18911         }
18912         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18913         for(idx=precision-length; idx>0; idx--){
18914           *(--bufpt) = '0';                             /* Zero pad */
18915         }
18916         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18917         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18918           const char *pre;
18919           char x;
18920           pre = &aPrefix[infop->prefix];
18921           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18922         }
18923         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18924         break;
18925       case etFLOAT:
18926       case etEXP:
18927       case etGENERIC:
18928         realvalue = va_arg(ap,double);
18929 #ifdef SQLITE_OMIT_FLOATING_POINT
18930         length = 0;
18931 #else
18932         if( precision<0 ) precision = 6;         /* Set default precision */
18933         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18934         if( realvalue<0.0 ){
18935           realvalue = -realvalue;
18936           prefix = '-';
18937         }else{
18938           if( flag_plussign )          prefix = '+';
18939           else if( flag_blanksign )    prefix = ' ';
18940           else                         prefix = 0;
18941         }
18942         if( xtype==etGENERIC && precision>0 ) precision--;
18943 #if 0
18944         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18945         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18946 #else
18947         /* It makes more sense to use 0.5 */
18948         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18949 #endif
18950         if( xtype==etFLOAT ) realvalue += rounder;
18951         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18952         exp = 0;
18953         if( sqlite3IsNaN((double)realvalue) ){
18954           bufpt = "NaN";
18955           length = 3;
18956           break;
18957         }
18958         if( realvalue>0.0 ){
18959           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18960           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18961           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18962           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18963           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18964           if( exp>350 ){
18965             if( prefix=='-' ){
18966               bufpt = "-Inf";
18967             }else if( prefix=='+' ){
18968               bufpt = "+Inf";
18969             }else{
18970               bufpt = "Inf";
18971             }
18972             length = sqlite3Strlen30(bufpt);
18973             break;
18974           }
18975         }
18976         bufpt = buf;
18977         /*
18978         ** If the field type is etGENERIC, then convert to either etEXP
18979         ** or etFLOAT, as appropriate.
18980         */
18981         flag_exp = xtype==etEXP;
18982         if( xtype!=etFLOAT ){
18983           realvalue += rounder;
18984           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18985         }
18986         if( xtype==etGENERIC ){
18987           flag_rtz = !flag_alternateform;
18988           if( exp<-4 || exp>precision ){
18989             xtype = etEXP;
18990           }else{
18991             precision = precision - exp;
18992             xtype = etFLOAT;
18993           }
18994         }else{
18995           flag_rtz = 0;
18996         }
18997         if( xtype==etEXP ){
18998           e2 = 0;
18999         }else{
19000           e2 = exp;
19001         }
19002         nsd = 0;
19003         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19004         /* The sign in front of the number */
19005         if( prefix ){
19006           *(bufpt++) = prefix;
19007         }
19008         /* Digits prior to the decimal point */
19009         if( e2<0 ){
19010           *(bufpt++) = '0';
19011         }else{
19012           for(; e2>=0; e2--){
19013             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19014           }
19015         }
19016         /* The decimal point */
19017         if( flag_dp ){
19018           *(bufpt++) = '.';
19019         }
19020         /* "0" digits after the decimal point but before the first
19021         ** significant digit of the number */
19022         for(e2++; e2<0; precision--, e2++){
19023           assert( precision>0 );
19024           *(bufpt++) = '0';
19025         }
19026         /* Significant digits after the decimal point */
19027         while( (precision--)>0 ){
19028           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19029         }
19030         /* Remove trailing zeros and the "." if no digits follow the "." */
19031         if( flag_rtz && flag_dp ){
19032           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19033           assert( bufpt>buf );
19034           if( bufpt[-1]=='.' ){
19035             if( flag_altform2 ){
19036               *(bufpt++) = '0';
19037             }else{
19038               *(--bufpt) = 0;
19039             }
19040           }
19041         }
19042         /* Add the "eNNN" suffix */
19043         if( flag_exp || xtype==etEXP ){
19044           *(bufpt++) = aDigits[infop->charset];
19045           if( exp<0 ){
19046             *(bufpt++) = '-'; exp = -exp;
19047           }else{
19048             *(bufpt++) = '+';
19049           }
19050           if( exp>=100 ){
19051             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19052             exp %= 100;
19053           }
19054           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19055           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19056         }
19057         *bufpt = 0;
19058
19059         /* The converted number is in buf[] and zero terminated. Output it.
19060         ** Note that the number is in the usual order, not reversed as with
19061         ** integer conversions. */
19062         length = (int)(bufpt-buf);
19063         bufpt = buf;
19064
19065         /* Special case:  Add leading zeros if the flag_zeropad flag is
19066         ** set and we are not left justified */
19067         if( flag_zeropad && !flag_leftjustify && length < width){
19068           int i;
19069           int nPad = width - length;
19070           for(i=width; i>=nPad; i--){
19071             bufpt[i] = bufpt[i-nPad];
19072           }
19073           i = prefix!=0;
19074           while( nPad-- ) bufpt[i++] = '0';
19075           length = width;
19076         }
19077 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19078         break;
19079       case etSIZE:
19080         *(va_arg(ap,int*)) = pAccum->nChar;
19081         length = width = 0;
19082         break;
19083       case etPERCENT:
19084         buf[0] = '%';
19085         bufpt = buf;
19086         length = 1;
19087         break;
19088       case etCHARX:
19089         c = va_arg(ap,int);
19090         buf[0] = (char)c;
19091         if( precision>=0 ){
19092           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19093           length = precision;
19094         }else{
19095           length =1;
19096         }
19097         bufpt = buf;
19098         break;
19099       case etSTRING:
19100       case etDYNSTRING:
19101         bufpt = va_arg(ap,char*);
19102         if( bufpt==0 ){
19103           bufpt = "";
19104         }else if( xtype==etDYNSTRING ){
19105           zExtra = bufpt;
19106         }
19107         if( precision>=0 ){
19108           for(length=0; length<precision && bufpt[length]; length++){}
19109         }else{
19110           length = sqlite3Strlen30(bufpt);
19111         }
19112         break;
19113       case etSQLESCAPE:
19114       case etSQLESCAPE2:
19115       case etSQLESCAPE3: {
19116         int i, j, k, n, isnull;
19117         int needQuote;
19118         char ch;
19119         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19120         char *escarg = va_arg(ap,char*);
19121         isnull = escarg==0;
19122         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19123         k = precision;
19124         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19125           if( ch==q )  n++;
19126         }
19127         needQuote = !isnull && xtype==etSQLESCAPE2;
19128         n += i + 1 + needQuote*2;
19129         if( n>etBUFSIZE ){
19130           bufpt = zExtra = sqlite3Malloc( n );
19131           if( bufpt==0 ){
19132             pAccum->mallocFailed = 1;
19133             return;
19134           }
19135         }else{
19136           bufpt = buf;
19137         }
19138         j = 0;
19139         if( needQuote ) bufpt[j++] = q;
19140         k = i;
19141         for(i=0; i<k; i++){
19142           bufpt[j++] = ch = escarg[i];
19143           if( ch==q ) bufpt[j++] = ch;
19144         }
19145         if( needQuote ) bufpt[j++] = q;
19146         bufpt[j] = 0;
19147         length = j;
19148         /* The precision in %q and %Q means how many input characters to
19149         ** consume, not the length of the output...
19150         ** if( precision>=0 && precision<length ) length = precision; */
19151         break;
19152       }
19153       case etTOKEN: {
19154         Token *pToken = va_arg(ap, Token*);
19155         if( pToken ){
19156           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19157         }
19158         length = width = 0;
19159         break;
19160       }
19161       case etSRCLIST: {
19162         SrcList *pSrc = va_arg(ap, SrcList*);
19163         int k = va_arg(ap, int);
19164         struct SrcList_item *pItem = &pSrc->a[k];
19165         assert( k>=0 && k<pSrc->nSrc );
19166         if( pItem->zDatabase ){
19167           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19168           sqlite3StrAccumAppend(pAccum, ".", 1);
19169         }
19170         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19171         length = width = 0;
19172         break;
19173       }
19174       default: {
19175         assert( xtype==etINVALID );
19176         return;
19177       }
19178     }/* End switch over the format type */
19179     /*
19180     ** The text of the conversion is pointed to by "bufpt" and is
19181     ** "length" characters long.  The field width is "width".  Do
19182     ** the output.
19183     */
19184     if( !flag_leftjustify ){
19185       register int nspace;
19186       nspace = width-length;
19187       if( nspace>0 ){
19188         appendSpace(pAccum, nspace);
19189       }
19190     }
19191     if( length>0 ){
19192       sqlite3StrAccumAppend(pAccum, bufpt, length);
19193     }
19194     if( flag_leftjustify ){
19195       register int nspace;
19196       nspace = width-length;
19197       if( nspace>0 ){
19198         appendSpace(pAccum, nspace);
19199       }
19200     }
19201     if( zExtra ){
19202       sqlite3_free(zExtra);
19203     }
19204   }/* End for loop over the format string */
19205 } /* End of function */
19206
19207 /*
19208 ** Append N bytes of text from z to the StrAccum object.
19209 */
19210 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19211   assert( z!=0 || N==0 );
19212   if( p->tooBig | p->mallocFailed ){
19213     testcase(p->tooBig);
19214     testcase(p->mallocFailed);
19215     return;
19216   }
19217   if( N<0 ){
19218     N = sqlite3Strlen30(z);
19219   }
19220   if( N==0 || NEVER(z==0) ){
19221     return;
19222   }
19223   if( p->nChar+N >= p->nAlloc ){
19224     char *zNew;
19225     if( !p->useMalloc ){
19226       p->tooBig = 1;
19227       N = p->nAlloc - p->nChar - 1;
19228       if( N<=0 ){
19229         return;
19230       }
19231     }else{
19232       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19233       i64 szNew = p->nChar;
19234       szNew += N + 1;
19235       if( szNew > p->mxAlloc ){
19236         sqlite3StrAccumReset(p);
19237         p->tooBig = 1;
19238         return;
19239       }else{
19240         p->nAlloc = (int)szNew;
19241       }
19242       if( p->useMalloc==1 ){
19243         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19244       }else{
19245         zNew = sqlite3_realloc(zOld, p->nAlloc);
19246       }
19247       if( zNew ){
19248         if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19249         p->zText = zNew;
19250       }else{
19251         p->mallocFailed = 1;
19252         sqlite3StrAccumReset(p);
19253         return;
19254       }
19255     }
19256   }
19257   memcpy(&p->zText[p->nChar], z, N);
19258   p->nChar += N;
19259 }
19260
19261 /*
19262 ** Finish off a string by making sure it is zero-terminated.
19263 ** Return a pointer to the resulting string.  Return a NULL
19264 ** pointer if any kind of error was encountered.
19265 */
19266 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19267   if( p->zText ){
19268     p->zText[p->nChar] = 0;
19269     if( p->useMalloc && p->zText==p->zBase ){
19270       if( p->useMalloc==1 ){
19271         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19272       }else{
19273         p->zText = sqlite3_malloc(p->nChar+1);
19274       }
19275       if( p->zText ){
19276         memcpy(p->zText, p->zBase, p->nChar+1);
19277       }else{
19278         p->mallocFailed = 1;
19279       }
19280     }
19281   }
19282   return p->zText;
19283 }
19284
19285 /*
19286 ** Reset an StrAccum string.  Reclaim all malloced memory.
19287 */
19288 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19289   if( p->zText!=p->zBase ){
19290     if( p->useMalloc==1 ){
19291       sqlite3DbFree(p->db, p->zText);
19292     }else{
19293       sqlite3_free(p->zText);
19294     }
19295   }
19296   p->zText = 0;
19297 }
19298
19299 /*
19300 ** Initialize a string accumulator
19301 */
19302 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19303   p->zText = p->zBase = zBase;
19304   p->db = 0;
19305   p->nChar = 0;
19306   p->nAlloc = n;
19307   p->mxAlloc = mx;
19308   p->useMalloc = 1;
19309   p->tooBig = 0;
19310   p->mallocFailed = 0;
19311 }
19312
19313 /*
19314 ** Print into memory obtained from sqliteMalloc().  Use the internal
19315 ** %-conversion extensions.
19316 */
19317 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19318   char *z;
19319   char zBase[SQLITE_PRINT_BUF_SIZE];
19320   StrAccum acc;
19321   assert( db!=0 );
19322   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19323                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19324   acc.db = db;
19325   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19326   z = sqlite3StrAccumFinish(&acc);
19327   if( acc.mallocFailed ){
19328     db->mallocFailed = 1;
19329   }
19330   return z;
19331 }
19332
19333 /*
19334 ** Print into memory obtained from sqliteMalloc().  Use the internal
19335 ** %-conversion extensions.
19336 */
19337 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19338   va_list ap;
19339   char *z;
19340   va_start(ap, zFormat);
19341   z = sqlite3VMPrintf(db, zFormat, ap);
19342   va_end(ap);
19343   return z;
19344 }
19345
19346 /*
19347 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19348 ** the string and before returnning.  This routine is intended to be used
19349 ** to modify an existing string.  For example:
19350 **
19351 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19352 **
19353 */
19354 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19355   va_list ap;
19356   char *z;
19357   va_start(ap, zFormat);
19358   z = sqlite3VMPrintf(db, zFormat, ap);
19359   va_end(ap);
19360   sqlite3DbFree(db, zStr);
19361   return z;
19362 }
19363
19364 /*
19365 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19366 ** %-conversion extensions.
19367 */
19368 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19369   char *z;
19370   char zBase[SQLITE_PRINT_BUF_SIZE];
19371   StrAccum acc;
19372 #ifndef SQLITE_OMIT_AUTOINIT
19373   if( sqlite3_initialize() ) return 0;
19374 #endif
19375   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19376   acc.useMalloc = 2;
19377   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19378   z = sqlite3StrAccumFinish(&acc);
19379   return z;
19380 }
19381
19382 /*
19383 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19384 ** %-conversion extensions.
19385 */
19386 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19387   va_list ap;
19388   char *z;
19389 #ifndef SQLITE_OMIT_AUTOINIT
19390   if( sqlite3_initialize() ) return 0;
19391 #endif
19392   va_start(ap, zFormat);
19393   z = sqlite3_vmprintf(zFormat, ap);
19394   va_end(ap);
19395   return z;
19396 }
19397
19398 /*
19399 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19400 ** current locale settings.  This is important for SQLite because we
19401 ** are not able to use a "," as the decimal point in place of "." as
19402 ** specified by some locales.
19403 **
19404 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19405 ** from the snprintf() standard.  Unfortunately, it is too late to change
19406 ** this without breaking compatibility, so we just have to live with the
19407 ** mistake.
19408 **
19409 ** sqlite3_vsnprintf() is the varargs version.
19410 */
19411 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19412   StrAccum acc;
19413   if( n<=0 ) return zBuf;
19414   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19415   acc.useMalloc = 0;
19416   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19417   return sqlite3StrAccumFinish(&acc);
19418 }
19419 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19420   char *z;
19421   va_list ap;
19422   va_start(ap,zFormat);
19423   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19424   va_end(ap);
19425   return z;
19426 }
19427
19428 /*
19429 ** This is the routine that actually formats the sqlite3_log() message.
19430 ** We house it in a separate routine from sqlite3_log() to avoid using
19431 ** stack space on small-stack systems when logging is disabled.
19432 **
19433 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19434 ** allocate memory because it might be called while the memory allocator
19435 ** mutex is held.
19436 */
19437 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19438   StrAccum acc;                          /* String accumulator */
19439   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19440
19441   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19442   acc.useMalloc = 0;
19443   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19444   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19445                            sqlite3StrAccumFinish(&acc));
19446 }
19447
19448 /*
19449 ** Format and write a message to the log if logging is enabled.
19450 */
19451 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19452   va_list ap;                             /* Vararg list */
19453   if( sqlite3GlobalConfig.xLog ){
19454     va_start(ap, zFormat);
19455     renderLogMsg(iErrCode, zFormat, ap);
19456     va_end(ap);
19457   }
19458 }
19459
19460 #if defined(SQLITE_DEBUG)
19461 /*
19462 ** A version of printf() that understands %lld.  Used for debugging.
19463 ** The printf() built into some versions of windows does not understand %lld
19464 ** and segfaults if you give it a long long int.
19465 */
19466 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19467   va_list ap;
19468   StrAccum acc;
19469   char zBuf[500];
19470   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19471   acc.useMalloc = 0;
19472   va_start(ap,zFormat);
19473   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19474   va_end(ap);
19475   sqlite3StrAccumFinish(&acc);
19476   fprintf(stdout,"%s", zBuf);
19477   fflush(stdout);
19478 }
19479 #endif
19480
19481 #ifndef SQLITE_OMIT_TRACE
19482 /*
19483 ** variable-argument wrapper around sqlite3VXPrintf().
19484 */
19485 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19486   va_list ap;
19487   va_start(ap,zFormat);
19488   sqlite3VXPrintf(p, 1, zFormat, ap);
19489   va_end(ap);
19490 }
19491 #endif
19492
19493 /************** End of printf.c **********************************************/
19494 /************** Begin file random.c ******************************************/
19495 /*
19496 ** 2001 September 15
19497 **
19498 ** The author disclaims copyright to this source code.  In place of
19499 ** a legal notice, here is a blessing:
19500 **
19501 **    May you do good and not evil.
19502 **    May you find forgiveness for yourself and forgive others.
19503 **    May you share freely, never taking more than you give.
19504 **
19505 *************************************************************************
19506 ** This file contains code to implement a pseudo-random number
19507 ** generator (PRNG) for SQLite.
19508 **
19509 ** Random numbers are used by some of the database backends in order
19510 ** to generate random integer keys for tables or random filenames.
19511 */
19512
19513
19514 /* All threads share a single random number generator.
19515 ** This structure is the current state of the generator.
19516 */
19517 static SQLITE_WSD struct sqlite3PrngType {
19518   unsigned char isInit;          /* True if initialized */
19519   unsigned char i, j;            /* State variables */
19520   unsigned char s[256];          /* State variables */
19521 } sqlite3Prng;
19522
19523 /*
19524 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19525 ** must be held while executing this routine.
19526 **
19527 ** Why not just use a library random generator like lrand48() for this?
19528 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19529 ** good source of random numbers.  The lrand48() library function may
19530 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19531 ** subtle problems on some systems that could cause problems.  It is hard
19532 ** to know.  To minimize the risk of problems due to bad lrand48()
19533 ** implementations, SQLite uses this random number generator based
19534 ** on RC4, which we know works very well.
19535 **
19536 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19537 ** randomness any more.  But we will leave this code in all the same.
19538 */
19539 static u8 randomByte(void){
19540   unsigned char t;
19541
19542
19543   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19544   ** state vector.  If writable static data is unsupported on the target,
19545   ** we have to locate the state vector at run-time.  In the more common
19546   ** case where writable static data is supported, wsdPrng can refer directly
19547   ** to the "sqlite3Prng" state vector declared above.
19548   */
19549 #ifdef SQLITE_OMIT_WSD
19550   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19551 # define wsdPrng p[0]
19552 #else
19553 # define wsdPrng sqlite3Prng
19554 #endif
19555
19556
19557   /* Initialize the state of the random number generator once,
19558   ** the first time this routine is called.  The seed value does
19559   ** not need to contain a lot of randomness since we are not
19560   ** trying to do secure encryption or anything like that...
19561   **
19562   ** Nothing in this file or anywhere else in SQLite does any kind of
19563   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19564   ** number generator) not as an encryption device.
19565   */
19566   if( !wsdPrng.isInit ){
19567     int i;
19568     char k[256];
19569     wsdPrng.j = 0;
19570     wsdPrng.i = 0;
19571     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19572     for(i=0; i<256; i++){
19573       wsdPrng.s[i] = (u8)i;
19574     }
19575     for(i=0; i<256; i++){
19576       wsdPrng.j += wsdPrng.s[i] + k[i];
19577       t = wsdPrng.s[wsdPrng.j];
19578       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19579       wsdPrng.s[i] = t;
19580     }
19581     wsdPrng.isInit = 1;
19582   }
19583
19584   /* Generate and return single random byte
19585   */
19586   wsdPrng.i++;
19587   t = wsdPrng.s[wsdPrng.i];
19588   wsdPrng.j += t;
19589   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19590   wsdPrng.s[wsdPrng.j] = t;
19591   t += wsdPrng.s[wsdPrng.i];
19592   return wsdPrng.s[t];
19593 }
19594
19595 /*
19596 ** Return N random bytes.
19597 */
19598 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19599   unsigned char *zBuf = pBuf;
19600 #if SQLITE_THREADSAFE
19601   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19602 #endif
19603   sqlite3_mutex_enter(mutex);
19604   while( N-- ){
19605     *(zBuf++) = randomByte();
19606   }
19607   sqlite3_mutex_leave(mutex);
19608 }
19609
19610 #ifndef SQLITE_OMIT_BUILTIN_TEST
19611 /*
19612 ** For testing purposes, we sometimes want to preserve the state of
19613 ** PRNG and restore the PRNG to its saved state at a later time, or
19614 ** to reset the PRNG to its initial state.  These routines accomplish
19615 ** those tasks.
19616 **
19617 ** The sqlite3_test_control() interface calls these routines to
19618 ** control the PRNG.
19619 */
19620 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19621 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19622   memcpy(
19623     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19624     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19625     sizeof(sqlite3Prng)
19626   );
19627 }
19628 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19629   memcpy(
19630     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19631     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19632     sizeof(sqlite3Prng)
19633   );
19634 }
19635 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19636   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19637 }
19638 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19639
19640 /************** End of random.c **********************************************/
19641 /************** Begin file utf.c *********************************************/
19642 /*
19643 ** 2004 April 13
19644 **
19645 ** The author disclaims copyright to this source code.  In place of
19646 ** a legal notice, here is a blessing:
19647 **
19648 **    May you do good and not evil.
19649 **    May you find forgiveness for yourself and forgive others.
19650 **    May you share freely, never taking more than you give.
19651 **
19652 *************************************************************************
19653 ** This file contains routines used to translate between UTF-8, 
19654 ** UTF-16, UTF-16BE, and UTF-16LE.
19655 **
19656 ** Notes on UTF-8:
19657 **
19658 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19659 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19660 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19661 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19662 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19663 **
19664 **
19665 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19666 **
19667 **      Word-0               Word-1          Value
19668 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19669 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19670 **
19671 **
19672 ** BOM or Byte Order Mark:
19673 **     0xff 0xfe   little-endian utf-16 follows
19674 **     0xfe 0xff   big-endian utf-16 follows
19675 **
19676 */
19677
19678 #ifndef SQLITE_AMALGAMATION
19679 /*
19680 ** The following constant value is used by the SQLITE_BIGENDIAN and
19681 ** SQLITE_LITTLEENDIAN macros.
19682 */
19683 SQLITE_PRIVATE const int sqlite3one = 1;
19684 #endif /* SQLITE_AMALGAMATION */
19685
19686 /*
19687 ** This lookup table is used to help decode the first byte of
19688 ** a multi-byte UTF8 character.
19689 */
19690 static const unsigned char sqlite3Utf8Trans1[] = {
19691   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19692   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19693   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19694   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19695   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19696   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19697   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19698   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19699 };
19700
19701
19702 #define WRITE_UTF8(zOut, c) {                          \
19703   if( c<0x00080 ){                                     \
19704     *zOut++ = (u8)(c&0xFF);                            \
19705   }                                                    \
19706   else if( c<0x00800 ){                                \
19707     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19708     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19709   }                                                    \
19710   else if( c<0x10000 ){                                \
19711     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19712     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19713     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19714   }else{                                               \
19715     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19716     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19717     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19718     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19719   }                                                    \
19720 }
19721
19722 #define WRITE_UTF16LE(zOut, c) {                                    \
19723   if( c<=0xFFFF ){                                                  \
19724     *zOut++ = (u8)(c&0x00FF);                                       \
19725     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19726   }else{                                                            \
19727     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19728     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19729     *zOut++ = (u8)(c&0x00FF);                                       \
19730     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19731   }                                                                 \
19732 }
19733
19734 #define WRITE_UTF16BE(zOut, c) {                                    \
19735   if( c<=0xFFFF ){                                                  \
19736     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19737     *zOut++ = (u8)(c&0x00FF);                                       \
19738   }else{                                                            \
19739     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19740     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19741     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19742     *zOut++ = (u8)(c&0x00FF);                                       \
19743   }                                                                 \
19744 }
19745
19746 #define READ_UTF16LE(zIn, TERM, c){                                   \
19747   c = (*zIn++);                                                       \
19748   c += ((*zIn++)<<8);                                                 \
19749   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19750     int c2 = (*zIn++);                                                \
19751     c2 += ((*zIn++)<<8);                                              \
19752     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19753   }                                                                   \
19754 }
19755
19756 #define READ_UTF16BE(zIn, TERM, c){                                   \
19757   c = ((*zIn++)<<8);                                                  \
19758   c += (*zIn++);                                                      \
19759   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19760     int c2 = ((*zIn++)<<8);                                           \
19761     c2 += (*zIn++);                                                   \
19762     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19763   }                                                                   \
19764 }
19765
19766 /*
19767 ** Translate a single UTF-8 character.  Return the unicode value.
19768 **
19769 ** During translation, assume that the byte that zTerm points
19770 ** is a 0x00.
19771 **
19772 ** Write a pointer to the next unread byte back into *pzNext.
19773 **
19774 ** Notes On Invalid UTF-8:
19775 **
19776 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19777 **     be encoded as a multi-byte character.  Any multi-byte character that
19778 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19779 **
19780 **  *  This routine never allows a UTF16 surrogate value to be encoded.
19781 **     If a multi-byte character attempts to encode a value between
19782 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
19783 **
19784 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19785 **     byte of a character are interpreted as single-byte characters
19786 **     and rendered as themselves even though they are technically
19787 **     invalid characters.
19788 **
19789 **  *  This routine accepts an infinite number of different UTF8 encodings
19790 **     for unicode values 0x80 and greater.  It do not change over-length
19791 **     encodings to 0xfffd as some systems recommend.
19792 */
19793 #define READ_UTF8(zIn, zTerm, c)                           \
19794   c = *(zIn++);                                            \
19795   if( c>=0xc0 ){                                           \
19796     c = sqlite3Utf8Trans1[c-0xc0];                         \
19797     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19798       c = (c<<6) + (0x3f & *(zIn++));                      \
19799     }                                                      \
19800     if( c<0x80                                             \
19801         || (c&0xFFFFF800)==0xD800                          \
19802         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19803   }
19804 SQLITE_PRIVATE int sqlite3Utf8Read(
19805   const unsigned char *zIn,       /* First byte of UTF-8 character */
19806   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19807 ){
19808   unsigned int c;
19809
19810   /* Same as READ_UTF8() above but without the zTerm parameter.
19811   ** For this routine, we assume the UTF8 string is always zero-terminated.
19812   */
19813   c = *(zIn++);
19814   if( c>=0xc0 ){
19815     c = sqlite3Utf8Trans1[c-0xc0];
19816     while( (*zIn & 0xc0)==0x80 ){
19817       c = (c<<6) + (0x3f & *(zIn++));
19818     }
19819     if( c<0x80
19820         || (c&0xFFFFF800)==0xD800
19821         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19822   }
19823   *pzNext = zIn;
19824   return c;
19825 }
19826
19827
19828
19829
19830 /*
19831 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19832 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19833 */ 
19834 /* #define TRANSLATE_TRACE 1 */
19835
19836 #ifndef SQLITE_OMIT_UTF16
19837 /*
19838 ** This routine transforms the internal text encoding used by pMem to
19839 ** desiredEnc. It is an error if the string is already of the desired
19840 ** encoding, or if *pMem does not contain a string value.
19841 */
19842 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19843   int len;                    /* Maximum length of output string in bytes */
19844   unsigned char *zOut;                  /* Output buffer */
19845   unsigned char *zIn;                   /* Input iterator */
19846   unsigned char *zTerm;                 /* End of input */
19847   unsigned char *z;                     /* Output iterator */
19848   unsigned int c;
19849
19850   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19851   assert( pMem->flags&MEM_Str );
19852   assert( pMem->enc!=desiredEnc );
19853   assert( pMem->enc!=0 );
19854   assert( pMem->n>=0 );
19855
19856 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19857   {
19858     char zBuf[100];
19859     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19860     fprintf(stderr, "INPUT:  %s\n", zBuf);
19861   }
19862 #endif
19863
19864   /* If the translation is between UTF-16 little and big endian, then 
19865   ** all that is required is to swap the byte order. This case is handled
19866   ** differently from the others.
19867   */
19868   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19869     u8 temp;
19870     int rc;
19871     rc = sqlite3VdbeMemMakeWriteable(pMem);
19872     if( rc!=SQLITE_OK ){
19873       assert( rc==SQLITE_NOMEM );
19874       return SQLITE_NOMEM;
19875     }
19876     zIn = (u8*)pMem->z;
19877     zTerm = &zIn[pMem->n&~1];
19878     while( zIn<zTerm ){
19879       temp = *zIn;
19880       *zIn = *(zIn+1);
19881       zIn++;
19882       *zIn++ = temp;
19883     }
19884     pMem->enc = desiredEnc;
19885     goto translate_out;
19886   }
19887
19888   /* Set len to the maximum number of bytes required in the output buffer. */
19889   if( desiredEnc==SQLITE_UTF8 ){
19890     /* When converting from UTF-16, the maximum growth results from
19891     ** translating a 2-byte character to a 4-byte UTF-8 character.
19892     ** A single byte is required for the output string
19893     ** nul-terminator.
19894     */
19895     pMem->n &= ~1;
19896     len = pMem->n * 2 + 1;
19897   }else{
19898     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19899     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19900     ** character. Two bytes are required in the output buffer for the
19901     ** nul-terminator.
19902     */
19903     len = pMem->n * 2 + 2;
19904   }
19905
19906   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19907   ** byte past the end.
19908   **
19909   ** Variable zOut is set to point at the output buffer, space obtained
19910   ** from sqlite3_malloc().
19911   */
19912   zIn = (u8*)pMem->z;
19913   zTerm = &zIn[pMem->n];
19914   zOut = sqlite3DbMallocRaw(pMem->db, len);
19915   if( !zOut ){
19916     return SQLITE_NOMEM;
19917   }
19918   z = zOut;
19919
19920   if( pMem->enc==SQLITE_UTF8 ){
19921     if( desiredEnc==SQLITE_UTF16LE ){
19922       /* UTF-8 -> UTF-16 Little-endian */
19923       while( zIn<zTerm ){
19924         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19925         READ_UTF8(zIn, zTerm, c);
19926         WRITE_UTF16LE(z, c);
19927       }
19928     }else{
19929       assert( desiredEnc==SQLITE_UTF16BE );
19930       /* UTF-8 -> UTF-16 Big-endian */
19931       while( zIn<zTerm ){
19932         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19933         READ_UTF8(zIn, zTerm, c);
19934         WRITE_UTF16BE(z, c);
19935       }
19936     }
19937     pMem->n = (int)(z - zOut);
19938     *z++ = 0;
19939   }else{
19940     assert( desiredEnc==SQLITE_UTF8 );
19941     if( pMem->enc==SQLITE_UTF16LE ){
19942       /* UTF-16 Little-endian -> UTF-8 */
19943       while( zIn<zTerm ){
19944         READ_UTF16LE(zIn, zIn<zTerm, c); 
19945         WRITE_UTF8(z, c);
19946       }
19947     }else{
19948       /* UTF-16 Big-endian -> UTF-8 */
19949       while( zIn<zTerm ){
19950         READ_UTF16BE(zIn, zIn<zTerm, c); 
19951         WRITE_UTF8(z, c);
19952       }
19953     }
19954     pMem->n = (int)(z - zOut);
19955   }
19956   *z = 0;
19957   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19958
19959   sqlite3VdbeMemRelease(pMem);
19960   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19961   pMem->enc = desiredEnc;
19962   pMem->flags |= (MEM_Term|MEM_Dyn);
19963   pMem->z = (char*)zOut;
19964   pMem->zMalloc = pMem->z;
19965
19966 translate_out:
19967 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19968   {
19969     char zBuf[100];
19970     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19971     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19972   }
19973 #endif
19974   return SQLITE_OK;
19975 }
19976
19977 /*
19978 ** This routine checks for a byte-order mark at the beginning of the 
19979 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19980 ** the encoding of the Mem adjusted. This routine does not do any
19981 ** byte-swapping, it just sets Mem.enc appropriately.
19982 **
19983 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19984 ** changed by this function.
19985 */
19986 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19987   int rc = SQLITE_OK;
19988   u8 bom = 0;
19989
19990   assert( pMem->n>=0 );
19991   if( pMem->n>1 ){
19992     u8 b1 = *(u8 *)pMem->z;
19993     u8 b2 = *(((u8 *)pMem->z) + 1);
19994     if( b1==0xFE && b2==0xFF ){
19995       bom = SQLITE_UTF16BE;
19996     }
19997     if( b1==0xFF && b2==0xFE ){
19998       bom = SQLITE_UTF16LE;
19999     }
20000   }
20001   
20002   if( bom ){
20003     rc = sqlite3VdbeMemMakeWriteable(pMem);
20004     if( rc==SQLITE_OK ){
20005       pMem->n -= 2;
20006       memmove(pMem->z, &pMem->z[2], pMem->n);
20007       pMem->z[pMem->n] = '\0';
20008       pMem->z[pMem->n+1] = '\0';
20009       pMem->flags |= MEM_Term;
20010       pMem->enc = bom;
20011     }
20012   }
20013   return rc;
20014 }
20015 #endif /* SQLITE_OMIT_UTF16 */
20016
20017 /*
20018 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20019 ** return the number of unicode characters in pZ up to (but not including)
20020 ** the first 0x00 byte. If nByte is not less than zero, return the
20021 ** number of unicode characters in the first nByte of pZ (or up to 
20022 ** the first 0x00, whichever comes first).
20023 */
20024 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20025   int r = 0;
20026   const u8 *z = (const u8*)zIn;
20027   const u8 *zTerm;
20028   if( nByte>=0 ){
20029     zTerm = &z[nByte];
20030   }else{
20031     zTerm = (const u8*)(-1);
20032   }
20033   assert( z<=zTerm );
20034   while( *z!=0 && z<zTerm ){
20035     SQLITE_SKIP_UTF8(z);
20036     r++;
20037   }
20038   return r;
20039 }
20040
20041 /* This test function is not currently used by the automated test-suite. 
20042 ** Hence it is only available in debug builds.
20043 */
20044 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20045 /*
20046 ** Translate UTF-8 to UTF-8.
20047 **
20048 ** This has the effect of making sure that the string is well-formed
20049 ** UTF-8.  Miscoded characters are removed.
20050 **
20051 ** The translation is done in-place and aborted if the output
20052 ** overruns the input.
20053 */
20054 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20055   unsigned char *zOut = zIn;
20056   unsigned char *zStart = zIn;
20057   u32 c;
20058
20059   while( zIn[0] && zOut<=zIn ){
20060     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20061     if( c!=0xfffd ){
20062       WRITE_UTF8(zOut, c);
20063     }
20064   }
20065   *zOut = 0;
20066   return (int)(zOut - zStart);
20067 }
20068 #endif
20069
20070 #ifndef SQLITE_OMIT_UTF16
20071 /*
20072 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20073 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20074 ** be freed by the calling function.
20075 **
20076 ** NULL is returned if there is an allocation error.
20077 */
20078 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20079   Mem m;
20080   memset(&m, 0, sizeof(m));
20081   m.db = db;
20082   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20083   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20084   if( db->mallocFailed ){
20085     sqlite3VdbeMemRelease(&m);
20086     m.z = 0;
20087   }
20088   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20089   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20090   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20091   assert( m.z || db->mallocFailed );
20092   return m.z;
20093 }
20094
20095 /*
20096 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20097 ** enc. A pointer to the new string is returned, and the value of *pnOut
20098 ** is set to the length of the returned string in bytes. The call should
20099 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20100 ** no longer required.
20101 ** 
20102 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20103 ** flag set.
20104 */
20105 #ifdef SQLITE_ENABLE_STAT2
20106 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20107   Mem m;
20108   memset(&m, 0, sizeof(m));
20109   m.db = db;
20110   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20111   if( sqlite3VdbeMemTranslate(&m, enc) ){
20112     assert( db->mallocFailed );
20113     return 0;
20114   }
20115   assert( m.z==m.zMalloc );
20116   *pnOut = m.n;
20117   return m.z;
20118 }
20119 #endif
20120
20121 /*
20122 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20123 ** Return the number of bytes in the first nChar unicode characters
20124 ** in pZ.  nChar must be non-negative.
20125 */
20126 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20127   int c;
20128   unsigned char const *z = zIn;
20129   int n = 0;
20130   
20131   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20132     while( n<nChar ){
20133       READ_UTF16BE(z, 1, c);
20134       n++;
20135     }
20136   }else{
20137     while( n<nChar ){
20138       READ_UTF16LE(z, 1, c);
20139       n++;
20140     }
20141   }
20142   return (int)(z-(unsigned char const *)zIn);
20143 }
20144
20145 #if defined(SQLITE_TEST)
20146 /*
20147 ** This routine is called from the TCL test function "translate_selftest".
20148 ** It checks that the primitives for serializing and deserializing
20149 ** characters in each encoding are inverses of each other.
20150 */
20151 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20152   unsigned int i, t;
20153   unsigned char zBuf[20];
20154   unsigned char *z;
20155   int n;
20156   unsigned int c;
20157
20158   for(i=0; i<0x00110000; i++){
20159     z = zBuf;
20160     WRITE_UTF8(z, i);
20161     n = (int)(z-zBuf);
20162     assert( n>0 && n<=4 );
20163     z[0] = 0;
20164     z = zBuf;
20165     c = sqlite3Utf8Read(z, (const u8**)&z);
20166     t = i;
20167     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20168     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20169     assert( c==t );
20170     assert( (z-zBuf)==n );
20171   }
20172   for(i=0; i<0x00110000; i++){
20173     if( i>=0xD800 && i<0xE000 ) continue;
20174     z = zBuf;
20175     WRITE_UTF16LE(z, i);
20176     n = (int)(z-zBuf);
20177     assert( n>0 && n<=4 );
20178     z[0] = 0;
20179     z = zBuf;
20180     READ_UTF16LE(z, 1, c);
20181     assert( c==i );
20182     assert( (z-zBuf)==n );
20183   }
20184   for(i=0; i<0x00110000; i++){
20185     if( i>=0xD800 && i<0xE000 ) continue;
20186     z = zBuf;
20187     WRITE_UTF16BE(z, i);
20188     n = (int)(z-zBuf);
20189     assert( n>0 && n<=4 );
20190     z[0] = 0;
20191     z = zBuf;
20192     READ_UTF16BE(z, 1, c);
20193     assert( c==i );
20194     assert( (z-zBuf)==n );
20195   }
20196 }
20197 #endif /* SQLITE_TEST */
20198 #endif /* SQLITE_OMIT_UTF16 */
20199
20200 /************** End of utf.c *************************************************/
20201 /************** Begin file util.c ********************************************/
20202 /*
20203 ** 2001 September 15
20204 **
20205 ** The author disclaims copyright to this source code.  In place of
20206 ** a legal notice, here is a blessing:
20207 **
20208 **    May you do good and not evil.
20209 **    May you find forgiveness for yourself and forgive others.
20210 **    May you share freely, never taking more than you give.
20211 **
20212 *************************************************************************
20213 ** Utility functions used throughout sqlite.
20214 **
20215 ** This file contains functions for allocating memory, comparing
20216 ** strings, and stuff like that.
20217 **
20218 */
20219 #ifdef SQLITE_HAVE_ISNAN
20220 # include <math.h>
20221 #endif
20222
20223 /*
20224 ** Routine needed to support the testcase() macro.
20225 */
20226 #ifdef SQLITE_COVERAGE_TEST
20227 SQLITE_PRIVATE void sqlite3Coverage(int x){
20228   static unsigned dummy = 0;
20229   dummy += (unsigned)x;
20230 }
20231 #endif
20232
20233 #ifndef SQLITE_OMIT_FLOATING_POINT
20234 /*
20235 ** Return true if the floating point value is Not a Number (NaN).
20236 **
20237 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20238 ** Otherwise, we have our own implementation that works on most systems.
20239 */
20240 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20241   int rc;   /* The value return */
20242 #if !defined(SQLITE_HAVE_ISNAN)
20243   /*
20244   ** Systems that support the isnan() library function should probably
20245   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20246   ** found that many systems do not have a working isnan() function so
20247   ** this implementation is provided as an alternative.
20248   **
20249   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20250   ** On the other hand, the use of -ffast-math comes with the following
20251   ** warning:
20252   **
20253   **      This option [-ffast-math] should never be turned on by any
20254   **      -O option since it can result in incorrect output for programs
20255   **      which depend on an exact implementation of IEEE or ISO 
20256   **      rules/specifications for math functions.
20257   **
20258   ** Under MSVC, this NaN test may fail if compiled with a floating-
20259   ** point precision mode other than /fp:precise.  From the MSDN 
20260   ** documentation:
20261   **
20262   **      The compiler [with /fp:precise] will properly handle comparisons 
20263   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20264   **      ...
20265   */
20266 #ifdef __FAST_MATH__
20267 # error SQLite will not work correctly with the -ffast-math option of GCC.
20268 #endif
20269   volatile double y = x;
20270   volatile double z = y;
20271   rc = (y!=z);
20272 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20273   rc = isnan(x);
20274 #endif /* SQLITE_HAVE_ISNAN */
20275   testcase( rc );
20276   return rc;
20277 }
20278 #endif /* SQLITE_OMIT_FLOATING_POINT */
20279
20280 /*
20281 ** Compute a string length that is limited to what can be stored in
20282 ** lower 30 bits of a 32-bit signed integer.
20283 **
20284 ** The value returned will never be negative.  Nor will it ever be greater
20285 ** than the actual length of the string.  For very long strings (greater
20286 ** than 1GiB) the value returned might be less than the true string length.
20287 */
20288 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20289   const char *z2 = z;
20290   if( z==0 ) return 0;
20291   while( *z2 ){ z2++; }
20292   return 0x3fffffff & (int)(z2 - z);
20293 }
20294
20295 /*
20296 ** Set the most recent error code and error string for the sqlite
20297 ** handle "db". The error code is set to "err_code".
20298 **
20299 ** If it is not NULL, string zFormat specifies the format of the
20300 ** error string in the style of the printf functions: The following
20301 ** format characters are allowed:
20302 **
20303 **      %s      Insert a string
20304 **      %z      A string that should be freed after use
20305 **      %d      Insert an integer
20306 **      %T      Insert a token
20307 **      %S      Insert the first element of a SrcList
20308 **
20309 ** zFormat and any string tokens that follow it are assumed to be
20310 ** encoded in UTF-8.
20311 **
20312 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20313 ** should be called with err_code set to SQLITE_OK and zFormat set
20314 ** to NULL.
20315 */
20316 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20317   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20318     db->errCode = err_code;
20319     if( zFormat ){
20320       char *z;
20321       va_list ap;
20322       va_start(ap, zFormat);
20323       z = sqlite3VMPrintf(db, zFormat, ap);
20324       va_end(ap);
20325       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20326     }else{
20327       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20328     }
20329   }
20330 }
20331
20332 /*
20333 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20334 ** The following formatting characters are allowed:
20335 **
20336 **      %s      Insert a string
20337 **      %z      A string that should be freed after use
20338 **      %d      Insert an integer
20339 **      %T      Insert a token
20340 **      %S      Insert the first element of a SrcList
20341 **
20342 ** This function should be used to report any error that occurs whilst
20343 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20344 ** last thing the sqlite3_prepare() function does is copy the error
20345 ** stored by this function into the database handle using sqlite3Error().
20346 ** Function sqlite3Error() should be used during statement execution
20347 ** (sqlite3_step() etc.).
20348 */
20349 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20350   char *zMsg;
20351   va_list ap;
20352   sqlite3 *db = pParse->db;
20353   va_start(ap, zFormat);
20354   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20355   va_end(ap);
20356   if( db->suppressErr ){
20357     sqlite3DbFree(db, zMsg);
20358   }else{
20359     pParse->nErr++;
20360     sqlite3DbFree(db, pParse->zErrMsg);
20361     pParse->zErrMsg = zMsg;
20362     pParse->rc = SQLITE_ERROR;
20363   }
20364 }
20365
20366 /*
20367 ** Convert an SQL-style quoted string into a normal string by removing
20368 ** the quote characters.  The conversion is done in-place.  If the
20369 ** input does not begin with a quote character, then this routine
20370 ** is a no-op.
20371 **
20372 ** The input string must be zero-terminated.  A new zero-terminator
20373 ** is added to the dequoted string.
20374 **
20375 ** The return value is -1 if no dequoting occurs or the length of the
20376 ** dequoted string, exclusive of the zero terminator, if dequoting does
20377 ** occur.
20378 **
20379 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20380 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20381 ** "a-b-c".
20382 */
20383 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20384   char quote;
20385   int i, j;
20386   if( z==0 ) return -1;
20387   quote = z[0];
20388   switch( quote ){
20389     case '\'':  break;
20390     case '"':   break;
20391     case '`':   break;                /* For MySQL compatibility */
20392     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20393     default:    return -1;
20394   }
20395   for(i=1, j=0; ALWAYS(z[i]); i++){
20396     if( z[i]==quote ){
20397       if( z[i+1]==quote ){
20398         z[j++] = quote;
20399         i++;
20400       }else{
20401         break;
20402       }
20403     }else{
20404       z[j++] = z[i];
20405     }
20406   }
20407   z[j] = 0;
20408   return j;
20409 }
20410
20411 /* Convenient short-hand */
20412 #define UpperToLower sqlite3UpperToLower
20413
20414 /*
20415 ** Some systems have stricmp().  Others have strcasecmp().  Because
20416 ** there is no consistency, we will define our own.
20417 **
20418 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20419 ** applications and extensions to compare the contents of two buffers
20420 ** containing UTF-8 strings in a case-independent fashion, using the same
20421 ** definition of case independence that SQLite uses internally when
20422 ** comparing identifiers.
20423 */
20424 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20425   register unsigned char *a, *b;
20426   a = (unsigned char *)zLeft;
20427   b = (unsigned char *)zRight;
20428   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20429   return UpperToLower[*a] - UpperToLower[*b];
20430 }
20431 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20432   register unsigned char *a, *b;
20433   a = (unsigned char *)zLeft;
20434   b = (unsigned char *)zRight;
20435   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20436   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20437 }
20438
20439 /*
20440 ** The string z[] is an text representation of a real number.
20441 ** Convert this string to a double and write it into *pResult.
20442 **
20443 ** The string z[] is length bytes in length (bytes, not characters) and
20444 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20445 **
20446 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20447 ** if the string is empty or contains extraneous text.  Valid numbers
20448 ** are in one of these formats:
20449 **
20450 **    [+-]digits[E[+-]digits]
20451 **    [+-]digits.[digits][E[+-]digits]
20452 **    [+-].digits[E[+-]digits]
20453 **
20454 ** Leading and trailing whitespace is ignored for the purpose of determining
20455 ** validity.
20456 **
20457 ** If some prefix of the input string is a valid number, this routine
20458 ** returns FALSE but it still converts the prefix and writes the result
20459 ** into *pResult.
20460 */
20461 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20462 #ifndef SQLITE_OMIT_FLOATING_POINT
20463   int incr = (enc==SQLITE_UTF8?1:2);
20464   const char *zEnd = z + length;
20465   /* sign * significand * (10 ^ (esign * exponent)) */
20466   int sign = 1;    /* sign of significand */
20467   i64 s = 0;       /* significand */
20468   int d = 0;       /* adjust exponent for shifting decimal point */
20469   int esign = 1;   /* sign of exponent */
20470   int e = 0;       /* exponent */
20471   int eValid = 1;  /* True exponent is either not used or is well-formed */
20472   double result;
20473   int nDigits = 0;
20474
20475   *pResult = 0.0;   /* Default return value, in case of an error */
20476
20477   if( enc==SQLITE_UTF16BE ) z++;
20478
20479   /* skip leading spaces */
20480   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20481   if( z>=zEnd ) return 0;
20482
20483   /* get sign of significand */
20484   if( *z=='-' ){
20485     sign = -1;
20486     z+=incr;
20487   }else if( *z=='+' ){
20488     z+=incr;
20489   }
20490
20491   /* skip leading zeroes */
20492   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20493
20494   /* copy max significant digits to significand */
20495   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20496     s = s*10 + (*z - '0');
20497     z+=incr, nDigits++;
20498   }
20499
20500   /* skip non-significant significand digits
20501   ** (increase exponent by d to shift decimal left) */
20502   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20503   if( z>=zEnd ) goto do_atof_calc;
20504
20505   /* if decimal point is present */
20506   if( *z=='.' ){
20507     z+=incr;
20508     /* copy digits from after decimal to significand
20509     ** (decrease exponent by d to shift decimal right) */
20510     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20511       s = s*10 + (*z - '0');
20512       z+=incr, nDigits++, d--;
20513     }
20514     /* skip non-significant digits */
20515     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20516   }
20517   if( z>=zEnd ) goto do_atof_calc;
20518
20519   /* if exponent is present */
20520   if( *z=='e' || *z=='E' ){
20521     z+=incr;
20522     eValid = 0;
20523     if( z>=zEnd ) goto do_atof_calc;
20524     /* get sign of exponent */
20525     if( *z=='-' ){
20526       esign = -1;
20527       z+=incr;
20528     }else if( *z=='+' ){
20529       z+=incr;
20530     }
20531     /* copy digits to exponent */
20532     while( z<zEnd && sqlite3Isdigit(*z) ){
20533       e = e*10 + (*z - '0');
20534       z+=incr;
20535       eValid = 1;
20536     }
20537   }
20538
20539   /* skip trailing spaces */
20540   if( nDigits && eValid ){
20541     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20542   }
20543
20544 do_atof_calc:
20545   /* adjust exponent by d, and update sign */
20546   e = (e*esign) + d;
20547   if( e<0 ) {
20548     esign = -1;
20549     e *= -1;
20550   } else {
20551     esign = 1;
20552   }
20553
20554   /* if 0 significand */
20555   if( !s ) {
20556     /* In the IEEE 754 standard, zero is signed.
20557     ** Add the sign if we've seen at least one digit */
20558     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20559   } else {
20560     /* attempt to reduce exponent */
20561     if( esign>0 ){
20562       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20563     }else{
20564       while( !(s%10) && e>0 ) e--,s/=10;
20565     }
20566
20567     /* adjust the sign of significand */
20568     s = sign<0 ? -s : s;
20569
20570     /* if exponent, scale significand as appropriate
20571     ** and store in result. */
20572     if( e ){
20573       double scale = 1.0;
20574       /* attempt to handle extremely small/large numbers better */
20575       if( e>307 && e<342 ){
20576         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20577         if( esign<0 ){
20578           result = s / scale;
20579           result /= 1.0e+308;
20580         }else{
20581           result = s * scale;
20582           result *= 1.0e+308;
20583         }
20584       }else{
20585         /* 1.0e+22 is the largest power of 10 than can be 
20586         ** represented exactly. */
20587         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20588         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20589         if( esign<0 ){
20590           result = s / scale;
20591         }else{
20592           result = s * scale;
20593         }
20594       }
20595     } else {
20596       result = (double)s;
20597     }
20598   }
20599
20600   /* store the result */
20601   *pResult = result;
20602
20603   /* return true if number and no extra non-whitespace chracters after */
20604   return z>=zEnd && nDigits>0 && eValid;
20605 #else
20606   return !sqlite3Atoi64(z, pResult, length, enc);
20607 #endif /* SQLITE_OMIT_FLOATING_POINT */
20608 }
20609
20610 /*
20611 ** Compare the 19-character string zNum against the text representation
20612 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20613 ** if zNum is less than, equal to, or greater than the string.
20614 ** Note that zNum must contain exactly 19 characters.
20615 **
20616 ** Unlike memcmp() this routine is guaranteed to return the difference
20617 ** in the values of the last digit if the only difference is in the
20618 ** last digit.  So, for example,
20619 **
20620 **      compare2pow63("9223372036854775800", 1)
20621 **
20622 ** will return -8.
20623 */
20624 static int compare2pow63(const char *zNum, int incr){
20625   int c = 0;
20626   int i;
20627                     /* 012345678901234567 */
20628   const char *pow63 = "922337203685477580";
20629   for(i=0; c==0 && i<18; i++){
20630     c = (zNum[i*incr]-pow63[i])*10;
20631   }
20632   if( c==0 ){
20633     c = zNum[18*incr] - '8';
20634     testcase( c==(-1) );
20635     testcase( c==0 );
20636     testcase( c==(+1) );
20637   }
20638   return c;
20639 }
20640
20641
20642 /*
20643 ** Convert zNum to a 64-bit signed integer.
20644 **
20645 ** If the zNum value is representable as a 64-bit twos-complement 
20646 ** integer, then write that value into *pNum and return 0.
20647 **
20648 ** If zNum is exactly 9223372036854665808, return 2.  This special
20649 ** case is broken out because while 9223372036854665808 cannot be a 
20650 ** signed 64-bit integer, its negative -9223372036854665808 can be.
20651 **
20652 ** If zNum is too big for a 64-bit integer and is not
20653 ** 9223372036854665808 then return 1.
20654 **
20655 ** length is the number of bytes in the string (bytes, not characters).
20656 ** The string is not necessarily zero-terminated.  The encoding is
20657 ** given by enc.
20658 */
20659 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20660   int incr = (enc==SQLITE_UTF8?1:2);
20661   u64 u = 0;
20662   int neg = 0; /* assume positive */
20663   int i;
20664   int c = 0;
20665   const char *zStart;
20666   const char *zEnd = zNum + length;
20667   if( enc==SQLITE_UTF16BE ) zNum++;
20668   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20669   if( zNum<zEnd ){
20670     if( *zNum=='-' ){
20671       neg = 1;
20672       zNum+=incr;
20673     }else if( *zNum=='+' ){
20674       zNum+=incr;
20675     }
20676   }
20677   zStart = zNum;
20678   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20679   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20680     u = u*10 + c - '0';
20681   }
20682   if( u>LARGEST_INT64 ){
20683     *pNum = SMALLEST_INT64;
20684   }else if( neg ){
20685     *pNum = -(i64)u;
20686   }else{
20687     *pNum = (i64)u;
20688   }
20689   testcase( i==18 );
20690   testcase( i==19 );
20691   testcase( i==20 );
20692   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20693     /* zNum is empty or contains non-numeric text or is longer
20694     ** than 19 digits (thus guaranteeing that it is too large) */
20695     return 1;
20696   }else if( i<19*incr ){
20697     /* Less than 19 digits, so we know that it fits in 64 bits */
20698     assert( u<=LARGEST_INT64 );
20699     return 0;
20700   }else{
20701     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
20702     c = compare2pow63(zNum, incr);
20703     if( c<0 ){
20704       /* zNum is less than 9223372036854775808 so it fits */
20705       assert( u<=LARGEST_INT64 );
20706       return 0;
20707     }else if( c>0 ){
20708       /* zNum is greater than 9223372036854775808 so it overflows */
20709       return 1;
20710     }else{
20711       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
20712       ** special case 2 overflow if positive */
20713       assert( u-1==LARGEST_INT64 );
20714       assert( (*pNum)==SMALLEST_INT64 );
20715       return neg ? 0 : 2;
20716     }
20717   }
20718 }
20719
20720 /*
20721 ** If zNum represents an integer that will fit in 32-bits, then set
20722 ** *pValue to that integer and return true.  Otherwise return false.
20723 **
20724 ** Any non-numeric characters that following zNum are ignored.
20725 ** This is different from sqlite3Atoi64() which requires the
20726 ** input number to be zero-terminated.
20727 */
20728 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20729   sqlite_int64 v = 0;
20730   int i, c;
20731   int neg = 0;
20732   if( zNum[0]=='-' ){
20733     neg = 1;
20734     zNum++;
20735   }else if( zNum[0]=='+' ){
20736     zNum++;
20737   }
20738   while( zNum[0]=='0' ) zNum++;
20739   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20740     v = v*10 + c;
20741   }
20742
20743   /* The longest decimal representation of a 32 bit integer is 10 digits:
20744   **
20745   **             1234567890
20746   **     2^31 -> 2147483648
20747   */
20748   testcase( i==10 );
20749   if( i>10 ){
20750     return 0;
20751   }
20752   testcase( v-neg==2147483647 );
20753   if( v-neg>2147483647 ){
20754     return 0;
20755   }
20756   if( neg ){
20757     v = -v;
20758   }
20759   *pValue = (int)v;
20760   return 1;
20761 }
20762
20763 /*
20764 ** Return a 32-bit integer value extracted from a string.  If the
20765 ** string is not an integer, just return 0.
20766 */
20767 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20768   int x = 0;
20769   if( z ) sqlite3GetInt32(z, &x);
20770   return x;
20771 }
20772
20773 /*
20774 ** The variable-length integer encoding is as follows:
20775 **
20776 ** KEY:
20777 **         A = 0xxxxxxx    7 bits of data and one flag bit
20778 **         B = 1xxxxxxx    7 bits of data and one flag bit
20779 **         C = xxxxxxxx    8 bits of data
20780 **
20781 **  7 bits - A
20782 ** 14 bits - BA
20783 ** 21 bits - BBA
20784 ** 28 bits - BBBA
20785 ** 35 bits - BBBBA
20786 ** 42 bits - BBBBBA
20787 ** 49 bits - BBBBBBA
20788 ** 56 bits - BBBBBBBA
20789 ** 64 bits - BBBBBBBBC
20790 */
20791
20792 /*
20793 ** Write a 64-bit variable-length integer to memory starting at p[0].
20794 ** The length of data write will be between 1 and 9 bytes.  The number
20795 ** of bytes written is returned.
20796 **
20797 ** A variable-length integer consists of the lower 7 bits of each byte
20798 ** for all bytes that have the 8th bit set and one byte with the 8th
20799 ** bit clear.  Except, if we get to the 9th byte, it stores the full
20800 ** 8 bits and is the last byte.
20801 */
20802 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20803   int i, j, n;
20804   u8 buf[10];
20805   if( v & (((u64)0xff000000)<<32) ){
20806     p[8] = (u8)v;
20807     v >>= 8;
20808     for(i=7; i>=0; i--){
20809       p[i] = (u8)((v & 0x7f) | 0x80);
20810       v >>= 7;
20811     }
20812     return 9;
20813   }    
20814   n = 0;
20815   do{
20816     buf[n++] = (u8)((v & 0x7f) | 0x80);
20817     v >>= 7;
20818   }while( v!=0 );
20819   buf[0] &= 0x7f;
20820   assert( n<=9 );
20821   for(i=0, j=n-1; j>=0; j--, i++){
20822     p[i] = buf[j];
20823   }
20824   return n;
20825 }
20826
20827 /*
20828 ** This routine is a faster version of sqlite3PutVarint() that only
20829 ** works for 32-bit positive integers and which is optimized for
20830 ** the common case of small integers.  A MACRO version, putVarint32,
20831 ** is provided which inlines the single-byte case.  All code should use
20832 ** the MACRO version as this function assumes the single-byte case has
20833 ** already been handled.
20834 */
20835 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20836 #ifndef putVarint32
20837   if( (v & ~0x7f)==0 ){
20838     p[0] = v;
20839     return 1;
20840   }
20841 #endif
20842   if( (v & ~0x3fff)==0 ){
20843     p[0] = (u8)((v>>7) | 0x80);
20844     p[1] = (u8)(v & 0x7f);
20845     return 2;
20846   }
20847   return sqlite3PutVarint(p, v);
20848 }
20849
20850 /*
20851 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20852 ** are defined here rather than simply putting the constant expressions
20853 ** inline in order to work around bugs in the RVT compiler.
20854 **
20855 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20856 **
20857 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20858 */
20859 #define SLOT_2_0     0x001fc07f
20860 #define SLOT_4_2_0   0xf01fc07f
20861
20862
20863 /*
20864 ** Read a 64-bit variable-length integer from memory starting at p[0].
20865 ** Return the number of bytes read.  The value is stored in *v.
20866 */
20867 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20868   u32 a,b,s;
20869
20870   a = *p;
20871   /* a: p0 (unmasked) */
20872   if (!(a&0x80))
20873   {
20874     *v = a;
20875     return 1;
20876   }
20877
20878   p++;
20879   b = *p;
20880   /* b: p1 (unmasked) */
20881   if (!(b&0x80))
20882   {
20883     a &= 0x7f;
20884     a = a<<7;
20885     a |= b;
20886     *v = a;
20887     return 2;
20888   }
20889
20890   /* Verify that constants are precomputed correctly */
20891   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20892   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20893
20894   p++;
20895   a = a<<14;
20896   a |= *p;
20897   /* a: p0<<14 | p2 (unmasked) */
20898   if (!(a&0x80))
20899   {
20900     a &= SLOT_2_0;
20901     b &= 0x7f;
20902     b = b<<7;
20903     a |= b;
20904     *v = a;
20905     return 3;
20906   }
20907
20908   /* CSE1 from below */
20909   a &= SLOT_2_0;
20910   p++;
20911   b = b<<14;
20912   b |= *p;
20913   /* b: p1<<14 | p3 (unmasked) */
20914   if (!(b&0x80))
20915   {
20916     b &= SLOT_2_0;
20917     /* moved CSE1 up */
20918     /* a &= (0x7f<<14)|(0x7f); */
20919     a = a<<7;
20920     a |= b;
20921     *v = a;
20922     return 4;
20923   }
20924
20925   /* a: p0<<14 | p2 (masked) */
20926   /* b: p1<<14 | p3 (unmasked) */
20927   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20928   /* moved CSE1 up */
20929   /* a &= (0x7f<<14)|(0x7f); */
20930   b &= SLOT_2_0;
20931   s = a;
20932   /* s: p0<<14 | p2 (masked) */
20933
20934   p++;
20935   a = a<<14;
20936   a |= *p;
20937   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20938   if (!(a&0x80))
20939   {
20940     /* we can skip these cause they were (effectively) done above in calc'ing s */
20941     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20942     /* b &= (0x7f<<14)|(0x7f); */
20943     b = b<<7;
20944     a |= b;
20945     s = s>>18;
20946     *v = ((u64)s)<<32 | a;
20947     return 5;
20948   }
20949
20950   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20951   s = s<<7;
20952   s |= b;
20953   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20954
20955   p++;
20956   b = b<<14;
20957   b |= *p;
20958   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20959   if (!(b&0x80))
20960   {
20961     /* we can skip this cause it was (effectively) done above in calc'ing s */
20962     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20963     a &= SLOT_2_0;
20964     a = a<<7;
20965     a |= b;
20966     s = s>>18;
20967     *v = ((u64)s)<<32 | a;
20968     return 6;
20969   }
20970
20971   p++;
20972   a = a<<14;
20973   a |= *p;
20974   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20975   if (!(a&0x80))
20976   {
20977     a &= SLOT_4_2_0;
20978     b &= SLOT_2_0;
20979     b = b<<7;
20980     a |= b;
20981     s = s>>11;
20982     *v = ((u64)s)<<32 | a;
20983     return 7;
20984   }
20985
20986   /* CSE2 from below */
20987   a &= SLOT_2_0;
20988   p++;
20989   b = b<<14;
20990   b |= *p;
20991   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20992   if (!(b&0x80))
20993   {
20994     b &= SLOT_4_2_0;
20995     /* moved CSE2 up */
20996     /* a &= (0x7f<<14)|(0x7f); */
20997     a = a<<7;
20998     a |= b;
20999     s = s>>4;
21000     *v = ((u64)s)<<32 | a;
21001     return 8;
21002   }
21003
21004   p++;
21005   a = a<<15;
21006   a |= *p;
21007   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21008
21009   /* moved CSE2 up */
21010   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21011   b &= SLOT_2_0;
21012   b = b<<8;
21013   a |= b;
21014
21015   s = s<<4;
21016   b = p[-4];
21017   b &= 0x7f;
21018   b = b>>3;
21019   s |= b;
21020
21021   *v = ((u64)s)<<32 | a;
21022
21023   return 9;
21024 }
21025
21026 /*
21027 ** Read a 32-bit variable-length integer from memory starting at p[0].
21028 ** Return the number of bytes read.  The value is stored in *v.
21029 **
21030 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21031 ** integer, then set *v to 0xffffffff.
21032 **
21033 ** A MACRO version, getVarint32, is provided which inlines the 
21034 ** single-byte case.  All code should use the MACRO version as 
21035 ** this function assumes the single-byte case has already been handled.
21036 */
21037 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21038   u32 a,b;
21039
21040   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21041   ** by the getVarin32() macro */
21042   a = *p;
21043   /* a: p0 (unmasked) */
21044 #ifndef getVarint32
21045   if (!(a&0x80))
21046   {
21047     /* Values between 0 and 127 */
21048     *v = a;
21049     return 1;
21050   }
21051 #endif
21052
21053   /* The 2-byte case */
21054   p++;
21055   b = *p;
21056   /* b: p1 (unmasked) */
21057   if (!(b&0x80))
21058   {
21059     /* Values between 128 and 16383 */
21060     a &= 0x7f;
21061     a = a<<7;
21062     *v = a | b;
21063     return 2;
21064   }
21065
21066   /* The 3-byte case */
21067   p++;
21068   a = a<<14;
21069   a |= *p;
21070   /* a: p0<<14 | p2 (unmasked) */
21071   if (!(a&0x80))
21072   {
21073     /* Values between 16384 and 2097151 */
21074     a &= (0x7f<<14)|(0x7f);
21075     b &= 0x7f;
21076     b = b<<7;
21077     *v = a | b;
21078     return 3;
21079   }
21080
21081   /* A 32-bit varint is used to store size information in btrees.
21082   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21083   ** A 3-byte varint is sufficient, for example, to record the size
21084   ** of a 1048569-byte BLOB or string.
21085   **
21086   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21087   ** rare larger cases can be handled by the slower 64-bit varint
21088   ** routine.
21089   */
21090 #if 1
21091   {
21092     u64 v64;
21093     u8 n;
21094
21095     p -= 2;
21096     n = sqlite3GetVarint(p, &v64);
21097     assert( n>3 && n<=9 );
21098     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21099       *v = 0xffffffff;
21100     }else{
21101       *v = (u32)v64;
21102     }
21103     return n;
21104   }
21105
21106 #else
21107   /* For following code (kept for historical record only) shows an
21108   ** unrolling for the 3- and 4-byte varint cases.  This code is
21109   ** slightly faster, but it is also larger and much harder to test.
21110   */
21111   p++;
21112   b = b<<14;
21113   b |= *p;
21114   /* b: p1<<14 | p3 (unmasked) */
21115   if (!(b&0x80))
21116   {
21117     /* Values between 2097152 and 268435455 */
21118     b &= (0x7f<<14)|(0x7f);
21119     a &= (0x7f<<14)|(0x7f);
21120     a = a<<7;
21121     *v = a | b;
21122     return 4;
21123   }
21124
21125   p++;
21126   a = a<<14;
21127   a |= *p;
21128   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21129   if (!(a&0x80))
21130   {
21131     /* Values  between 268435456 and 34359738367 */
21132     a &= SLOT_4_2_0;
21133     b &= SLOT_4_2_0;
21134     b = b<<7;
21135     *v = a | b;
21136     return 5;
21137   }
21138
21139   /* We can only reach this point when reading a corrupt database
21140   ** file.  In that case we are not in any hurry.  Use the (relatively
21141   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21142   ** value. */
21143   {
21144     u64 v64;
21145     u8 n;
21146
21147     p -= 4;
21148     n = sqlite3GetVarint(p, &v64);
21149     assert( n>5 && n<=9 );
21150     *v = (u32)v64;
21151     return n;
21152   }
21153 #endif
21154 }
21155
21156 /*
21157 ** Return the number of bytes that will be needed to store the given
21158 ** 64-bit integer.
21159 */
21160 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21161   int i = 0;
21162   do{
21163     i++;
21164     v >>= 7;
21165   }while( v!=0 && ALWAYS(i<9) );
21166   return i;
21167 }
21168
21169
21170 /*
21171 ** Read or write a four-byte big-endian integer value.
21172 */
21173 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21174   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21175 }
21176 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21177   p[0] = (u8)(v>>24);
21178   p[1] = (u8)(v>>16);
21179   p[2] = (u8)(v>>8);
21180   p[3] = (u8)v;
21181 }
21182
21183
21184
21185 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21186 /*
21187 ** Translate a single byte of Hex into an integer.
21188 ** This routine only works if h really is a valid hexadecimal
21189 ** character:  0..9a..fA..F
21190 */
21191 static u8 hexToInt(int h){
21192   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21193 #ifdef SQLITE_ASCII
21194   h += 9*(1&(h>>6));
21195 #endif
21196 #ifdef SQLITE_EBCDIC
21197   h += 9*(1&~(h>>4));
21198 #endif
21199   return (u8)(h & 0xf);
21200 }
21201 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21202
21203 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21204 /*
21205 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21206 ** value.  Return a pointer to its binary value.  Space to hold the
21207 ** binary value has been obtained from malloc and must be freed by
21208 ** the calling routine.
21209 */
21210 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21211   char *zBlob;
21212   int i;
21213
21214   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21215   n--;
21216   if( zBlob ){
21217     for(i=0; i<n; i+=2){
21218       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21219     }
21220     zBlob[i/2] = 0;
21221   }
21222   return zBlob;
21223 }
21224 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21225
21226 /*
21227 ** Log an error that is an API call on a connection pointer that should
21228 ** not have been used.  The "type" of connection pointer is given as the
21229 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21230 */
21231 static void logBadConnection(const char *zType){
21232   sqlite3_log(SQLITE_MISUSE, 
21233      "API call with %s database connection pointer",
21234      zType
21235   );
21236 }
21237
21238 /*
21239 ** Check to make sure we have a valid db pointer.  This test is not
21240 ** foolproof but it does provide some measure of protection against
21241 ** misuse of the interface such as passing in db pointers that are
21242 ** NULL or which have been previously closed.  If this routine returns
21243 ** 1 it means that the db pointer is valid and 0 if it should not be
21244 ** dereferenced for any reason.  The calling function should invoke
21245 ** SQLITE_MISUSE immediately.
21246 **
21247 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21248 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21249 ** open properly and is not fit for general use but which can be
21250 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21251 */
21252 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21253   u32 magic;
21254   if( db==0 ){
21255     logBadConnection("NULL");
21256     return 0;
21257   }
21258   magic = db->magic;
21259   if( magic!=SQLITE_MAGIC_OPEN ){
21260     if( sqlite3SafetyCheckSickOrOk(db) ){
21261       testcase( sqlite3GlobalConfig.xLog!=0 );
21262       logBadConnection("unopened");
21263     }
21264     return 0;
21265   }else{
21266     return 1;
21267   }
21268 }
21269 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21270   u32 magic;
21271   magic = db->magic;
21272   if( magic!=SQLITE_MAGIC_SICK &&
21273       magic!=SQLITE_MAGIC_OPEN &&
21274       magic!=SQLITE_MAGIC_BUSY ){
21275     testcase( sqlite3GlobalConfig.xLog!=0 );
21276     logBadConnection("invalid");
21277     return 0;
21278   }else{
21279     return 1;
21280   }
21281 }
21282
21283 /*
21284 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21285 ** the other 64-bit signed integer at *pA and store the result in *pA.
21286 ** Return 0 on success.  Or if the operation would have resulted in an
21287 ** overflow, leave *pA unchanged and return 1.
21288 */
21289 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21290   i64 iA = *pA;
21291   testcase( iA==0 ); testcase( iA==1 );
21292   testcase( iB==-1 ); testcase( iB==0 );
21293   if( iB>=0 ){
21294     testcase( iA>0 && LARGEST_INT64 - iA == iB );
21295     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21296     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21297     *pA += iB;
21298   }else{
21299     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21300     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21301     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21302     *pA += iB;
21303   }
21304   return 0; 
21305 }
21306 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21307   testcase( iB==SMALLEST_INT64+1 );
21308   if( iB==SMALLEST_INT64 ){
21309     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21310     if( (*pA)>=0 ) return 1;
21311     *pA -= iB;
21312     return 0;
21313   }else{
21314     return sqlite3AddInt64(pA, -iB);
21315   }
21316 }
21317 #define TWOPOWER32 (((i64)1)<<32)
21318 #define TWOPOWER31 (((i64)1)<<31)
21319 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21320   i64 iA = *pA;
21321   i64 iA1, iA0, iB1, iB0, r;
21322
21323   iA1 = iA/TWOPOWER32;
21324   iA0 = iA % TWOPOWER32;
21325   iB1 = iB/TWOPOWER32;
21326   iB0 = iB % TWOPOWER32;
21327   if( iA1*iB1 != 0 ) return 1;
21328   assert( iA1*iB0==0 || iA0*iB1==0 );
21329   r = iA1*iB0 + iA0*iB1;
21330   testcase( r==(-TWOPOWER31)-1 );
21331   testcase( r==(-TWOPOWER31) );
21332   testcase( r==TWOPOWER31 );
21333   testcase( r==TWOPOWER31-1 );
21334   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21335   r *= TWOPOWER32;
21336   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21337   *pA = r;
21338   return 0;
21339 }
21340
21341 /*
21342 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
21343 ** if the integer has a value of -2147483648, return +2147483647
21344 */
21345 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21346   if( x>=0 ) return x;
21347   if( x==(int)0x80000000 ) return 0x7fffffff;
21348   return -x;
21349 }
21350
21351 /************** End of util.c ************************************************/
21352 /************** Begin file hash.c ********************************************/
21353 /*
21354 ** 2001 September 22
21355 **
21356 ** The author disclaims copyright to this source code.  In place of
21357 ** a legal notice, here is a blessing:
21358 **
21359 **    May you do good and not evil.
21360 **    May you find forgiveness for yourself and forgive others.
21361 **    May you share freely, never taking more than you give.
21362 **
21363 *************************************************************************
21364 ** This is the implementation of generic hash-tables
21365 ** used in SQLite.
21366 */
21367
21368 /* Turn bulk memory into a hash table object by initializing the
21369 ** fields of the Hash structure.
21370 **
21371 ** "pNew" is a pointer to the hash table that is to be initialized.
21372 */
21373 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21374   assert( pNew!=0 );
21375   pNew->first = 0;
21376   pNew->count = 0;
21377   pNew->htsize = 0;
21378   pNew->ht = 0;
21379 }
21380
21381 /* Remove all entries from a hash table.  Reclaim all memory.
21382 ** Call this routine to delete a hash table or to reset a hash table
21383 ** to the empty state.
21384 */
21385 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21386   HashElem *elem;         /* For looping over all elements of the table */
21387
21388   assert( pH!=0 );
21389   elem = pH->first;
21390   pH->first = 0;
21391   sqlite3_free(pH->ht);
21392   pH->ht = 0;
21393   pH->htsize = 0;
21394   while( elem ){
21395     HashElem *next_elem = elem->next;
21396     sqlite3_free(elem);
21397     elem = next_elem;
21398   }
21399   pH->count = 0;
21400 }
21401
21402 /*
21403 ** The hashing function.
21404 */
21405 static unsigned int strHash(const char *z, int nKey){
21406   int h = 0;
21407   assert( nKey>=0 );
21408   while( nKey > 0  ){
21409     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21410     nKey--;
21411   }
21412   return h;
21413 }
21414
21415
21416 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21417 ** insert pNew into the pEntry hash bucket.
21418 */
21419 static void insertElement(
21420   Hash *pH,              /* The complete hash table */
21421   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21422   HashElem *pNew         /* The element to be inserted */
21423 ){
21424   HashElem *pHead;       /* First element already in pEntry */
21425   if( pEntry ){
21426     pHead = pEntry->count ? pEntry->chain : 0;
21427     pEntry->count++;
21428     pEntry->chain = pNew;
21429   }else{
21430     pHead = 0;
21431   }
21432   if( pHead ){
21433     pNew->next = pHead;
21434     pNew->prev = pHead->prev;
21435     if( pHead->prev ){ pHead->prev->next = pNew; }
21436     else             { pH->first = pNew; }
21437     pHead->prev = pNew;
21438   }else{
21439     pNew->next = pH->first;
21440     if( pH->first ){ pH->first->prev = pNew; }
21441     pNew->prev = 0;
21442     pH->first = pNew;
21443   }
21444 }
21445
21446
21447 /* Resize the hash table so that it cantains "new_size" buckets.
21448 **
21449 ** The hash table might fail to resize if sqlite3_malloc() fails or
21450 ** if the new size is the same as the prior size.
21451 ** Return TRUE if the resize occurs and false if not.
21452 */
21453 static int rehash(Hash *pH, unsigned int new_size){
21454   struct _ht *new_ht;            /* The new hash table */
21455   HashElem *elem, *next_elem;    /* For looping over existing elements */
21456
21457 #if SQLITE_MALLOC_SOFT_LIMIT>0
21458   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21459     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21460   }
21461   if( new_size==pH->htsize ) return 0;
21462 #endif
21463
21464   /* The inability to allocates space for a larger hash table is
21465   ** a performance hit but it is not a fatal error.  So mark the
21466   ** allocation as a benign.
21467   */
21468   sqlite3BeginBenignMalloc();
21469   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21470   sqlite3EndBenignMalloc();
21471
21472   if( new_ht==0 ) return 0;
21473   sqlite3_free(pH->ht);
21474   pH->ht = new_ht;
21475   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21476   memset(new_ht, 0, new_size*sizeof(struct _ht));
21477   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21478     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21479     next_elem = elem->next;
21480     insertElement(pH, &new_ht[h], elem);
21481   }
21482   return 1;
21483 }
21484
21485 /* This function (for internal use only) locates an element in an
21486 ** hash table that matches the given key.  The hash for this key has
21487 ** already been computed and is passed as the 4th parameter.
21488 */
21489 static HashElem *findElementGivenHash(
21490   const Hash *pH,     /* The pH to be searched */
21491   const char *pKey,   /* The key we are searching for */
21492   int nKey,           /* Bytes in key (not counting zero terminator) */
21493   unsigned int h      /* The hash for this key. */
21494 ){
21495   HashElem *elem;                /* Used to loop thru the element list */
21496   int count;                     /* Number of elements left to test */
21497
21498   if( pH->ht ){
21499     struct _ht *pEntry = &pH->ht[h];
21500     elem = pEntry->chain;
21501     count = pEntry->count;
21502   }else{
21503     elem = pH->first;
21504     count = pH->count;
21505   }
21506   while( count-- && ALWAYS(elem) ){
21507     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21508       return elem;
21509     }
21510     elem = elem->next;
21511   }
21512   return 0;
21513 }
21514
21515 /* Remove a single entry from the hash table given a pointer to that
21516 ** element and a hash on the element's key.
21517 */
21518 static void removeElementGivenHash(
21519   Hash *pH,         /* The pH containing "elem" */
21520   HashElem* elem,   /* The element to be removed from the pH */
21521   unsigned int h    /* Hash value for the element */
21522 ){
21523   struct _ht *pEntry;
21524   if( elem->prev ){
21525     elem->prev->next = elem->next; 
21526   }else{
21527     pH->first = elem->next;
21528   }
21529   if( elem->next ){
21530     elem->next->prev = elem->prev;
21531   }
21532   if( pH->ht ){
21533     pEntry = &pH->ht[h];
21534     if( pEntry->chain==elem ){
21535       pEntry->chain = elem->next;
21536     }
21537     pEntry->count--;
21538     assert( pEntry->count>=0 );
21539   }
21540   sqlite3_free( elem );
21541   pH->count--;
21542   if( pH->count<=0 ){
21543     assert( pH->first==0 );
21544     assert( pH->count==0 );
21545     sqlite3HashClear(pH);
21546   }
21547 }
21548
21549 /* Attempt to locate an element of the hash table pH with a key
21550 ** that matches pKey,nKey.  Return the data for this element if it is
21551 ** found, or NULL if there is no match.
21552 */
21553 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21554   HashElem *elem;    /* The element that matches key */
21555   unsigned int h;    /* A hash on key */
21556
21557   assert( pH!=0 );
21558   assert( pKey!=0 );
21559   assert( nKey>=0 );
21560   if( pH->ht ){
21561     h = strHash(pKey, nKey) % pH->htsize;
21562   }else{
21563     h = 0;
21564   }
21565   elem = findElementGivenHash(pH, pKey, nKey, h);
21566   return elem ? elem->data : 0;
21567 }
21568
21569 /* Insert an element into the hash table pH.  The key is pKey,nKey
21570 ** and the data is "data".
21571 **
21572 ** If no element exists with a matching key, then a new
21573 ** element is created and NULL is returned.
21574 **
21575 ** If another element already exists with the same key, then the
21576 ** new data replaces the old data and the old data is returned.
21577 ** The key is not copied in this instance.  If a malloc fails, then
21578 ** the new data is returned and the hash table is unchanged.
21579 **
21580 ** If the "data" parameter to this function is NULL, then the
21581 ** element corresponding to "key" is removed from the hash table.
21582 */
21583 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21584   unsigned int h;       /* the hash of the key modulo hash table size */
21585   HashElem *elem;       /* Used to loop thru the element list */
21586   HashElem *new_elem;   /* New element added to the pH */
21587
21588   assert( pH!=0 );
21589   assert( pKey!=0 );
21590   assert( nKey>=0 );
21591   if( pH->htsize ){
21592     h = strHash(pKey, nKey) % pH->htsize;
21593   }else{
21594     h = 0;
21595   }
21596   elem = findElementGivenHash(pH,pKey,nKey,h);
21597   if( elem ){
21598     void *old_data = elem->data;
21599     if( data==0 ){
21600       removeElementGivenHash(pH,elem,h);
21601     }else{
21602       elem->data = data;
21603       elem->pKey = pKey;
21604       assert(nKey==elem->nKey);
21605     }
21606     return old_data;
21607   }
21608   if( data==0 ) return 0;
21609   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21610   if( new_elem==0 ) return data;
21611   new_elem->pKey = pKey;
21612   new_elem->nKey = nKey;
21613   new_elem->data = data;
21614   pH->count++;
21615   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21616     if( rehash(pH, pH->count*2) ){
21617       assert( pH->htsize>0 );
21618       h = strHash(pKey, nKey) % pH->htsize;
21619     }
21620   }
21621   if( pH->ht ){
21622     insertElement(pH, &pH->ht[h], new_elem);
21623   }else{
21624     insertElement(pH, 0, new_elem);
21625   }
21626   return 0;
21627 }
21628
21629 /************** End of hash.c ************************************************/
21630 /************** Begin file opcodes.c *****************************************/
21631 /* Automatically generated.  Do not edit */
21632 /* See the mkopcodec.awk script for details. */
21633 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21634 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21635  static const char *const azName[] = { "?",
21636      /*   1 */ "Goto",
21637      /*   2 */ "Gosub",
21638      /*   3 */ "Return",
21639      /*   4 */ "Yield",
21640      /*   5 */ "HaltIfNull",
21641      /*   6 */ "Halt",
21642      /*   7 */ "Integer",
21643      /*   8 */ "Int64",
21644      /*   9 */ "String",
21645      /*  10 */ "Null",
21646      /*  11 */ "Blob",
21647      /*  12 */ "Variable",
21648      /*  13 */ "Move",
21649      /*  14 */ "Copy",
21650      /*  15 */ "SCopy",
21651      /*  16 */ "ResultRow",
21652      /*  17 */ "CollSeq",
21653      /*  18 */ "Function",
21654      /*  19 */ "Not",
21655      /*  20 */ "AddImm",
21656      /*  21 */ "MustBeInt",
21657      /*  22 */ "RealAffinity",
21658      /*  23 */ "Permutation",
21659      /*  24 */ "Compare",
21660      /*  25 */ "Jump",
21661      /*  26 */ "If",
21662      /*  27 */ "IfNot",
21663      /*  28 */ "Column",
21664      /*  29 */ "Affinity",
21665      /*  30 */ "MakeRecord",
21666      /*  31 */ "Count",
21667      /*  32 */ "Savepoint",
21668      /*  33 */ "AutoCommit",
21669      /*  34 */ "Transaction",
21670      /*  35 */ "ReadCookie",
21671      /*  36 */ "SetCookie",
21672      /*  37 */ "VerifyCookie",
21673      /*  38 */ "OpenRead",
21674      /*  39 */ "OpenWrite",
21675      /*  40 */ "OpenAutoindex",
21676      /*  41 */ "OpenEphemeral",
21677      /*  42 */ "OpenPseudo",
21678      /*  43 */ "Close",
21679      /*  44 */ "SeekLt",
21680      /*  45 */ "SeekLe",
21681      /*  46 */ "SeekGe",
21682      /*  47 */ "SeekGt",
21683      /*  48 */ "Seek",
21684      /*  49 */ "NotFound",
21685      /*  50 */ "Found",
21686      /*  51 */ "IsUnique",
21687      /*  52 */ "NotExists",
21688      /*  53 */ "Sequence",
21689      /*  54 */ "NewRowid",
21690      /*  55 */ "Insert",
21691      /*  56 */ "InsertInt",
21692      /*  57 */ "Delete",
21693      /*  58 */ "ResetCount",
21694      /*  59 */ "RowKey",
21695      /*  60 */ "RowData",
21696      /*  61 */ "Rowid",
21697      /*  62 */ "NullRow",
21698      /*  63 */ "Last",
21699      /*  64 */ "Sort",
21700      /*  65 */ "Rewind",
21701      /*  66 */ "Prev",
21702      /*  67 */ "Next",
21703      /*  68 */ "Or",
21704      /*  69 */ "And",
21705      /*  70 */ "IdxInsert",
21706      /*  71 */ "IdxDelete",
21707      /*  72 */ "IdxRowid",
21708      /*  73 */ "IsNull",
21709      /*  74 */ "NotNull",
21710      /*  75 */ "Ne",
21711      /*  76 */ "Eq",
21712      /*  77 */ "Gt",
21713      /*  78 */ "Le",
21714      /*  79 */ "Lt",
21715      /*  80 */ "Ge",
21716      /*  81 */ "IdxLT",
21717      /*  82 */ "BitAnd",
21718      /*  83 */ "BitOr",
21719      /*  84 */ "ShiftLeft",
21720      /*  85 */ "ShiftRight",
21721      /*  86 */ "Add",
21722      /*  87 */ "Subtract",
21723      /*  88 */ "Multiply",
21724      /*  89 */ "Divide",
21725      /*  90 */ "Remainder",
21726      /*  91 */ "Concat",
21727      /*  92 */ "IdxGE",
21728      /*  93 */ "BitNot",
21729      /*  94 */ "String8",
21730      /*  95 */ "Destroy",
21731      /*  96 */ "Clear",
21732      /*  97 */ "CreateIndex",
21733      /*  98 */ "CreateTable",
21734      /*  99 */ "ParseSchema",
21735      /* 100 */ "LoadAnalysis",
21736      /* 101 */ "DropTable",
21737      /* 102 */ "DropIndex",
21738      /* 103 */ "DropTrigger",
21739      /* 104 */ "IntegrityCk",
21740      /* 105 */ "RowSetAdd",
21741      /* 106 */ "RowSetRead",
21742      /* 107 */ "RowSetTest",
21743      /* 108 */ "Program",
21744      /* 109 */ "Param",
21745      /* 110 */ "FkCounter",
21746      /* 111 */ "FkIfZero",
21747      /* 112 */ "MemMax",
21748      /* 113 */ "IfPos",
21749      /* 114 */ "IfNeg",
21750      /* 115 */ "IfZero",
21751      /* 116 */ "AggStep",
21752      /* 117 */ "AggFinal",
21753      /* 118 */ "Checkpoint",
21754      /* 119 */ "JournalMode",
21755      /* 120 */ "Vacuum",
21756      /* 121 */ "IncrVacuum",
21757      /* 122 */ "Expire",
21758      /* 123 */ "TableLock",
21759      /* 124 */ "VBegin",
21760      /* 125 */ "VCreate",
21761      /* 126 */ "VDestroy",
21762      /* 127 */ "VOpen",
21763      /* 128 */ "VFilter",
21764      /* 129 */ "VColumn",
21765      /* 130 */ "Real",
21766      /* 131 */ "VNext",
21767      /* 132 */ "VRename",
21768      /* 133 */ "VUpdate",
21769      /* 134 */ "Pagecount",
21770      /* 135 */ "MaxPgcnt",
21771      /* 136 */ "Trace",
21772      /* 137 */ "Noop",
21773      /* 138 */ "Explain",
21774      /* 139 */ "NotUsed_139",
21775      /* 140 */ "NotUsed_140",
21776      /* 141 */ "ToText",
21777      /* 142 */ "ToBlob",
21778      /* 143 */ "ToNumeric",
21779      /* 144 */ "ToInt",
21780      /* 145 */ "ToReal",
21781   };
21782   return azName[i];
21783 }
21784 #endif
21785
21786 /************** End of opcodes.c *********************************************/
21787 /************** Begin file os_os2.c ******************************************/
21788 /*
21789 ** 2006 Feb 14
21790 **
21791 ** The author disclaims copyright to this source code.  In place of
21792 ** a legal notice, here is a blessing:
21793 **
21794 **    May you do good and not evil.
21795 **    May you find forgiveness for yourself and forgive others.
21796 **    May you share freely, never taking more than you give.
21797 **
21798 ******************************************************************************
21799 **
21800 ** This file contains code that is specific to OS/2.
21801 */
21802
21803
21804 #if SQLITE_OS_OS2
21805
21806 /*
21807 ** A Note About Memory Allocation:
21808 **
21809 ** This driver uses malloc()/free() directly rather than going through
21810 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21811 ** are designed for use on embedded systems where memory is scarce and
21812 ** malloc failures happen frequently.  OS/2 does not typically run on
21813 ** embedded systems, and when it does the developers normally have bigger
21814 ** problems to worry about than running out of memory.  So there is not
21815 ** a compelling need to use the wrappers.
21816 **
21817 ** But there is a good reason to not use the wrappers.  If we use the
21818 ** wrappers then we will get simulated malloc() failures within this
21819 ** driver.  And that causes all kinds of problems for our tests.  We
21820 ** could enhance SQLite to deal with simulated malloc failures within
21821 ** the OS driver, but the code to deal with those failure would not
21822 ** be exercised on Linux (which does not need to malloc() in the driver)
21823 ** and so we would have difficulty writing coverage tests for that
21824 ** code.  Better to leave the code out, we think.
21825 **
21826 ** The point of this discussion is as follows:  When creating a new
21827 ** OS layer for an embedded system, if you use this file as an example,
21828 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
21829 ** desktops but not so well in embedded systems.
21830 */
21831
21832 /*
21833 ** Macros used to determine whether or not to use threads.
21834 */
21835 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21836 # define SQLITE_OS2_THREADS 1
21837 #endif
21838
21839 /*
21840 ** Include code that is common to all os_*.c files
21841 */
21842 /************** Include os_common.h in the middle of os_os2.c ****************/
21843 /************** Begin file os_common.h ***************************************/
21844 /*
21845 ** 2004 May 22
21846 **
21847 ** The author disclaims copyright to this source code.  In place of
21848 ** a legal notice, here is a blessing:
21849 **
21850 **    May you do good and not evil.
21851 **    May you find forgiveness for yourself and forgive others.
21852 **    May you share freely, never taking more than you give.
21853 **
21854 ******************************************************************************
21855 **
21856 ** This file contains macros and a little bit of code that is common to
21857 ** all of the platform-specific files (os_*.c) and is #included into those
21858 ** files.
21859 **
21860 ** This file should be #included by the os_*.c files only.  It is not a
21861 ** general purpose header file.
21862 */
21863 #ifndef _OS_COMMON_H_
21864 #define _OS_COMMON_H_
21865
21866 /*
21867 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21868 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21869 ** switch.  The following code should catch this problem at compile-time.
21870 */
21871 #ifdef MEMORY_DEBUG
21872 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21873 #endif
21874
21875 #ifdef SQLITE_DEBUG
21876 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21877 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21878 #else
21879 #define OSTRACE(X)
21880 #endif
21881
21882 /*
21883 ** Macros for performance tracing.  Normally turned off.  Only works
21884 ** on i486 hardware.
21885 */
21886 #ifdef SQLITE_PERFORMANCE_TRACE
21887
21888 /* 
21889 ** hwtime.h contains inline assembler code for implementing 
21890 ** high-performance timing routines.
21891 */
21892 /************** Include hwtime.h in the middle of os_common.h ****************/
21893 /************** Begin file hwtime.h ******************************************/
21894 /*
21895 ** 2008 May 27
21896 **
21897 ** The author disclaims copyright to this source code.  In place of
21898 ** a legal notice, here is a blessing:
21899 **
21900 **    May you do good and not evil.
21901 **    May you find forgiveness for yourself and forgive others.
21902 **    May you share freely, never taking more than you give.
21903 **
21904 ******************************************************************************
21905 **
21906 ** This file contains inline asm code for retrieving "high-performance"
21907 ** counters for x86 class CPUs.
21908 */
21909 #ifndef _HWTIME_H_
21910 #define _HWTIME_H_
21911
21912 /*
21913 ** The following routine only works on pentium-class (or newer) processors.
21914 ** It uses the RDTSC opcode to read the cycle count value out of the
21915 ** processor and returns that value.  This can be used for high-res
21916 ** profiling.
21917 */
21918 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21919       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21920
21921   #if defined(__GNUC__)
21922
21923   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21924      unsigned int lo, hi;
21925      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21926      return (sqlite_uint64)hi << 32 | lo;
21927   }
21928
21929   #elif defined(_MSC_VER)
21930
21931   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21932      __asm {
21933         rdtsc
21934         ret       ; return value at EDX:EAX
21935      }
21936   }
21937
21938   #endif
21939
21940 #elif (defined(__GNUC__) && defined(__x86_64__))
21941
21942   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21943       unsigned long val;
21944       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21945       return val;
21946   }
21947  
21948 #elif (defined(__GNUC__) && defined(__ppc__))
21949
21950   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21951       unsigned long long retval;
21952       unsigned long junk;
21953       __asm__ __volatile__ ("\n\
21954           1:      mftbu   %1\n\
21955                   mftb    %L0\n\
21956                   mftbu   %0\n\
21957                   cmpw    %0,%1\n\
21958                   bne     1b"
21959                   : "=r" (retval), "=r" (junk));
21960       return retval;
21961   }
21962
21963 #else
21964
21965   #error Need implementation of sqlite3Hwtime() for your platform.
21966
21967   /*
21968   ** To compile without implementing sqlite3Hwtime() for your platform,
21969   ** you can remove the above #error and use the following
21970   ** stub function.  You will lose timing support for many
21971   ** of the debugging and testing utilities, but it should at
21972   ** least compile and run.
21973   */
21974 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21975
21976 #endif
21977
21978 #endif /* !defined(_HWTIME_H_) */
21979
21980 /************** End of hwtime.h **********************************************/
21981 /************** Continuing where we left off in os_common.h ******************/
21982
21983 static sqlite_uint64 g_start;
21984 static sqlite_uint64 g_elapsed;
21985 #define TIMER_START       g_start=sqlite3Hwtime()
21986 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21987 #define TIMER_ELAPSED     g_elapsed
21988 #else
21989 #define TIMER_START
21990 #define TIMER_END
21991 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21992 #endif
21993
21994 /*
21995 ** If we compile with the SQLITE_TEST macro set, then the following block
21996 ** of code will give us the ability to simulate a disk I/O error.  This
21997 ** is used for testing the I/O recovery logic.
21998 */
21999 #ifdef SQLITE_TEST
22000 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22001 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22002 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22003 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22004 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22005 SQLITE_API int sqlite3_diskfull_pending = 0;
22006 SQLITE_API int sqlite3_diskfull = 0;
22007 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22008 #define SimulateIOError(CODE)  \
22009   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22010        || sqlite3_io_error_pending-- == 1 )  \
22011               { local_ioerr(); CODE; }
22012 static void local_ioerr(){
22013   IOTRACE(("IOERR\n"));
22014   sqlite3_io_error_hit++;
22015   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22016 }
22017 #define SimulateDiskfullError(CODE) \
22018    if( sqlite3_diskfull_pending ){ \
22019      if( sqlite3_diskfull_pending == 1 ){ \
22020        local_ioerr(); \
22021        sqlite3_diskfull = 1; \
22022        sqlite3_io_error_hit = 1; \
22023        CODE; \
22024      }else{ \
22025        sqlite3_diskfull_pending--; \
22026      } \
22027    }
22028 #else
22029 #define SimulateIOErrorBenign(X)
22030 #define SimulateIOError(A)
22031 #define SimulateDiskfullError(A)
22032 #endif
22033
22034 /*
22035 ** When testing, keep a count of the number of open files.
22036 */
22037 #ifdef SQLITE_TEST
22038 SQLITE_API int sqlite3_open_file_count = 0;
22039 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22040 #else
22041 #define OpenCounter(X)
22042 #endif
22043
22044 #endif /* !defined(_OS_COMMON_H_) */
22045
22046 /************** End of os_common.h *******************************************/
22047 /************** Continuing where we left off in os_os2.c *********************/
22048
22049 /* Forward references */
22050 typedef struct os2File os2File;         /* The file structure */
22051 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22052 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22053
22054 /*
22055 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22056 ** protability layer.
22057 */
22058 struct os2File {
22059   const sqlite3_io_methods *pMethod;  /* Always the first entry */
22060   HFILE h;                  /* Handle for accessing the file */
22061   int flags;                /* Flags provided to os2Open() */
22062   int locktype;             /* Type of lock currently held on this file */
22063   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22064   char *zFullPathCp;        /* Full path name of this file */
22065   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22066 };
22067
22068 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22069
22070 /*
22071 ** Missing from some versions of the OS/2 toolkit -
22072 ** used to allocate from high memory if possible
22073 */
22074 #ifndef OBJ_ANY
22075 # define OBJ_ANY 0x00000400
22076 #endif
22077
22078 /*****************************************************************************
22079 ** The next group of routines implement the I/O methods specified
22080 ** by the sqlite3_io_methods object.
22081 ******************************************************************************/
22082
22083 /*
22084 ** Close a file.
22085 */
22086 static int os2Close( sqlite3_file *id ){
22087   APIRET rc;
22088   os2File *pFile = (os2File*)id;
22089
22090   assert( id!=0 );
22091   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22092
22093   rc = DosClose( pFile->h );
22094
22095   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22096     DosForceDelete( (PSZ)pFile->zFullPathCp );
22097
22098   free( pFile->zFullPathCp );
22099   pFile->zFullPathCp = NULL;
22100   pFile->locktype = NO_LOCK;
22101   pFile->h = (HFILE)-1;
22102   pFile->flags = 0;
22103
22104   OpenCounter( -1 );
22105   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22106 }
22107
22108 /*
22109 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22110 ** bytes were read successfully and SQLITE_IOERR if anything goes
22111 ** wrong.
22112 */
22113 static int os2Read(
22114   sqlite3_file *id,               /* File to read from */
22115   void *pBuf,                     /* Write content into this buffer */
22116   int amt,                        /* Number of bytes to read */
22117   sqlite3_int64 offset            /* Begin reading at this offset */
22118 ){
22119   ULONG fileLocation = 0L;
22120   ULONG got;
22121   os2File *pFile = (os2File*)id;
22122   assert( id!=0 );
22123   SimulateIOError( return SQLITE_IOERR_READ );
22124   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22125   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22126     return SQLITE_IOERR;
22127   }
22128   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22129     return SQLITE_IOERR_READ;
22130   }
22131   if( got == (ULONG)amt )
22132     return SQLITE_OK;
22133   else {
22134     /* Unread portions of the input buffer must be zero-filled */
22135     memset(&((char*)pBuf)[got], 0, amt-got);
22136     return SQLITE_IOERR_SHORT_READ;
22137   }
22138 }
22139
22140 /*
22141 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22142 ** or some other error code on failure.
22143 */
22144 static int os2Write(
22145   sqlite3_file *id,               /* File to write into */
22146   const void *pBuf,               /* The bytes to be written */
22147   int amt,                        /* Number of bytes to write */
22148   sqlite3_int64 offset            /* Offset into the file to begin writing at */
22149 ){
22150   ULONG fileLocation = 0L;
22151   APIRET rc = NO_ERROR;
22152   ULONG wrote;
22153   os2File *pFile = (os2File*)id;
22154   assert( id!=0 );
22155   SimulateIOError( return SQLITE_IOERR_WRITE );
22156   SimulateDiskfullError( return SQLITE_FULL );
22157   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22158   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22159     return SQLITE_IOERR;
22160   }
22161   assert( amt>0 );
22162   while( amt > 0 &&
22163          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22164          wrote > 0
22165   ){
22166     amt -= wrote;
22167     pBuf = &((char*)pBuf)[wrote];
22168   }
22169
22170   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22171 }
22172
22173 /*
22174 ** Truncate an open file to a specified size
22175 */
22176 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22177   APIRET rc;
22178   os2File *pFile = (os2File*)id;
22179   assert( id!=0 );
22180   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22181   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22182
22183   /* If the user has configured a chunk-size for this file, truncate the
22184   ** file so that it consists of an integer number of chunks (i.e. the
22185   ** actual file size after the operation may be larger than the requested
22186   ** size).
22187   */
22188   if( pFile->szChunk ){
22189     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22190   }
22191   
22192   rc = DosSetFileSize( pFile->h, nByte );
22193   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22194 }
22195
22196 #ifdef SQLITE_TEST
22197 /*
22198 ** Count the number of fullsyncs and normal syncs.  This is used to test
22199 ** that syncs and fullsyncs are occuring at the right times.
22200 */
22201 SQLITE_API int sqlite3_sync_count = 0;
22202 SQLITE_API int sqlite3_fullsync_count = 0;
22203 #endif
22204
22205 /*
22206 ** Make sure all writes to a particular file are committed to disk.
22207 */
22208 static int os2Sync( sqlite3_file *id, int flags ){
22209   os2File *pFile = (os2File*)id;
22210   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22211 #ifdef SQLITE_TEST
22212   if( flags & SQLITE_SYNC_FULL){
22213     sqlite3_fullsync_count++;
22214   }
22215   sqlite3_sync_count++;
22216 #endif
22217   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22218   ** no-op
22219   */
22220 #ifdef SQLITE_NO_SYNC
22221   UNUSED_PARAMETER(pFile);
22222   return SQLITE_OK;
22223 #else
22224   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22225 #endif
22226 }
22227
22228 /*
22229 ** Determine the current size of a file in bytes
22230 */
22231 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22232   APIRET rc = NO_ERROR;
22233   FILESTATUS3 fsts3FileInfo;
22234   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22235   assert( id!=0 );
22236   SimulateIOError( return SQLITE_IOERR_FSTAT );
22237   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22238   if( rc == NO_ERROR ){
22239     *pSize = fsts3FileInfo.cbFile;
22240     return SQLITE_OK;
22241   }else{
22242     return SQLITE_IOERR_FSTAT;
22243   }
22244 }
22245
22246 /*
22247 ** Acquire a reader lock.
22248 */
22249 static int getReadLock( os2File *pFile ){
22250   FILELOCK  LockArea,
22251             UnlockArea;
22252   APIRET res;
22253   memset(&LockArea, 0, sizeof(LockArea));
22254   memset(&UnlockArea, 0, sizeof(UnlockArea));
22255   LockArea.lOffset = SHARED_FIRST;
22256   LockArea.lRange = SHARED_SIZE;
22257   UnlockArea.lOffset = 0L;
22258   UnlockArea.lRange = 0L;
22259   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22260   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22261   return res;
22262 }
22263
22264 /*
22265 ** Undo a readlock
22266 */
22267 static int unlockReadLock( os2File *id ){
22268   FILELOCK  LockArea,
22269             UnlockArea;
22270   APIRET res;
22271   memset(&LockArea, 0, sizeof(LockArea));
22272   memset(&UnlockArea, 0, sizeof(UnlockArea));
22273   LockArea.lOffset = 0L;
22274   LockArea.lRange = 0L;
22275   UnlockArea.lOffset = SHARED_FIRST;
22276   UnlockArea.lRange = SHARED_SIZE;
22277   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22278   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22279   return res;
22280 }
22281
22282 /*
22283 ** Lock the file with the lock specified by parameter locktype - one
22284 ** of the following:
22285 **
22286 **     (1) SHARED_LOCK
22287 **     (2) RESERVED_LOCK
22288 **     (3) PENDING_LOCK
22289 **     (4) EXCLUSIVE_LOCK
22290 **
22291 ** Sometimes when requesting one lock state, additional lock states
22292 ** are inserted in between.  The locking might fail on one of the later
22293 ** transitions leaving the lock state different from what it started but
22294 ** still short of its goal.  The following chart shows the allowed
22295 ** transitions and the inserted intermediate states:
22296 **
22297 **    UNLOCKED -> SHARED
22298 **    SHARED -> RESERVED
22299 **    SHARED -> (PENDING) -> EXCLUSIVE
22300 **    RESERVED -> (PENDING) -> EXCLUSIVE
22301 **    PENDING -> EXCLUSIVE
22302 **
22303 ** This routine will only increase a lock.  The os2Unlock() routine
22304 ** erases all locks at once and returns us immediately to locking level 0.
22305 ** It is not possible to lower the locking level one step at a time.  You
22306 ** must go straight to locking level 0.
22307 */
22308 static int os2Lock( sqlite3_file *id, int locktype ){
22309   int rc = SQLITE_OK;       /* Return code from subroutines */
22310   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22311   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22312   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22313   FILELOCK  LockArea,
22314             UnlockArea;
22315   os2File *pFile = (os2File*)id;
22316   memset(&LockArea, 0, sizeof(LockArea));
22317   memset(&UnlockArea, 0, sizeof(UnlockArea));
22318   assert( pFile!=0 );
22319   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22320
22321   /* If there is already a lock of this type or more restrictive on the
22322   ** os2File, do nothing. Don't use the end_lock: exit path, as
22323   ** sqlite3_mutex_enter() hasn't been called yet.
22324   */
22325   if( pFile->locktype>=locktype ){
22326     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22327     return SQLITE_OK;
22328   }
22329
22330   /* Make sure the locking sequence is correct
22331   */
22332   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22333   assert( locktype!=PENDING_LOCK );
22334   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22335
22336   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22337   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22338   ** the PENDING_LOCK byte is temporary.
22339   */
22340   newLocktype = pFile->locktype;
22341   if( pFile->locktype==NO_LOCK
22342       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22343   ){
22344     LockArea.lOffset = PENDING_BYTE;
22345     LockArea.lRange = 1L;
22346     UnlockArea.lOffset = 0L;
22347     UnlockArea.lRange = 0L;
22348
22349     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22350     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22351     if( res == NO_ERROR ){
22352       gotPendingLock = 1;
22353       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22354     }
22355   }
22356
22357   /* Acquire a shared lock
22358   */
22359   if( locktype==SHARED_LOCK && res == NO_ERROR ){
22360     assert( pFile->locktype==NO_LOCK );
22361     res = getReadLock(pFile);
22362     if( res == NO_ERROR ){
22363       newLocktype = SHARED_LOCK;
22364     }
22365     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22366   }
22367
22368   /* Acquire a RESERVED lock
22369   */
22370   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22371     assert( pFile->locktype==SHARED_LOCK );
22372     LockArea.lOffset = RESERVED_BYTE;
22373     LockArea.lRange = 1L;
22374     UnlockArea.lOffset = 0L;
22375     UnlockArea.lRange = 0L;
22376     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22377     if( res == NO_ERROR ){
22378       newLocktype = RESERVED_LOCK;
22379     }
22380     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22381   }
22382
22383   /* Acquire a PENDING lock
22384   */
22385   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22386     newLocktype = PENDING_LOCK;
22387     gotPendingLock = 0;
22388     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22389                pFile->h ));
22390   }
22391
22392   /* Acquire an EXCLUSIVE lock
22393   */
22394   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22395     assert( pFile->locktype>=SHARED_LOCK );
22396     res = unlockReadLock(pFile);
22397     OSTRACE(( "unreadlock = %d\n", res ));
22398     LockArea.lOffset = SHARED_FIRST;
22399     LockArea.lRange = SHARED_SIZE;
22400     UnlockArea.lOffset = 0L;
22401     UnlockArea.lRange = 0L;
22402     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22403     if( res == NO_ERROR ){
22404       newLocktype = EXCLUSIVE_LOCK;
22405     }else{
22406       OSTRACE(( "OS/2 error-code = %d\n", res ));
22407       getReadLock(pFile);
22408     }
22409     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22410   }
22411
22412   /* If we are holding a PENDING lock that ought to be released, then
22413   ** release it now.
22414   */
22415   if( gotPendingLock && locktype==SHARED_LOCK ){
22416     int r;
22417     LockArea.lOffset = 0L;
22418     LockArea.lRange = 0L;
22419     UnlockArea.lOffset = PENDING_BYTE;
22420     UnlockArea.lRange = 1L;
22421     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22422     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22423   }
22424
22425   /* Update the state of the lock has held in the file descriptor then
22426   ** return the appropriate result code.
22427   */
22428   if( res == NO_ERROR ){
22429     rc = SQLITE_OK;
22430   }else{
22431     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22432               locktype, newLocktype ));
22433     rc = SQLITE_BUSY;
22434   }
22435   pFile->locktype = newLocktype;
22436   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22437   return rc;
22438 }
22439
22440 /*
22441 ** This routine checks if there is a RESERVED lock held on the specified
22442 ** file by this or any other process. If such a lock is held, return
22443 ** non-zero, otherwise zero.
22444 */
22445 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22446   int r = 0;
22447   os2File *pFile = (os2File*)id;
22448   assert( pFile!=0 );
22449   if( pFile->locktype>=RESERVED_LOCK ){
22450     r = 1;
22451     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22452   }else{
22453     FILELOCK  LockArea,
22454               UnlockArea;
22455     APIRET rc = NO_ERROR;
22456     memset(&LockArea, 0, sizeof(LockArea));
22457     memset(&UnlockArea, 0, sizeof(UnlockArea));
22458     LockArea.lOffset = RESERVED_BYTE;
22459     LockArea.lRange = 1L;
22460     UnlockArea.lOffset = 0L;
22461     UnlockArea.lRange = 0L;
22462     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22463     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22464     if( rc == NO_ERROR ){
22465       APIRET rcu = NO_ERROR; /* return code for unlocking */
22466       LockArea.lOffset = 0L;
22467       LockArea.lRange = 0L;
22468       UnlockArea.lOffset = RESERVED_BYTE;
22469       UnlockArea.lRange = 1L;
22470       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22471       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22472     }
22473     r = !(rc == NO_ERROR);
22474     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22475   }
22476   *pOut = r;
22477   return SQLITE_OK;
22478 }
22479
22480 /*
22481 ** Lower the locking level on file descriptor id to locktype.  locktype
22482 ** must be either NO_LOCK or SHARED_LOCK.
22483 **
22484 ** If the locking level of the file descriptor is already at or below
22485 ** the requested locking level, this routine is a no-op.
22486 **
22487 ** It is not possible for this routine to fail if the second argument
22488 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22489 ** might return SQLITE_IOERR;
22490 */
22491 static int os2Unlock( sqlite3_file *id, int locktype ){
22492   int type;
22493   os2File *pFile = (os2File*)id;
22494   APIRET rc = SQLITE_OK;
22495   APIRET res = NO_ERROR;
22496   FILELOCK  LockArea,
22497             UnlockArea;
22498   memset(&LockArea, 0, sizeof(LockArea));
22499   memset(&UnlockArea, 0, sizeof(UnlockArea));
22500   assert( pFile!=0 );
22501   assert( locktype<=SHARED_LOCK );
22502   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22503   type = pFile->locktype;
22504   if( type>=EXCLUSIVE_LOCK ){
22505     LockArea.lOffset = 0L;
22506     LockArea.lRange = 0L;
22507     UnlockArea.lOffset = SHARED_FIRST;
22508     UnlockArea.lRange = SHARED_SIZE;
22509     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22510     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22511     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22512       /* This should never happen.  We should always be able to
22513       ** reacquire the read lock */
22514       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22515       rc = SQLITE_IOERR_UNLOCK;
22516     }
22517   }
22518   if( type>=RESERVED_LOCK ){
22519     LockArea.lOffset = 0L;
22520     LockArea.lRange = 0L;
22521     UnlockArea.lOffset = RESERVED_BYTE;
22522     UnlockArea.lRange = 1L;
22523     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22524     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22525   }
22526   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22527     res = unlockReadLock(pFile);
22528     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22529               pFile->h, type, locktype, res ));
22530   }
22531   if( type>=PENDING_LOCK ){
22532     LockArea.lOffset = 0L;
22533     LockArea.lRange = 0L;
22534     UnlockArea.lOffset = PENDING_BYTE;
22535     UnlockArea.lRange = 1L;
22536     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22537     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22538   }
22539   pFile->locktype = locktype;
22540   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22541   return rc;
22542 }
22543
22544 /*
22545 ** Control and query of the open file handle.
22546 */
22547 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22548   switch( op ){
22549     case SQLITE_FCNTL_LOCKSTATE: {
22550       *(int*)pArg = ((os2File*)id)->locktype;
22551       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22552                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22553       return SQLITE_OK;
22554     }
22555     case SQLITE_FCNTL_CHUNK_SIZE: {
22556       ((os2File*)id)->szChunk = *(int*)pArg;
22557       return SQLITE_OK;
22558     }
22559     case SQLITE_FCNTL_SIZE_HINT: {
22560       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22561       SimulateIOErrorBenign(1);
22562       os2Truncate(id, sz);
22563       SimulateIOErrorBenign(0);
22564       return SQLITE_OK;
22565     }
22566     case SQLITE_FCNTL_SYNC_OMITTED: {
22567       return SQLITE_OK;
22568     }
22569   }
22570   return SQLITE_NOTFOUND;
22571 }
22572
22573 /*
22574 ** Return the sector size in bytes of the underlying block device for
22575 ** the specified file. This is almost always 512 bytes, but may be
22576 ** larger for some devices.
22577 **
22578 ** SQLite code assumes this function cannot fail. It also assumes that
22579 ** if two files are created in the same file-system directory (i.e.
22580 ** a database and its journal file) that the sector size will be the
22581 ** same for both.
22582 */
22583 static int os2SectorSize(sqlite3_file *id){
22584   UNUSED_PARAMETER(id);
22585   return SQLITE_DEFAULT_SECTOR_SIZE;
22586 }
22587
22588 /*
22589 ** Return a vector of device characteristics.
22590 */
22591 static int os2DeviceCharacteristics(sqlite3_file *id){
22592   UNUSED_PARAMETER(id);
22593   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22594 }
22595
22596
22597 /*
22598 ** Character set conversion objects used by conversion routines.
22599 */
22600 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22601 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22602
22603 /*
22604 ** Helper function to initialize the conversion objects from and to UTF-8.
22605 */
22606 static void initUconvObjects( void ){
22607   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22608     ucUtf8 = NULL;
22609   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22610     uclCp = NULL;
22611 }
22612
22613 /*
22614 ** Helper function to free the conversion objects from and to UTF-8.
22615 */
22616 static void freeUconvObjects( void ){
22617   if ( ucUtf8 )
22618     UniFreeUconvObject( ucUtf8 );
22619   if ( uclCp )
22620     UniFreeUconvObject( uclCp );
22621   ucUtf8 = NULL;
22622   uclCp = NULL;
22623 }
22624
22625 /*
22626 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22627 ** The two-step process: first convert the incoming UTF-8 string
22628 ** into UCS-2 and then from UCS-2 to the current codepage.
22629 ** The returned char pointer has to be freed.
22630 */
22631 static char *convertUtf8PathToCp( const char *in ){
22632   UniChar tempPath[CCHMAXPATH];
22633   char *out = (char *)calloc( CCHMAXPATH, 1 );
22634
22635   if( !out )
22636     return NULL;
22637
22638   if( !ucUtf8 || !uclCp )
22639     initUconvObjects();
22640
22641   /* determine string for the conversion of UTF-8 which is CP1208 */
22642   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22643     return out; /* if conversion fails, return the empty string */
22644
22645   /* conversion for current codepage which can be used for paths */
22646   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22647
22648   return out;
22649 }
22650
22651 /*
22652 ** Helper function to convert filenames from local codepage to UTF-8.
22653 ** The two-step process: first convert the incoming codepage-specific
22654 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22655 ** The returned char pointer has to be freed.
22656 **
22657 ** This function is non-static to be able to use this in shell.c and
22658 ** similar applications that take command line arguments.
22659 */
22660 char *convertCpPathToUtf8( const char *in ){
22661   UniChar tempPath[CCHMAXPATH];
22662   char *out = (char *)calloc( CCHMAXPATH, 1 );
22663
22664   if( !out )
22665     return NULL;
22666
22667   if( !ucUtf8 || !uclCp )
22668     initUconvObjects();
22669
22670   /* conversion for current codepage which can be used for paths */
22671   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22672     return out; /* if conversion fails, return the empty string */
22673
22674   /* determine string for the conversion of UTF-8 which is CP1208 */
22675   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22676
22677   return out;
22678 }
22679
22680
22681 #ifndef SQLITE_OMIT_WAL
22682
22683 /*
22684 ** Use main database file for interprocess locking. If un-defined
22685 ** a separate file is created for this purpose. The file will be
22686 ** used only to set file locks. There will be no data written to it.
22687 */
22688 #define SQLITE_OS2_NO_WAL_LOCK_FILE     
22689
22690 #if 0
22691 static void _ERR_TRACE( const char *fmt, ... ) {
22692   va_list  ap;
22693   va_start(ap, fmt);
22694   vfprintf(stderr, fmt, ap);
22695   fflush(stderr);
22696 }
22697 #define ERR_TRACE(rc, msg)        \
22698         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
22699 #else
22700 #define ERR_TRACE(rc, msg)
22701 #endif
22702
22703 /*
22704 ** Helper functions to obtain and relinquish the global mutex. The
22705 ** global mutex is used to protect os2ShmNodeList.
22706 **
22707 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
22708 ** is held when required. This function is only used as part of assert() 
22709 ** statements. e.g.
22710 **
22711 **   os2ShmEnterMutex()
22712 **     assert( os2ShmMutexHeld() );
22713 **   os2ShmLeaveMutex()
22714 */
22715 static void os2ShmEnterMutex(void){
22716   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22717 }
22718 static void os2ShmLeaveMutex(void){
22719   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22720 }
22721 #ifdef SQLITE_DEBUG
22722 static int os2ShmMutexHeld(void) {
22723   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22724 }
22725 int GetCurrentProcessId(void) {
22726   PPIB pib;
22727   DosGetInfoBlocks(NULL, &pib);
22728   return (int)pib->pib_ulpid;
22729 }
22730 #endif
22731
22732 /*
22733 ** Object used to represent a the shared memory area for a single log file.
22734 ** When multiple threads all reference the same log-summary, each thread has
22735 ** its own os2File object, but they all point to a single instance of this 
22736 ** object.  In other words, each log-summary is opened only once per process.
22737 **
22738 ** os2ShmMutexHeld() must be true when creating or destroying
22739 ** this object or while reading or writing the following fields:
22740 **
22741 **      nRef
22742 **      pNext 
22743 **
22744 ** The following fields are read-only after the object is created:
22745 ** 
22746 **      szRegion
22747 **      hLockFile
22748 **      shmBaseName
22749 **
22750 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
22751 ** os2ShmMutexHeld() is true when reading or writing any other field
22752 ** in this structure.
22753 **
22754 */
22755 struct os2ShmNode {
22756   sqlite3_mutex *mutex;      /* Mutex to access this object */
22757   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
22758
22759   int szRegion;              /* Size of shared-memory regions */
22760
22761   int nRegion;               /* Size of array apRegion */
22762   void **apRegion;           /* Array of pointers to shared-memory regions */
22763
22764   int nRef;                  /* Number of os2ShmLink objects pointing to this */
22765   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
22766
22767   HFILE hLockFile;           /* File used for inter-process memory locking */
22768   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
22769 };
22770
22771
22772 /*
22773 ** Structure used internally by this VFS to record the state of an
22774 ** open shared memory connection.
22775 **
22776 ** The following fields are initialized when this object is created and
22777 ** are read-only thereafter:
22778 **
22779 **    os2Shm.pShmNode
22780 **    os2Shm.id
22781 **
22782 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
22783 ** while accessing any read/write fields.
22784 */
22785 struct os2ShmLink {
22786   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
22787   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
22788   u32 sharedMask;            /* Mask of shared locks held */
22789   u32 exclMask;              /* Mask of exclusive locks held */
22790 #ifdef SQLITE_DEBUG
22791   u8 id;                     /* Id of this connection with its os2ShmNode */
22792 #endif
22793 };
22794
22795
22796 /*
22797 ** A global list of all os2ShmNode objects.
22798 **
22799 ** The os2ShmMutexHeld() must be true while reading or writing this list.
22800 */
22801 static os2ShmNode *os2ShmNodeList = NULL;
22802
22803 /*
22804 ** Constants used for locking
22805 */
22806 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
22807 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
22808 #else
22809 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
22810 #endif
22811
22812 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
22813
22814 /*
22815 ** Apply advisory locks for all n bytes beginning at ofst.
22816 */
22817 #define _SHM_UNLCK  1   /* no lock */
22818 #define _SHM_RDLCK  2   /* shared lock, no wait */
22819 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
22820 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
22821 static int os2ShmSystemLock(
22822   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
22823   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
22824   int ofst,             /* Offset to first byte to be locked/unlocked */
22825   int nByte             /* Number of bytes to lock or unlock */
22826 ){
22827   APIRET rc;
22828   FILELOCK area;
22829   ULONG mode, timeout;
22830
22831   /* Access to the os2ShmNode object is serialized by the caller */
22832   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
22833
22834   mode = 1;     /* shared lock */
22835   timeout = 0;  /* no wait */
22836   area.lOffset = ofst;
22837   area.lRange = nByte;
22838
22839   switch( lockType ) {
22840     case _SHM_WRLCK_WAIT:
22841       timeout = (ULONG)-1;      /* wait forever */
22842     case _SHM_WRLCK:
22843       mode = 0;                 /* exclusive lock */
22844     case _SHM_RDLCK:
22845       rc = DosSetFileLocks(pNode->hLockFile, 
22846                            NULL, &area, timeout, mode);
22847       break;
22848     /* case _SHM_UNLCK: */
22849     default:
22850       rc = DosSetFileLocks(pNode->hLockFile, 
22851                            &area, NULL, 0, 0);
22852       break;
22853   }
22854                           
22855   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
22856            pNode->hLockFile,
22857            rc==SQLITE_OK ? "ok" : "failed",
22858            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
22859            rc));
22860
22861   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
22862
22863   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
22864 }
22865
22866 /*
22867 ** Find an os2ShmNode in global list or allocate a new one, if not found.
22868 **
22869 ** This is not a VFS shared-memory method; it is a utility function called
22870 ** by VFS shared-memory methods.
22871 */
22872 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
22873   os2ShmLink *pLink;
22874   os2ShmNode *pNode;
22875   int cbShmName, rc = SQLITE_OK;
22876   char shmName[CCHMAXPATH + 30];
22877 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
22878   ULONG action;
22879 #endif
22880   
22881   /* We need some additional space at the end to append the region number */
22882   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
22883   if( cbShmName >= CCHMAXPATH-8 )
22884     return SQLITE_IOERR_SHMOPEN; 
22885
22886   /* Replace colon in file name to form a valid shared memory name */
22887   shmName[10+1] = '!';
22888
22889   /* Allocate link object (we free it later in case of failure) */
22890   pLink = sqlite3_malloc( sizeof(*pLink) );
22891   if( !pLink )
22892     return SQLITE_NOMEM;
22893
22894   /* Access node list */
22895   os2ShmEnterMutex();
22896
22897   /* Find node by it's shared memory base name */
22898   for( pNode = os2ShmNodeList; 
22899        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
22900        pNode = pNode->pNext )   ;
22901
22902   /* Not found: allocate a new node */
22903   if( !pNode ) {
22904     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
22905     if( pNode ) {
22906       memset(pNode, 0, sizeof(*pNode) );
22907       pNode->szRegion = szRegion;
22908       pNode->hLockFile = (HFILE)-1;      
22909       strcpy(pNode->shmBaseName, shmName);
22910
22911 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22912       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
22913 #else
22914       sprintf(shmName, "%s-lck", fd->zFullPathCp);
22915       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
22916                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
22917                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
22918                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
22919                   NULL) != 0 ) {
22920 #endif
22921         sqlite3_free(pNode);  
22922         rc = SQLITE_IOERR;
22923       } else {
22924         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
22925         if( !pNode->mutex ) {
22926           sqlite3_free(pNode);  
22927           rc = SQLITE_NOMEM;
22928         }
22929       }   
22930     } else {
22931       rc = SQLITE_NOMEM;
22932     }
22933     
22934     if( rc == SQLITE_OK ) {
22935       pNode->pNext = os2ShmNodeList;
22936       os2ShmNodeList = pNode;
22937     } else {
22938       pNode = NULL;
22939     }
22940   } else if( pNode->szRegion != szRegion ) {
22941     rc = SQLITE_IOERR_SHMSIZE;
22942     pNode = NULL;
22943   }
22944
22945   if( pNode ) {
22946     sqlite3_mutex_enter(pNode->mutex);
22947
22948     memset(pLink, 0, sizeof(*pLink));
22949
22950     pLink->pShmNode = pNode;
22951     pLink->pNext = pNode->pFirst;
22952     pNode->pFirst = pLink;
22953     pNode->nRef++;
22954
22955     fd->pShmLink = pLink;
22956
22957     sqlite3_mutex_leave(pNode->mutex);
22958     
22959   } else {
22960     /* Error occured. Free our link object. */
22961     sqlite3_free(pLink);  
22962   }
22963
22964   os2ShmLeaveMutex();
22965
22966   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
22967   
22968   return rc;
22969 }
22970
22971 /*
22972 ** Purge the os2ShmNodeList list of all entries with nRef==0.
22973 **
22974 ** This is not a VFS shared-memory method; it is a utility function called
22975 ** by VFS shared-memory methods.
22976 */
22977 static void os2PurgeShmNodes( int deleteFlag ) {
22978   os2ShmNode *pNode;
22979   os2ShmNode **ppNode;
22980
22981   os2ShmEnterMutex();
22982   
22983   ppNode = &os2ShmNodeList;
22984
22985   while( *ppNode ) {
22986     pNode = *ppNode;
22987
22988     if( pNode->nRef == 0 ) {
22989       *ppNode = pNode->pNext;   
22990      
22991       if( pNode->apRegion ) {
22992         /* Prevent other processes from resizing the shared memory */
22993         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
22994
22995         while( pNode->nRegion-- ) {
22996 #ifdef SQLITE_DEBUG
22997           int rc = 
22998 #endif          
22999           DosFreeMem(pNode->apRegion[pNode->nRegion]);
23000
23001           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23002                   (int)GetCurrentProcessId(), pNode->nRegion,
23003                   rc == 0 ? "ok" : "failed"));
23004         }
23005
23006         /* Allow other processes to resize the shared memory */
23007         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23008
23009         sqlite3_free(pNode->apRegion);
23010       }  
23011
23012       DosClose(pNode->hLockFile);
23013       
23014 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23015       if( deleteFlag ) {
23016          char fileName[CCHMAXPATH];
23017          /* Skip "\\SHAREMEM\\" */
23018          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23019          /* restore colon */
23020          fileName[1] = ':';
23021          
23022          DosForceDelete(fileName); 
23023       }
23024 #endif
23025
23026       sqlite3_mutex_free(pNode->mutex);
23027
23028       sqlite3_free(pNode);
23029       
23030     } else {
23031       ppNode = &pNode->pNext;
23032     }
23033   } 
23034
23035   os2ShmLeaveMutex();
23036 }
23037
23038 /*
23039 ** This function is called to obtain a pointer to region iRegion of the
23040 ** shared-memory associated with the database file id. Shared-memory regions
23041 ** are numbered starting from zero. Each shared-memory region is szRegion
23042 ** bytes in size.
23043 **
23044 ** If an error occurs, an error code is returned and *pp is set to NULL.
23045 **
23046 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23047 ** region has not been allocated (by any client, including one running in a
23048 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23049 ** bExtend is non-zero and the requested shared-memory region has not yet
23050 ** been allocated, it is allocated by this function.
23051 **
23052 ** If the shared-memory region has already been allocated or is allocated by
23053 ** this call as described above, then it is mapped into this processes
23054 ** address space (if it is not already), *pp is set to point to the mapped
23055 ** memory and SQLITE_OK returned.
23056 */
23057 static int os2ShmMap(
23058   sqlite3_file *id,               /* Handle open on database file */
23059   int iRegion,                    /* Region to retrieve */
23060   int szRegion,                   /* Size of regions */
23061   int bExtend,                    /* True to extend block if necessary */
23062   void volatile **pp              /* OUT: Mapped memory */
23063 ){
23064   PVOID pvTemp;
23065   void **apRegion;
23066   os2ShmNode *pNode;
23067   int n, rc = SQLITE_OK;
23068   char shmName[CCHMAXPATH];
23069   os2File *pFile = (os2File*)id;
23070   
23071   *pp = NULL;
23072
23073   if( !pFile->pShmLink )
23074     rc = os2OpenSharedMemory( pFile, szRegion );
23075   
23076   if( rc == SQLITE_OK ) {
23077     pNode = pFile->pShmLink->pShmNode ;
23078     
23079     sqlite3_mutex_enter(pNode->mutex);
23080     
23081     assert( szRegion==pNode->szRegion );
23082
23083     /* Unmapped region ? */
23084     if( iRegion >= pNode->nRegion ) {
23085       /* Prevent other processes from resizing the shared memory */
23086       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23087
23088       apRegion = sqlite3_realloc(
23089         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23090
23091       if( apRegion ) {
23092         pNode->apRegion = apRegion;
23093
23094         while( pNode->nRegion <= iRegion ) {
23095           sprintf(shmName, "%s-%u", 
23096                   pNode->shmBaseName, pNode->nRegion);
23097
23098           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
23099                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23100             if( !bExtend )
23101               break;
23102
23103             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23104                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
23105                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23106                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
23107               rc = SQLITE_NOMEM;
23108               break;
23109             }
23110           }
23111
23112           apRegion[pNode->nRegion++] = pvTemp;
23113         }
23114
23115         /* zero out remaining entries */ 
23116         for( n = pNode->nRegion; n <= iRegion; n++ )
23117           pNode->apRegion[n] = NULL;
23118
23119         /* Return this region (maybe zero) */
23120         *pp = pNode->apRegion[iRegion];
23121       } else {
23122         rc = SQLITE_NOMEM;
23123       }
23124
23125       /* Allow other processes to resize the shared memory */
23126       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23127       
23128     } else {
23129       /* Region has been mapped previously */
23130       *pp = pNode->apRegion[iRegion];
23131     }
23132
23133     sqlite3_mutex_leave(pNode->mutex);
23134   } 
23135
23136   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
23137                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23138           
23139   return rc;
23140 }
23141
23142 /*
23143 ** Close a connection to shared-memory.  Delete the underlying
23144 ** storage if deleteFlag is true.
23145 **
23146 ** If there is no shared memory associated with the connection then this
23147 ** routine is a harmless no-op.
23148 */
23149 static int os2ShmUnmap(
23150   sqlite3_file *id,               /* The underlying database file */
23151   int deleteFlag                  /* Delete shared-memory if true */
23152 ){
23153   os2File *pFile = (os2File*)id;
23154   os2ShmLink *pLink = pFile->pShmLink;
23155   
23156   if( pLink ) {
23157     int nRef = -1;
23158     os2ShmLink **ppLink;
23159     os2ShmNode *pNode = pLink->pShmNode;
23160
23161     sqlite3_mutex_enter(pNode->mutex);
23162     
23163     for( ppLink = &pNode->pFirst;
23164          *ppLink && *ppLink != pLink;
23165          ppLink = &(*ppLink)->pNext )   ;
23166          
23167     assert(*ppLink);
23168
23169     if( *ppLink ) {
23170       *ppLink = pLink->pNext;
23171       nRef = --pNode->nRef;
23172     } else {
23173       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
23174                     pNode->shmBaseName))
23175     }
23176     
23177     pFile->pShmLink = NULL;
23178     sqlite3_free(pLink);
23179
23180     sqlite3_mutex_leave(pNode->mutex);
23181     
23182     if( nRef == 0 )
23183       os2PurgeShmNodes( deleteFlag );
23184   }
23185
23186   return SQLITE_OK;
23187 }
23188
23189 /*
23190 ** Change the lock state for a shared-memory segment.
23191 **
23192 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23193 ** different here than in posix.  In xShmLock(), one can go from unlocked
23194 ** to shared and back or from unlocked to exclusive and back.  But one may
23195 ** not go from shared to exclusive or from exclusive to shared.
23196 */
23197 static int os2ShmLock(
23198   sqlite3_file *id,          /* Database file holding the shared memory */
23199   int ofst,                  /* First lock to acquire or release */
23200   int n,                     /* Number of locks to acquire or release */
23201   int flags                  /* What to do with the lock */
23202 ){
23203   u32 mask;                             /* Mask of locks to take or release */
23204   int rc = SQLITE_OK;                   /* Result code */
23205   os2File *pFile = (os2File*)id;
23206   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
23207   os2ShmLink *pX;                       /* For looping over all siblings */
23208   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
23209   
23210   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23211   assert( n>=1 );
23212   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23213        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23214        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23215        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23216   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23217
23218   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23219   assert( n>1 || mask==(1<<ofst) );
23220
23221
23222   sqlite3_mutex_enter(pShmNode->mutex);
23223
23224   if( flags & SQLITE_SHM_UNLOCK ){
23225     u32 allMask = 0; /* Mask of locks held by siblings */
23226
23227     /* See if any siblings hold this same lock */
23228     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23229       if( pX==p ) continue;
23230       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23231       allMask |= pX->sharedMask;
23232     }
23233
23234     /* Unlock the system-level locks */
23235     if( (mask & allMask)==0 ){
23236       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23237     }else{
23238       rc = SQLITE_OK;
23239     }
23240
23241     /* Undo the local locks */
23242     if( rc==SQLITE_OK ){
23243       p->exclMask &= ~mask;
23244       p->sharedMask &= ~mask;
23245     } 
23246   }else if( flags & SQLITE_SHM_SHARED ){
23247     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
23248
23249     /* Find out which shared locks are already held by sibling connections.
23250     ** If any sibling already holds an exclusive lock, go ahead and return
23251     ** SQLITE_BUSY.
23252     */
23253     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23254       if( (pX->exclMask & mask)!=0 ){
23255         rc = SQLITE_BUSY;
23256         break;
23257       }
23258       allShared |= pX->sharedMask;
23259     }
23260
23261     /* Get shared locks at the system level, if necessary */
23262     if( rc==SQLITE_OK ){
23263       if( (allShared & mask)==0 ){
23264         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23265       }else{
23266         rc = SQLITE_OK;
23267       }
23268     }
23269
23270     /* Get the local shared locks */
23271     if( rc==SQLITE_OK ){
23272       p->sharedMask |= mask;
23273     }
23274   }else{
23275     /* Make sure no sibling connections hold locks that will block this
23276     ** lock.  If any do, return SQLITE_BUSY right away.
23277     */
23278     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23279       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23280         rc = SQLITE_BUSY;
23281         break;
23282       }
23283     }
23284   
23285     /* Get the exclusive locks at the system level.  Then if successful
23286     ** also mark the local connection as being locked.
23287     */
23288     if( rc==SQLITE_OK ){
23289       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23290       if( rc==SQLITE_OK ){
23291         assert( (p->sharedMask & mask)==0 );
23292         p->exclMask |= mask;
23293       }
23294     }
23295   }
23296
23297   sqlite3_mutex_leave(pShmNode->mutex);
23298   
23299   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23300            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23301            rc ? "failed" : "ok"));
23302
23303   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
23304                  ofst, n, flags, rc))
23305                   
23306   return rc; 
23307 }
23308
23309 /*
23310 ** Implement a memory barrier or memory fence on shared memory.
23311 **
23312 ** All loads and stores begun before the barrier must complete before
23313 ** any load or store begun after the barrier.
23314 */
23315 static void os2ShmBarrier(
23316   sqlite3_file *id                /* Database file holding the shared memory */
23317 ){
23318   UNUSED_PARAMETER(id);
23319   os2ShmEnterMutex();
23320   os2ShmLeaveMutex();
23321 }
23322
23323 #else
23324 # define os2ShmMap     0
23325 # define os2ShmLock    0
23326 # define os2ShmBarrier 0
23327 # define os2ShmUnmap   0
23328 #endif /* #ifndef SQLITE_OMIT_WAL */
23329
23330
23331 /*
23332 ** This vector defines all the methods that can operate on an
23333 ** sqlite3_file for os2.
23334 */
23335 static const sqlite3_io_methods os2IoMethod = {
23336   2,                              /* iVersion */
23337   os2Close,                       /* xClose */
23338   os2Read,                        /* xRead */
23339   os2Write,                       /* xWrite */
23340   os2Truncate,                    /* xTruncate */
23341   os2Sync,                        /* xSync */
23342   os2FileSize,                    /* xFileSize */
23343   os2Lock,                        /* xLock */
23344   os2Unlock,                      /* xUnlock */
23345   os2CheckReservedLock,           /* xCheckReservedLock */
23346   os2FileControl,                 /* xFileControl */
23347   os2SectorSize,                  /* xSectorSize */
23348   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
23349   os2ShmMap,                      /* xShmMap */
23350   os2ShmLock,                     /* xShmLock */
23351   os2ShmBarrier,                  /* xShmBarrier */
23352   os2ShmUnmap                     /* xShmUnmap */
23353 };
23354
23355
23356 /***************************************************************************
23357 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23358 **
23359 ** The next block of code implements the VFS methods.
23360 ****************************************************************************/
23361
23362 /*
23363 ** Create a temporary file name in zBuf.  zBuf must be big enough to
23364 ** hold at pVfs->mxPathname characters.
23365 */
23366 static int getTempname(int nBuf, char *zBuf ){
23367   static const char zChars[] =
23368     "abcdefghijklmnopqrstuvwxyz"
23369     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23370     "0123456789";
23371   int i, j;
23372   PSZ zTempPathCp;      
23373   char zTempPath[CCHMAXPATH];
23374   ULONG ulDriveNum, ulDriveMap;
23375   
23376   /* It's odd to simulate an io-error here, but really this is just
23377   ** using the io-error infrastructure to test that SQLite handles this
23378   ** function failing. 
23379   */
23380   SimulateIOError( return SQLITE_IOERR );
23381
23382   if( sqlite3_temp_directory ) {
23383     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23384   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
23385              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
23386              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23387     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23388     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23389     free( zTempPathUTF );
23390   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23391     zTempPath[0] = (char)('A' + ulDriveNum - 1);
23392     zTempPath[1] = ':'; 
23393     zTempPath[2] = '\0'; 
23394   } else {
23395     zTempPath[0] = '\0'; 
23396   }
23397   
23398   /* Strip off a trailing slashes or backslashes, otherwise we would get *
23399    * multiple (back)slashes which causes DosOpen() to fail.              *
23400    * Trailing spaces are not allowed, either.                            */
23401   j = sqlite3Strlen30(zTempPath);
23402   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
23403                     zTempPath[j-1] == ' ' ) ){
23404     j--;
23405   }
23406   zTempPath[j] = '\0';
23407   
23408   /* We use 20 bytes to randomize the name */
23409   sqlite3_snprintf(nBuf-22, zBuf,
23410                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23411   j = sqlite3Strlen30(zBuf);
23412   sqlite3_randomness( 20, &zBuf[j] );
23413   for( i = 0; i < 20; i++, j++ ){
23414     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23415   }
23416   zBuf[j] = 0;
23417
23418   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23419   return SQLITE_OK;
23420 }
23421
23422
23423 /*
23424 ** Turn a relative pathname into a full pathname.  Write the full
23425 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
23426 ** bytes in size.
23427 */
23428 static int os2FullPathname(
23429   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
23430   const char *zRelative,      /* Possibly relative input path */
23431   int nFull,                  /* Size of output buffer in bytes */
23432   char *zFull                 /* Output buffer */
23433 ){
23434   char *zRelativeCp = convertUtf8PathToCp( zRelative );
23435   char zFullCp[CCHMAXPATH] = "\0";
23436   char *zFullUTF;
23437   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
23438                                 zFullCp, CCHMAXPATH );
23439   free( zRelativeCp );
23440   zFullUTF = convertCpPathToUtf8( zFullCp );
23441   sqlite3_snprintf( nFull, zFull, zFullUTF );
23442   free( zFullUTF );
23443   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23444 }
23445
23446
23447 /*
23448 ** Open a file.
23449 */
23450 static int os2Open(
23451   sqlite3_vfs *pVfs,            /* Not used */
23452   const char *zName,            /* Name of the file (UTF-8) */
23453   sqlite3_file *id,             /* Write the SQLite file handle here */
23454   int flags,                    /* Open mode flags */
23455   int *pOutFlags                /* Status return flags */
23456 ){
23457   HFILE h;
23458   ULONG ulOpenFlags = 0;
23459   ULONG ulOpenMode = 0;
23460   ULONG ulAction = 0;
23461   ULONG rc;
23462   os2File *pFile = (os2File*)id;
23463   const char *zUtf8Name = zName;
23464   char *zNameCp;
23465   char  zTmpname[CCHMAXPATH];
23466
23467   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23468   int isCreate     = (flags & SQLITE_OPEN_CREATE);
23469   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23470 #ifndef NDEBUG
23471   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23472   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23473   int eType        = (flags & 0xFFFFFF00);
23474   int isOpenJournal = (isCreate && (
23475         eType==SQLITE_OPEN_MASTER_JOURNAL 
23476      || eType==SQLITE_OPEN_MAIN_JOURNAL 
23477      || eType==SQLITE_OPEN_WAL
23478   ));
23479 #endif
23480
23481   UNUSED_PARAMETER(pVfs);
23482   assert( id!=0 );
23483
23484   /* Check the following statements are true: 
23485   **
23486   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
23487   **   (b) if CREATE is set, then READWRITE must also be set, and
23488   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23489   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23490   */
23491   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23492   assert(isCreate==0 || isReadWrite);
23493   assert(isExclusive==0 || isCreate);
23494   assert(isDelete==0 || isCreate);
23495
23496   /* The main DB, main journal, WAL file and master journal are never 
23497   ** automatically deleted. Nor are they ever temporary files.  */
23498   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23499   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23500   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23501   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23502
23503   /* Assert that the upper layer has set one of the "file-type" flags. */
23504   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
23505        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
23506        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
23507        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23508   );
23509
23510   memset( pFile, 0, sizeof(*pFile) );
23511   pFile->h = (HFILE)-1;
23512
23513   /* If the second argument to this function is NULL, generate a 
23514   ** temporary file name to use 
23515   */
23516   if( !zUtf8Name ){
23517     assert(isDelete && !isOpenJournal);
23518     rc = getTempname(CCHMAXPATH, zTmpname);
23519     if( rc!=SQLITE_OK ){
23520       return rc;
23521     }
23522     zUtf8Name = zTmpname;
23523   }
23524
23525   if( isReadWrite ){
23526     ulOpenMode |= OPEN_ACCESS_READWRITE;
23527   }else{
23528     ulOpenMode |= OPEN_ACCESS_READONLY;
23529   }
23530
23531   /* Open in random access mode for possibly better speed.  Allow full
23532   ** sharing because file locks will provide exclusive access when needed.
23533   ** The handle should not be inherited by child processes and we don't 
23534   ** want popups from the critical error handler.
23535   */
23536   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
23537                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23538
23539   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
23540   ** created. SQLite doesn't use it to indicate "exclusive access" 
23541   ** as it is usually understood.
23542   */
23543   if( isExclusive ){
23544     /* Creates a new file, only if it does not already exist. */
23545     /* If the file exists, it fails. */
23546     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23547   }else if( isCreate ){
23548     /* Open existing file, or create if it doesn't exist */
23549     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23550   }else{
23551     /* Opens a file, only if it exists. */
23552     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23553   }
23554
23555   zNameCp = convertUtf8PathToCp( zUtf8Name );
23556   rc = DosOpen( (PSZ)zNameCp,
23557                 &h,
23558                 &ulAction,
23559                 0L,
23560                 FILE_NORMAL,
23561                 ulOpenFlags,
23562                 ulOpenMode,
23563                 (PEAOP2)NULL );
23564   free( zNameCp );
23565
23566   if( rc != NO_ERROR ){
23567     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23568               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23569
23570     if( isReadWrite ){
23571       return os2Open( pVfs, zName, id,
23572                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23573                       pOutFlags );
23574     }else{
23575       return SQLITE_CANTOPEN;
23576     }
23577   }
23578
23579   if( pOutFlags ){
23580     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23581   }
23582
23583   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23584   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23585   pFile->pMethod = &os2IoMethod;
23586   pFile->flags = flags;
23587   pFile->h = h;
23588
23589   OpenCounter(+1);
23590   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23591   return SQLITE_OK;
23592 }
23593
23594 /*
23595 ** Delete the named file.
23596 */
23597 static int os2Delete(
23598   sqlite3_vfs *pVfs,                     /* Not used on os2 */
23599   const char *zFilename,                 /* Name of file to delete */
23600   int syncDir                            /* Not used on os2 */
23601 ){
23602   APIRET rc;
23603   char *zFilenameCp;
23604   SimulateIOError( return SQLITE_IOERR_DELETE );
23605   zFilenameCp = convertUtf8PathToCp( zFilename );
23606   rc = DosDelete( (PSZ)zFilenameCp );
23607   free( zFilenameCp );
23608   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23609   return (rc == NO_ERROR ||
23610           rc == ERROR_FILE_NOT_FOUND ||
23611           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23612 }
23613
23614 /*
23615 ** Check the existance and status of a file.
23616 */
23617 static int os2Access(
23618   sqlite3_vfs *pVfs,        /* Not used on os2 */
23619   const char *zFilename,    /* Name of file to check */
23620   int flags,                /* Type of test to make on this file */
23621   int *pOut                 /* Write results here */
23622 ){
23623   APIRET rc;
23624   FILESTATUS3 fsts3ConfigInfo;
23625   char *zFilenameCp;
23626
23627   UNUSED_PARAMETER(pVfs);
23628   SimulateIOError( return SQLITE_IOERR_ACCESS; );
23629   
23630   zFilenameCp = convertUtf8PathToCp( zFilename );
23631   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23632                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23633   free( zFilenameCp );
23634   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23635             fsts3ConfigInfo.attrFile, flags, rc ));
23636
23637   switch( flags ){
23638     case SQLITE_ACCESS_EXISTS:
23639       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23640       ** as if it does not exist.
23641       */
23642       if( fsts3ConfigInfo.cbFile == 0 ) 
23643         rc = ERROR_FILE_NOT_FOUND;
23644       break;
23645     case SQLITE_ACCESS_READ:
23646       break;
23647     case SQLITE_ACCESS_READWRITE:
23648       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23649         rc = ERROR_ACCESS_DENIED;
23650       break;
23651     default:
23652       rc = ERROR_FILE_NOT_FOUND;
23653       assert( !"Invalid flags argument" );
23654   }
23655
23656   *pOut = (rc == NO_ERROR);
23657   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
23658
23659   return SQLITE_OK;
23660 }
23661
23662
23663 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23664 /*
23665 ** Interfaces for opening a shared library, finding entry points
23666 ** within the shared library, and closing the shared library.
23667 */
23668 /*
23669 ** Interfaces for opening a shared library, finding entry points
23670 ** within the shared library, and closing the shared library.
23671 */
23672 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23673   HMODULE hmod;
23674   APIRET rc;
23675   char *zFilenameCp = convertUtf8PathToCp(zFilename);
23676   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
23677   free(zFilenameCp);
23678   return rc != NO_ERROR ? 0 : (void*)hmod;
23679 }
23680 /*
23681 ** A no-op since the error code is returned on the DosLoadModule call.
23682 ** os2Dlopen returns zero if DosLoadModule is not successful.
23683 */
23684 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23685 /* no-op */
23686 }
23687 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
23688   PFN pfn;
23689   APIRET rc;
23690   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
23691   if( rc != NO_ERROR ){
23692     /* if the symbol itself was not found, search again for the same
23693      * symbol with an extra underscore, that might be needed depending
23694      * on the calling convention */
23695     char _zSymbol[256] = "_";
23696     strncat(_zSymbol, zSymbol, 254);
23697     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
23698   }
23699   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
23700 }
23701 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
23702   DosFreeModule((HMODULE)pHandle);
23703 }
23704 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23705   #define os2DlOpen 0
23706   #define os2DlError 0
23707   #define os2DlSym 0
23708   #define os2DlClose 0
23709 #endif
23710
23711
23712 /*
23713 ** Write up to nBuf bytes of randomness into zBuf.
23714 */
23715 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
23716   int n = 0;
23717 #if defined(SQLITE_TEST)
23718   n = nBuf;
23719   memset(zBuf, 0, nBuf);
23720 #else
23721   int i;                           
23722   PPIB ppib;
23723   PTIB ptib;
23724   DATETIME dt; 
23725   static unsigned c = 0;
23726   /* Ordered by variation probability */
23727   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
23728                             QSV_MAXPRMEM, QSV_MAXSHMEM,
23729                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
23730
23731   /* 8 bytes; timezone and weekday don't increase the randomness much */
23732   if( (int)sizeof(dt)-3 <= nBuf - n ){
23733     c += 0x0100;
23734     DosGetDateTime(&dt);
23735     dt.year = (USHORT)((dt.year - 1900) | c);
23736     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
23737     n += sizeof(dt)-3;
23738   }
23739
23740   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
23741   if( (int)sizeof(ULONG) <= nBuf - n ){
23742     DosGetInfoBlocks(&ptib, &ppib);
23743     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
23744                                  ptib->tib_ptib2->tib2_ultid);
23745     n += sizeof(ULONG);
23746   }
23747
23748   /* Up to 6 * 4 bytes; variables depend on the system state */
23749   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
23750     DosQuerySysInfo(svIdx[i], svIdx[i], 
23751                     (PULONG)&zBuf[n], sizeof(ULONG));
23752     n += sizeof(ULONG);
23753   } 
23754 #endif
23755
23756   return n;
23757 }
23758
23759 /*
23760 ** Sleep for a little while.  Return the amount of time slept.
23761 ** The argument is the number of microseconds we want to sleep.
23762 ** The return value is the number of microseconds of sleep actually
23763 ** requested from the underlying operating system, a number which
23764 ** might be greater than or equal to the argument, but not less
23765 ** than the argument.
23766 */
23767 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
23768   DosSleep( (microsec/1000) );
23769   return microsec;
23770 }
23771
23772 /*
23773 ** The following variable, if set to a non-zero value, becomes the result
23774 ** returned from sqlite3OsCurrentTime().  This is used for testing.
23775 */
23776 #ifdef SQLITE_TEST
23777 SQLITE_API int sqlite3_current_time = 0;
23778 #endif
23779
23780 /*
23781 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
23782 ** the current time and date as a Julian Day number times 86_400_000.  In
23783 ** other words, write into *piNow the number of milliseconds since the Julian
23784 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
23785 ** proleptic Gregorian calendar.
23786 **
23787 ** On success, return 0.  Return 1 if the time and date cannot be found.
23788 */
23789 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
23790 #ifdef SQLITE_TEST
23791   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
23792 #endif
23793   int year, month, datepart, timepart;
23794  
23795   DATETIME dt;
23796   DosGetDateTime( &dt );
23797
23798   year = dt.year;
23799   month = dt.month;
23800
23801   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
23802   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
23803   ** Calculate the Julian days
23804   */
23805   datepart = (int)dt.day - 32076 +
23806     1461*(year + 4800 + (month - 14)/12)/4 +
23807     367*(month - 2 - (month - 14)/12*12)/12 -
23808     3*((year + 4900 + (month - 14)/12)/100)/4;
23809
23810   /* Time in milliseconds, hours to noon added */
23811   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
23812     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
23813
23814   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
23815    
23816 #ifdef SQLITE_TEST
23817   if( sqlite3_current_time ){
23818     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
23819   }
23820 #endif
23821
23822   UNUSED_PARAMETER(pVfs);
23823   return 0;
23824 }
23825
23826 /*
23827 ** Find the current time (in Universal Coordinated Time).  Write the
23828 ** current time and date as a Julian Day number into *prNow and
23829 ** return 0.  Return 1 if the time and date cannot be found.
23830 */
23831 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
23832   int rc;
23833   sqlite3_int64 i;
23834   rc = os2CurrentTimeInt64(pVfs, &i);
23835   if( !rc ){
23836     *prNow = i/86400000.0;
23837   }
23838   return rc;
23839 }
23840
23841 /*
23842 ** The idea is that this function works like a combination of
23843 ** GetLastError() and FormatMessage() on windows (or errno and
23844 ** strerror_r() on unix). After an error is returned by an OS
23845 ** function, SQLite calls this function with zBuf pointing to
23846 ** a buffer of nBuf bytes. The OS layer should populate the
23847 ** buffer with a nul-terminated UTF-8 encoded error message
23848 ** describing the last IO error to have occurred within the calling
23849 ** thread.
23850 **
23851 ** If the error message is too large for the supplied buffer,
23852 ** it should be truncated. The return value of xGetLastError
23853 ** is zero if the error message fits in the buffer, or non-zero
23854 ** otherwise (if the message was truncated). If non-zero is returned,
23855 ** then it is not necessary to include the nul-terminator character
23856 ** in the output buffer.
23857 **
23858 ** Not supplying an error message will have no adverse effect
23859 ** on SQLite. It is fine to have an implementation that never
23860 ** returns an error message:
23861 **
23862 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23863 **     assert(zBuf[0]=='\0');
23864 **     return 0;
23865 **   }
23866 **
23867 ** However if an error message is supplied, it will be incorporated
23868 ** by sqlite into the error message available to the user using
23869 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
23870 */
23871 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23872   assert(zBuf[0]=='\0');
23873   return 0;
23874 }
23875
23876 /*
23877 ** Initialize and deinitialize the operating system interface.
23878 */
23879 SQLITE_API int sqlite3_os_init(void){
23880   static sqlite3_vfs os2Vfs = {
23881     3,                 /* iVersion */
23882     sizeof(os2File),   /* szOsFile */
23883     CCHMAXPATH,        /* mxPathname */
23884     0,                 /* pNext */
23885     "os2",             /* zName */
23886     0,                 /* pAppData */
23887
23888     os2Open,           /* xOpen */
23889     os2Delete,         /* xDelete */
23890     os2Access,         /* xAccess */
23891     os2FullPathname,   /* xFullPathname */
23892     os2DlOpen,         /* xDlOpen */
23893     os2DlError,        /* xDlError */
23894     os2DlSym,          /* xDlSym */
23895     os2DlClose,        /* xDlClose */
23896     os2Randomness,     /* xRandomness */
23897     os2Sleep,          /* xSleep */
23898     os2CurrentTime,    /* xCurrentTime */
23899     os2GetLastError,   /* xGetLastError */
23900     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
23901     0,                 /* xSetSystemCall */
23902     0,                 /* xGetSystemCall */
23903     0                  /* xNextSystemCall */
23904   };
23905   sqlite3_vfs_register(&os2Vfs, 1);
23906   initUconvObjects();
23907 /*  sqlite3OSTrace = 1; */
23908   return SQLITE_OK;
23909 }
23910 SQLITE_API int sqlite3_os_end(void){
23911   freeUconvObjects();
23912   return SQLITE_OK;
23913 }
23914
23915 #endif /* SQLITE_OS_OS2 */
23916
23917 /************** End of os_os2.c **********************************************/
23918 /************** Begin file os_unix.c *****************************************/
23919 /*
23920 ** 2004 May 22
23921 **
23922 ** The author disclaims copyright to this source code.  In place of
23923 ** a legal notice, here is a blessing:
23924 **
23925 **    May you do good and not evil.
23926 **    May you find forgiveness for yourself and forgive others.
23927 **    May you share freely, never taking more than you give.
23928 **
23929 ******************************************************************************
23930 **
23931 ** This file contains the VFS implementation for unix-like operating systems
23932 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23933 **
23934 ** There are actually several different VFS implementations in this file.
23935 ** The differences are in the way that file locking is done.  The default
23936 ** implementation uses Posix Advisory Locks.  Alternative implementations
23937 ** use flock(), dot-files, various proprietary locking schemas, or simply
23938 ** skip locking all together.
23939 **
23940 ** This source file is organized into divisions where the logic for various
23941 ** subfunctions is contained within the appropriate division.  PLEASE
23942 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
23943 ** in the correct division and should be clearly labeled.
23944 **
23945 ** The layout of divisions is as follows:
23946 **
23947 **   *  General-purpose declarations and utility functions.
23948 **   *  Unique file ID logic used by VxWorks.
23949 **   *  Various locking primitive implementations (all except proxy locking):
23950 **      + for Posix Advisory Locks
23951 **      + for no-op locks
23952 **      + for dot-file locks
23953 **      + for flock() locking
23954 **      + for named semaphore locks (VxWorks only)
23955 **      + for AFP filesystem locks (MacOSX only)
23956 **   *  sqlite3_file methods not associated with locking.
23957 **   *  Definitions of sqlite3_io_methods objects for all locking
23958 **      methods plus "finder" functions for each locking method.
23959 **   *  sqlite3_vfs method implementations.
23960 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
23961 **   *  Definitions of sqlite3_vfs objects for all locking methods
23962 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
23963 */
23964 #if SQLITE_OS_UNIX              /* This file is used on unix only */
23965
23966 /*
23967 ** There are various methods for file locking used for concurrency
23968 ** control:
23969 **
23970 **   1. POSIX locking (the default),
23971 **   2. No locking,
23972 **   3. Dot-file locking,
23973 **   4. flock() locking,
23974 **   5. AFP locking (OSX only),
23975 **   6. Named POSIX semaphores (VXWorks only),
23976 **   7. proxy locking. (OSX only)
23977 **
23978 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
23979 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
23980 ** selection of the appropriate locking style based on the filesystem
23981 ** where the database is located.  
23982 */
23983 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
23984 #  if defined(__APPLE__)
23985 #    define SQLITE_ENABLE_LOCKING_STYLE 1
23986 #  else
23987 #    define SQLITE_ENABLE_LOCKING_STYLE 0
23988 #  endif
23989 #endif
23990
23991 /*
23992 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
23993 ** vxworks, or 0 otherwise.
23994 */
23995 #ifndef OS_VXWORKS
23996 #  if defined(__RTP__) || defined(_WRS_KERNEL)
23997 #    define OS_VXWORKS 1
23998 #  else
23999 #    define OS_VXWORKS 0
24000 #  endif
24001 #endif
24002
24003 /*
24004 ** These #defines should enable >2GB file support on Posix if the
24005 ** underlying operating system supports it.  If the OS lacks
24006 ** large file support, these should be no-ops.
24007 **
24008 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24009 ** on the compiler command line.  This is necessary if you are compiling
24010 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24011 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24012 ** without this option, LFS is enable.  But LFS does not exist in the kernel
24013 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24014 ** portability you should omit LFS.
24015 **
24016 ** The previous paragraph was written in 2005.  (This paragraph is written
24017 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24018 ** you should probably leave LFS enabled.  But some embedded platforms might
24019 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24020 */
24021 #ifndef SQLITE_DISABLE_LFS
24022 # define _LARGE_FILE       1
24023 # ifndef _FILE_OFFSET_BITS
24024 #   define _FILE_OFFSET_BITS 64
24025 # endif
24026 # define _LARGEFILE_SOURCE 1
24027 #endif
24028
24029 /*
24030 ** standard include files.
24031 */
24032 #include <sys/types.h>
24033 #include <sys/stat.h>
24034 #include <fcntl.h>
24035 #include <unistd.h>
24036 #include <sys/time.h>
24037 #include <errno.h>
24038 #ifndef SQLITE_OMIT_WAL
24039 #include <sys/mman.h>
24040 #endif
24041
24042 #if SQLITE_ENABLE_LOCKING_STYLE
24043 # include <sys/ioctl.h>
24044 # if OS_VXWORKS
24045 #  include <semaphore.h>
24046 #  include <limits.h>
24047 # else
24048 #  include <sys/file.h>
24049 #  include <sys/param.h>
24050 # endif
24051 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24052
24053 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24054 # include <sys/mount.h>
24055 #endif
24056
24057 /*
24058 ** Allowed values of unixFile.fsFlags
24059 */
24060 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
24061
24062 /*
24063 ** If we are to be thread-safe, include the pthreads header and define
24064 ** the SQLITE_UNIX_THREADS macro.
24065 */
24066 #if SQLITE_THREADSAFE
24067 # define SQLITE_UNIX_THREADS 1
24068 #endif
24069
24070 /*
24071 ** Default permissions when creating a new file
24072 */
24073 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24074 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24075 #endif
24076
24077 /*
24078  ** Default permissions when creating auto proxy dir
24079  */
24080 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24081 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24082 #endif
24083
24084 /*
24085 ** Maximum supported path-length.
24086 */
24087 #define MAX_PATHNAME 512
24088
24089 /*
24090 ** Only set the lastErrno if the error code is a real error and not 
24091 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24092 */
24093 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24094
24095 /* Forward references */
24096 typedef struct unixShm unixShm;               /* Connection shared memory */
24097 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24098 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24099 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24100
24101 /*
24102 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24103 ** cannot be closed immediately. In these cases, instances of the following
24104 ** structure are used to store the file descriptor while waiting for an
24105 ** opportunity to either close or reuse it.
24106 */
24107 struct UnixUnusedFd {
24108   int fd;                   /* File descriptor to close */
24109   int flags;                /* Flags this file descriptor was opened with */
24110   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24111 };
24112
24113 /*
24114 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24115 ** VFS implementations.
24116 */
24117 typedef struct unixFile unixFile;
24118 struct unixFile {
24119   sqlite3_io_methods const *pMethod;  /* Always the first entry */
24120   unixInodeInfo *pInode;              /* Info about locks on this inode */
24121   int h;                              /* The file descriptor */
24122   int dirfd;                          /* File descriptor for the directory */
24123   unsigned char eFileLock;            /* The type of lock held on this fd */
24124   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
24125   int lastErrno;                      /* The unix errno from last I/O error */
24126   void *lockingContext;               /* Locking style specific state */
24127   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24128   const char *zPath;                  /* Name of the file */
24129   unixShm *pShm;                      /* Shared memory segment information */
24130   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24131 #if SQLITE_ENABLE_LOCKING_STYLE
24132   int openFlags;                      /* The flags specified at open() */
24133 #endif
24134 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24135   unsigned fsFlags;                   /* cached details from statfs() */
24136 #endif
24137 #if OS_VXWORKS
24138   int isDelete;                       /* Delete on close if true */
24139   struct vxworksFileId *pId;          /* Unique file ID */
24140 #endif
24141 #ifndef NDEBUG
24142   /* The next group of variables are used to track whether or not the
24143   ** transaction counter in bytes 24-27 of database files are updated
24144   ** whenever any part of the database changes.  An assertion fault will
24145   ** occur if a file is updated without also updating the transaction
24146   ** counter.  This test is made to avoid new problems similar to the
24147   ** one described by ticket #3584. 
24148   */
24149   unsigned char transCntrChng;   /* True if the transaction counter changed */
24150   unsigned char dbUpdate;        /* True if any part of database file changed */
24151   unsigned char inNormalWrite;   /* True if in a normal write operation */
24152 #endif
24153 #ifdef SQLITE_TEST
24154   /* In test mode, increase the size of this structure a bit so that 
24155   ** it is larger than the struct CrashFile defined in test6.c.
24156   */
24157   char aPadding[32];
24158 #endif
24159 };
24160
24161 /*
24162 ** Allowed values for the unixFile.ctrlFlags bitmask:
24163 */
24164 #define UNIXFILE_EXCL   0x01     /* Connections from one process only */
24165 #define UNIXFILE_RDONLY 0x02     /* Connection is read only */
24166
24167 /*
24168 ** Include code that is common to all os_*.c files
24169 */
24170 /************** Include os_common.h in the middle of os_unix.c ***************/
24171 /************** Begin file os_common.h ***************************************/
24172 /*
24173 ** 2004 May 22
24174 **
24175 ** The author disclaims copyright to this source code.  In place of
24176 ** a legal notice, here is a blessing:
24177 **
24178 **    May you do good and not evil.
24179 **    May you find forgiveness for yourself and forgive others.
24180 **    May you share freely, never taking more than you give.
24181 **
24182 ******************************************************************************
24183 **
24184 ** This file contains macros and a little bit of code that is common to
24185 ** all of the platform-specific files (os_*.c) and is #included into those
24186 ** files.
24187 **
24188 ** This file should be #included by the os_*.c files only.  It is not a
24189 ** general purpose header file.
24190 */
24191 #ifndef _OS_COMMON_H_
24192 #define _OS_COMMON_H_
24193
24194 /*
24195 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24196 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24197 ** switch.  The following code should catch this problem at compile-time.
24198 */
24199 #ifdef MEMORY_DEBUG
24200 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24201 #endif
24202
24203 #ifdef SQLITE_DEBUG
24204 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24205 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24206 #else
24207 #define OSTRACE(X)
24208 #endif
24209
24210 /*
24211 ** Macros for performance tracing.  Normally turned off.  Only works
24212 ** on i486 hardware.
24213 */
24214 #ifdef SQLITE_PERFORMANCE_TRACE
24215
24216 /* 
24217 ** hwtime.h contains inline assembler code for implementing 
24218 ** high-performance timing routines.
24219 */
24220 /************** Include hwtime.h in the middle of os_common.h ****************/
24221 /************** Begin file hwtime.h ******************************************/
24222 /*
24223 ** 2008 May 27
24224 **
24225 ** The author disclaims copyright to this source code.  In place of
24226 ** a legal notice, here is a blessing:
24227 **
24228 **    May you do good and not evil.
24229 **    May you find forgiveness for yourself and forgive others.
24230 **    May you share freely, never taking more than you give.
24231 **
24232 ******************************************************************************
24233 **
24234 ** This file contains inline asm code for retrieving "high-performance"
24235 ** counters for x86 class CPUs.
24236 */
24237 #ifndef _HWTIME_H_
24238 #define _HWTIME_H_
24239
24240 /*
24241 ** The following routine only works on pentium-class (or newer) processors.
24242 ** It uses the RDTSC opcode to read the cycle count value out of the
24243 ** processor and returns that value.  This can be used for high-res
24244 ** profiling.
24245 */
24246 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24247       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24248
24249   #if defined(__GNUC__)
24250
24251   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24252      unsigned int lo, hi;
24253      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24254      return (sqlite_uint64)hi << 32 | lo;
24255   }
24256
24257   #elif defined(_MSC_VER)
24258
24259   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24260      __asm {
24261         rdtsc
24262         ret       ; return value at EDX:EAX
24263      }
24264   }
24265
24266   #endif
24267
24268 #elif (defined(__GNUC__) && defined(__x86_64__))
24269
24270   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24271       unsigned long val;
24272       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24273       return val;
24274   }
24275  
24276 #elif (defined(__GNUC__) && defined(__ppc__))
24277
24278   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24279       unsigned long long retval;
24280       unsigned long junk;
24281       __asm__ __volatile__ ("\n\
24282           1:      mftbu   %1\n\
24283                   mftb    %L0\n\
24284                   mftbu   %0\n\
24285                   cmpw    %0,%1\n\
24286                   bne     1b"
24287                   : "=r" (retval), "=r" (junk));
24288       return retval;
24289   }
24290
24291 #else
24292
24293   #error Need implementation of sqlite3Hwtime() for your platform.
24294
24295   /*
24296   ** To compile without implementing sqlite3Hwtime() for your platform,
24297   ** you can remove the above #error and use the following
24298   ** stub function.  You will lose timing support for many
24299   ** of the debugging and testing utilities, but it should at
24300   ** least compile and run.
24301   */
24302 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24303
24304 #endif
24305
24306 #endif /* !defined(_HWTIME_H_) */
24307
24308 /************** End of hwtime.h **********************************************/
24309 /************** Continuing where we left off in os_common.h ******************/
24310
24311 static sqlite_uint64 g_start;
24312 static sqlite_uint64 g_elapsed;
24313 #define TIMER_START       g_start=sqlite3Hwtime()
24314 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24315 #define TIMER_ELAPSED     g_elapsed
24316 #else
24317 #define TIMER_START
24318 #define TIMER_END
24319 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24320 #endif
24321
24322 /*
24323 ** If we compile with the SQLITE_TEST macro set, then the following block
24324 ** of code will give us the ability to simulate a disk I/O error.  This
24325 ** is used for testing the I/O recovery logic.
24326 */
24327 #ifdef SQLITE_TEST
24328 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24329 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24330 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24331 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24332 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24333 SQLITE_API int sqlite3_diskfull_pending = 0;
24334 SQLITE_API int sqlite3_diskfull = 0;
24335 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24336 #define SimulateIOError(CODE)  \
24337   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24338        || sqlite3_io_error_pending-- == 1 )  \
24339               { local_ioerr(); CODE; }
24340 static void local_ioerr(){
24341   IOTRACE(("IOERR\n"));
24342   sqlite3_io_error_hit++;
24343   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24344 }
24345 #define SimulateDiskfullError(CODE) \
24346    if( sqlite3_diskfull_pending ){ \
24347      if( sqlite3_diskfull_pending == 1 ){ \
24348        local_ioerr(); \
24349        sqlite3_diskfull = 1; \
24350        sqlite3_io_error_hit = 1; \
24351        CODE; \
24352      }else{ \
24353        sqlite3_diskfull_pending--; \
24354      } \
24355    }
24356 #else
24357 #define SimulateIOErrorBenign(X)
24358 #define SimulateIOError(A)
24359 #define SimulateDiskfullError(A)
24360 #endif
24361
24362 /*
24363 ** When testing, keep a count of the number of open files.
24364 */
24365 #ifdef SQLITE_TEST
24366 SQLITE_API int sqlite3_open_file_count = 0;
24367 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24368 #else
24369 #define OpenCounter(X)
24370 #endif
24371
24372 #endif /* !defined(_OS_COMMON_H_) */
24373
24374 /************** End of os_common.h *******************************************/
24375 /************** Continuing where we left off in os_unix.c ********************/
24376
24377 /*
24378 ** Define various macros that are missing from some systems.
24379 */
24380 #ifndef O_LARGEFILE
24381 # define O_LARGEFILE 0
24382 #endif
24383 #ifdef SQLITE_DISABLE_LFS
24384 # undef O_LARGEFILE
24385 # define O_LARGEFILE 0
24386 #endif
24387 #ifndef O_NOFOLLOW
24388 # define O_NOFOLLOW 0
24389 #endif
24390 #ifndef O_BINARY
24391 # define O_BINARY 0
24392 #endif
24393
24394 /*
24395 ** The threadid macro resolves to the thread-id or to 0.  Used for
24396 ** testing and debugging only.
24397 */
24398 #if SQLITE_THREADSAFE
24399 #define threadid pthread_self()
24400 #else
24401 #define threadid 0
24402 #endif
24403
24404 /*
24405 ** Many system calls are accessed through pointer-to-functions so that
24406 ** they may be overridden at runtime to facilitate fault injection during
24407 ** testing and sandboxing.  The following array holds the names and pointers
24408 ** to all overrideable system calls.
24409 */
24410 static struct unix_syscall {
24411   const char *zName;            /* Name of the sytem call */
24412   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24413   sqlite3_syscall_ptr pDefault; /* Default value */
24414 } aSyscall[] = {
24415   { "open",         (sqlite3_syscall_ptr)open,       0  },
24416 #define osOpen      ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
24417
24418   { "close",        (sqlite3_syscall_ptr)close,      0  },
24419 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24420
24421   { "access",       (sqlite3_syscall_ptr)access,     0  },
24422 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24423
24424   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24425 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24426
24427   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24428 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24429
24430 /*
24431 ** The DJGPP compiler environment looks mostly like Unix, but it
24432 ** lacks the fcntl() system call.  So redefine fcntl() to be something
24433 ** that always succeeds.  This means that locking does not occur under
24434 ** DJGPP.  But it is DOS - what did you expect?
24435 */
24436 #ifdef __DJGPP__
24437   { "fstat",        0,                 0  },
24438 #define osFstat(a,b,c)    0
24439 #else     
24440   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24441 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24442 #endif
24443
24444   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24445 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24446
24447   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24448 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24449
24450   { "read",         (sqlite3_syscall_ptr)read,       0  },
24451 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24452
24453 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24454   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24455 #else
24456   { "pread",        (sqlite3_syscall_ptr)0,          0  },
24457 #endif
24458 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24459
24460 #if defined(USE_PREAD64)
24461   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24462 #else
24463   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24464 #endif
24465 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24466
24467   { "write",        (sqlite3_syscall_ptr)write,      0  },
24468 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24469
24470 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24471   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24472 #else
24473   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24474 #endif
24475 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24476                     aSyscall[12].pCurrent)
24477
24478 #if defined(USE_PREAD64)
24479   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24480 #else
24481   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24482 #endif
24483 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24484                     aSyscall[13].pCurrent)
24485
24486 #if SQLITE_ENABLE_LOCKING_STYLE
24487   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24488 #else
24489   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
24490 #endif
24491 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24492
24493 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24494   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24495 #else
24496   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24497 #endif
24498 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24499
24500 }; /* End of the overrideable system calls */
24501
24502 /*
24503 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24504 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24505 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24506 ** system call named zName.
24507 */
24508 static int unixSetSystemCall(
24509   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24510   const char *zName,            /* Name of system call to override */
24511   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24512 ){
24513   unsigned int i;
24514   int rc = SQLITE_NOTFOUND;
24515
24516   UNUSED_PARAMETER(pNotUsed);
24517   if( zName==0 ){
24518     /* If no zName is given, restore all system calls to their default
24519     ** settings and return NULL
24520     */
24521     rc = SQLITE_OK;
24522     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24523       if( aSyscall[i].pDefault ){
24524         aSyscall[i].pCurrent = aSyscall[i].pDefault;
24525       }
24526     }
24527   }else{
24528     /* If zName is specified, operate on only the one system call
24529     ** specified.
24530     */
24531     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24532       if( strcmp(zName, aSyscall[i].zName)==0 ){
24533         if( aSyscall[i].pDefault==0 ){
24534           aSyscall[i].pDefault = aSyscall[i].pCurrent;
24535         }
24536         rc = SQLITE_OK;
24537         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24538         aSyscall[i].pCurrent = pNewFunc;
24539         break;
24540       }
24541     }
24542   }
24543   return rc;
24544 }
24545
24546 /*
24547 ** Return the value of a system call.  Return NULL if zName is not a
24548 ** recognized system call name.  NULL is also returned if the system call
24549 ** is currently undefined.
24550 */
24551 static sqlite3_syscall_ptr unixGetSystemCall(
24552   sqlite3_vfs *pNotUsed,
24553   const char *zName
24554 ){
24555   unsigned int i;
24556
24557   UNUSED_PARAMETER(pNotUsed);
24558   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24559     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24560   }
24561   return 0;
24562 }
24563
24564 /*
24565 ** Return the name of the first system call after zName.  If zName==NULL
24566 ** then return the name of the first system call.  Return NULL if zName
24567 ** is the last system call or if zName is not the name of a valid
24568 ** system call.
24569 */
24570 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24571   int i = -1;
24572
24573   UNUSED_PARAMETER(p);
24574   if( zName ){
24575     for(i=0; i<ArraySize(aSyscall)-1; i++){
24576       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24577     }
24578   }
24579   for(i++; i<ArraySize(aSyscall); i++){
24580     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24581   }
24582   return 0;
24583 }
24584
24585 /*
24586 ** Retry open() calls that fail due to EINTR
24587 */
24588 static int robust_open(const char *z, int f, int m){
24589   int rc;
24590   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24591   return rc;
24592 }
24593
24594 /*
24595 ** Helper functions to obtain and relinquish the global mutex. The
24596 ** global mutex is used to protect the unixInodeInfo and
24597 ** vxworksFileId objects used by this file, all of which may be 
24598 ** shared by multiple threads.
24599 **
24600 ** Function unixMutexHeld() is used to assert() that the global mutex 
24601 ** is held when required. This function is only used as part of assert() 
24602 ** statements. e.g.
24603 **
24604 **   unixEnterMutex()
24605 **     assert( unixMutexHeld() );
24606 **   unixEnterLeave()
24607 */
24608 static void unixEnterMutex(void){
24609   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24610 }
24611 static void unixLeaveMutex(void){
24612   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24613 }
24614 #ifdef SQLITE_DEBUG
24615 static int unixMutexHeld(void) {
24616   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24617 }
24618 #endif
24619
24620
24621 #ifdef SQLITE_DEBUG
24622 /*
24623 ** Helper function for printing out trace information from debugging
24624 ** binaries. This returns the string represetation of the supplied
24625 ** integer lock-type.
24626 */
24627 static const char *azFileLock(int eFileLock){
24628   switch( eFileLock ){
24629     case NO_LOCK: return "NONE";
24630     case SHARED_LOCK: return "SHARED";
24631     case RESERVED_LOCK: return "RESERVED";
24632     case PENDING_LOCK: return "PENDING";
24633     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24634   }
24635   return "ERROR";
24636 }
24637 #endif
24638
24639 #ifdef SQLITE_LOCK_TRACE
24640 /*
24641 ** Print out information about all locking operations.
24642 **
24643 ** This routine is used for troubleshooting locks on multithreaded
24644 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
24645 ** command-line option on the compiler.  This code is normally
24646 ** turned off.
24647 */
24648 static int lockTrace(int fd, int op, struct flock *p){
24649   char *zOpName, *zType;
24650   int s;
24651   int savedErrno;
24652   if( op==F_GETLK ){
24653     zOpName = "GETLK";
24654   }else if( op==F_SETLK ){
24655     zOpName = "SETLK";
24656   }else{
24657     s = osFcntl(fd, op, p);
24658     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24659     return s;
24660   }
24661   if( p->l_type==F_RDLCK ){
24662     zType = "RDLCK";
24663   }else if( p->l_type==F_WRLCK ){
24664     zType = "WRLCK";
24665   }else if( p->l_type==F_UNLCK ){
24666     zType = "UNLCK";
24667   }else{
24668     assert( 0 );
24669   }
24670   assert( p->l_whence==SEEK_SET );
24671   s = osFcntl(fd, op, p);
24672   savedErrno = errno;
24673   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24674      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24675      (int)p->l_pid, s);
24676   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24677     struct flock l2;
24678     l2 = *p;
24679     osFcntl(fd, F_GETLK, &l2);
24680     if( l2.l_type==F_RDLCK ){
24681       zType = "RDLCK";
24682     }else if( l2.l_type==F_WRLCK ){
24683       zType = "WRLCK";
24684     }else if( l2.l_type==F_UNLCK ){
24685       zType = "UNLCK";
24686     }else{
24687       assert( 0 );
24688     }
24689     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24690        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24691   }
24692   errno = savedErrno;
24693   return s;
24694 }
24695 #undef osFcntl
24696 #define osFcntl lockTrace
24697 #endif /* SQLITE_LOCK_TRACE */
24698
24699 /*
24700 ** Retry ftruncate() calls that fail due to EINTR
24701 */
24702 static int robust_ftruncate(int h, sqlite3_int64 sz){
24703   int rc;
24704   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24705   return rc;
24706 }
24707
24708 /*
24709 ** This routine translates a standard POSIX errno code into something
24710 ** useful to the clients of the sqlite3 functions.  Specifically, it is
24711 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24712 ** and a variety of "please close the file descriptor NOW" errors into 
24713 ** SQLITE_IOERR
24714 ** 
24715 ** Errors during initialization of locks, or file system support for locks,
24716 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24717 */
24718 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24719   switch (posixError) {
24720 #if 0
24721   /* At one point this code was not commented out. In theory, this branch
24722   ** should never be hit, as this function should only be called after
24723   ** a locking-related function (i.e. fcntl()) has returned non-zero with
24724   ** the value of errno as the first argument. Since a system call has failed,
24725   ** errno should be non-zero.
24726   **
24727   ** Despite this, if errno really is zero, we still don't want to return
24728   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24729   ** propagated back to the caller. Commenting this branch out means errno==0
24730   ** will be handled by the "default:" case below.
24731   */
24732   case 0: 
24733     return SQLITE_OK;
24734 #endif
24735
24736   case EAGAIN:
24737   case ETIMEDOUT:
24738   case EBUSY:
24739   case EINTR:
24740   case ENOLCK:  
24741     /* random NFS retry error, unless during file system support 
24742      * introspection, in which it actually means what it says */
24743     return SQLITE_BUSY;
24744     
24745   case EACCES: 
24746     /* EACCES is like EAGAIN during locking operations, but not any other time*/
24747     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
24748         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
24749         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24750         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24751       return SQLITE_BUSY;
24752     }
24753     /* else fall through */
24754   case EPERM: 
24755     return SQLITE_PERM;
24756     
24757   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24758   ** this module never makes such a call. And the code in SQLite itself 
24759   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24760   ** this case is also commented out. If the system does set errno to EDEADLK,
24761   ** the default SQLITE_IOERR_XXX code will be returned. */
24762 #if 0
24763   case EDEADLK:
24764     return SQLITE_IOERR_BLOCKED;
24765 #endif
24766     
24767 #if EOPNOTSUPP!=ENOTSUP
24768   case EOPNOTSUPP: 
24769     /* something went terribly awry, unless during file system support 
24770      * introspection, in which it actually means what it says */
24771 #endif
24772 #ifdef ENOTSUP
24773   case ENOTSUP: 
24774     /* invalid fd, unless during file system support introspection, in which 
24775      * it actually means what it says */
24776 #endif
24777   case EIO:
24778   case EBADF:
24779   case EINVAL:
24780   case ENOTCONN:
24781   case ENODEV:
24782   case ENXIO:
24783   case ENOENT:
24784   case ESTALE:
24785   case ENOSYS:
24786     /* these should force the client to close the file and reconnect */
24787     
24788   default: 
24789     return sqliteIOErr;
24790   }
24791 }
24792
24793
24794
24795 /******************************************************************************
24796 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24797 **
24798 ** On most versions of unix, we can get a unique ID for a file by concatenating
24799 ** the device number and the inode number.  But this does not work on VxWorks.
24800 ** On VxWorks, a unique file id must be based on the canonical filename.
24801 **
24802 ** A pointer to an instance of the following structure can be used as a
24803 ** unique file ID in VxWorks.  Each instance of this structure contains
24804 ** a copy of the canonical filename.  There is also a reference count.  
24805 ** The structure is reclaimed when the number of pointers to it drops to
24806 ** zero.
24807 **
24808 ** There are never very many files open at one time and lookups are not
24809 ** a performance-critical path, so it is sufficient to put these
24810 ** structures on a linked list.
24811 */
24812 struct vxworksFileId {
24813   struct vxworksFileId *pNext;  /* Next in a list of them all */
24814   int nRef;                     /* Number of references to this one */
24815   int nName;                    /* Length of the zCanonicalName[] string */
24816   char *zCanonicalName;         /* Canonical filename */
24817 };
24818
24819 #if OS_VXWORKS
24820 /* 
24821 ** All unique filenames are held on a linked list headed by this
24822 ** variable:
24823 */
24824 static struct vxworksFileId *vxworksFileList = 0;
24825
24826 /*
24827 ** Simplify a filename into its canonical form
24828 ** by making the following changes:
24829 **
24830 **  * removing any trailing and duplicate /
24831 **  * convert /./ into just /
24832 **  * convert /A/../ where A is any simple name into just /
24833 **
24834 ** Changes are made in-place.  Return the new name length.
24835 **
24836 ** The original filename is in z[0..n-1].  Return the number of
24837 ** characters in the simplified name.
24838 */
24839 static int vxworksSimplifyName(char *z, int n){
24840   int i, j;
24841   while( n>1 && z[n-1]=='/' ){ n--; }
24842   for(i=j=0; i<n; i++){
24843     if( z[i]=='/' ){
24844       if( z[i+1]=='/' ) continue;
24845       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24846         i += 1;
24847         continue;
24848       }
24849       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24850         while( j>0 && z[j-1]!='/' ){ j--; }
24851         if( j>0 ){ j--; }
24852         i += 2;
24853         continue;
24854       }
24855     }
24856     z[j++] = z[i];
24857   }
24858   z[j] = 0;
24859   return j;
24860 }
24861
24862 /*
24863 ** Find a unique file ID for the given absolute pathname.  Return
24864 ** a pointer to the vxworksFileId object.  This pointer is the unique
24865 ** file ID.
24866 **
24867 ** The nRef field of the vxworksFileId object is incremented before
24868 ** the object is returned.  A new vxworksFileId object is created
24869 ** and added to the global list if necessary.
24870 **
24871 ** If a memory allocation error occurs, return NULL.
24872 */
24873 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24874   struct vxworksFileId *pNew;         /* search key and new file ID */
24875   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
24876   int n;                              /* Length of zAbsoluteName string */
24877
24878   assert( zAbsoluteName[0]=='/' );
24879   n = (int)strlen(zAbsoluteName);
24880   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24881   if( pNew==0 ) return 0;
24882   pNew->zCanonicalName = (char*)&pNew[1];
24883   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24884   n = vxworksSimplifyName(pNew->zCanonicalName, n);
24885
24886   /* Search for an existing entry that matching the canonical name.
24887   ** If found, increment the reference count and return a pointer to
24888   ** the existing file ID.
24889   */
24890   unixEnterMutex();
24891   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24892     if( pCandidate->nName==n 
24893      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24894     ){
24895        sqlite3_free(pNew);
24896        pCandidate->nRef++;
24897        unixLeaveMutex();
24898        return pCandidate;
24899     }
24900   }
24901
24902   /* No match was found.  We will make a new file ID */
24903   pNew->nRef = 1;
24904   pNew->nName = n;
24905   pNew->pNext = vxworksFileList;
24906   vxworksFileList = pNew;
24907   unixLeaveMutex();
24908   return pNew;
24909 }
24910
24911 /*
24912 ** Decrement the reference count on a vxworksFileId object.  Free
24913 ** the object when the reference count reaches zero.
24914 */
24915 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24916   unixEnterMutex();
24917   assert( pId->nRef>0 );
24918   pId->nRef--;
24919   if( pId->nRef==0 ){
24920     struct vxworksFileId **pp;
24921     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24922     assert( *pp==pId );
24923     *pp = pId->pNext;
24924     sqlite3_free(pId);
24925   }
24926   unixLeaveMutex();
24927 }
24928 #endif /* OS_VXWORKS */
24929 /*************** End of Unique File ID Utility Used By VxWorks ****************
24930 ******************************************************************************/
24931
24932
24933 /******************************************************************************
24934 *************************** Posix Advisory Locking ****************************
24935 **
24936 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24937 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24938 ** sets or clears a lock, that operation overrides any prior locks set
24939 ** by the same process.  It does not explicitly say so, but this implies
24940 ** that it overrides locks set by the same process using a different
24941 ** file descriptor.  Consider this test case:
24942 **
24943 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24944 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24945 **
24946 ** Suppose ./file1 and ./file2 are really the same file (because
24947 ** one is a hard or symbolic link to the other) then if you set
24948 ** an exclusive lock on fd1, then try to get an exclusive lock
24949 ** on fd2, it works.  I would have expected the second lock to
24950 ** fail since there was already a lock on the file due to fd1.
24951 ** But not so.  Since both locks came from the same process, the
24952 ** second overrides the first, even though they were on different
24953 ** file descriptors opened on different file names.
24954 **
24955 ** This means that we cannot use POSIX locks to synchronize file access
24956 ** among competing threads of the same process.  POSIX locks will work fine
24957 ** to synchronize access for threads in separate processes, but not
24958 ** threads within the same process.
24959 **
24960 ** To work around the problem, SQLite has to manage file locks internally
24961 ** on its own.  Whenever a new database is opened, we have to find the
24962 ** specific inode of the database file (the inode is determined by the
24963 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24964 ** and check for locks already existing on that inode.  When locks are
24965 ** created or removed, we have to look at our own internal record of the
24966 ** locks to see if another thread has previously set a lock on that same
24967 ** inode.
24968 **
24969 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24970 ** For VxWorks, we have to use the alternative unique ID system based on
24971 ** canonical filename and implemented in the previous division.)
24972 **
24973 ** The sqlite3_file structure for POSIX is no longer just an integer file
24974 ** descriptor.  It is now a structure that holds the integer file
24975 ** descriptor and a pointer to a structure that describes the internal
24976 ** locks on the corresponding inode.  There is one locking structure
24977 ** per inode, so if the same inode is opened twice, both unixFile structures
24978 ** point to the same locking structure.  The locking structure keeps
24979 ** a reference count (so we will know when to delete it) and a "cnt"
24980 ** field that tells us its internal lock status.  cnt==0 means the
24981 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24982 ** cnt>0 means there are cnt shared locks on the file.
24983 **
24984 ** Any attempt to lock or unlock a file first checks the locking
24985 ** structure.  The fcntl() system call is only invoked to set a 
24986 ** POSIX lock if the internal lock structure transitions between
24987 ** a locked and an unlocked state.
24988 **
24989 ** But wait:  there are yet more problems with POSIX advisory locks.
24990 **
24991 ** If you close a file descriptor that points to a file that has locks,
24992 ** all locks on that file that are owned by the current process are
24993 ** released.  To work around this problem, each unixInodeInfo object
24994 ** maintains a count of the number of pending locks on tha inode.
24995 ** When an attempt is made to close an unixFile, if there are
24996 ** other unixFile open on the same inode that are holding locks, the call
24997 ** to close() the file descriptor is deferred until all of the locks clear.
24998 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24999 ** be closed and that list is walked (and cleared) when the last lock
25000 ** clears.
25001 **
25002 ** Yet another problem:  LinuxThreads do not play well with posix locks.
25003 **
25004 ** Many older versions of linux use the LinuxThreads library which is
25005 ** not posix compliant.  Under LinuxThreads, a lock created by thread
25006 ** A cannot be modified or overridden by a different thread B.
25007 ** Only thread A can modify the lock.  Locking behavior is correct
25008 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25009 ** on linux - with NPTL a lock created by thread A can override locks
25010 ** in thread B.  But there is no way to know at compile-time which
25011 ** threading library is being used.  So there is no way to know at
25012 ** compile-time whether or not thread A can override locks on thread B.
25013 ** One has to do a run-time check to discover the behavior of the
25014 ** current process.
25015 **
25016 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
25017 ** was dropped beginning with version 3.7.0.  SQLite will still work with
25018 ** LinuxThreads provided that (1) there is no more than one connection 
25019 ** per database file in the same process and (2) database connections
25020 ** do not move across threads.
25021 */
25022
25023 /*
25024 ** An instance of the following structure serves as the key used
25025 ** to locate a particular unixInodeInfo object.
25026 */
25027 struct unixFileId {
25028   dev_t dev;                  /* Device number */
25029 #if OS_VXWORKS
25030   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25031 #else
25032   ino_t ino;                  /* Inode number */
25033 #endif
25034 };
25035
25036 /*
25037 ** An instance of the following structure is allocated for each open
25038 ** inode.  Or, on LinuxThreads, there is one of these structures for
25039 ** each inode opened by each thread.
25040 **
25041 ** A single inode can have multiple file descriptors, so each unixFile
25042 ** structure contains a pointer to an instance of this object and this
25043 ** object keeps a count of the number of unixFile pointing to it.
25044 */
25045 struct unixInodeInfo {
25046   struct unixFileId fileId;       /* The lookup key */
25047   int nShared;                    /* Number of SHARED locks held */
25048   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25049   unsigned char bProcessLock;     /* An exclusive process lock is held */
25050   int nRef;                       /* Number of pointers to this structure */
25051   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25052   int nLock;                      /* Number of outstanding file locks */
25053   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25054   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25055   unixInodeInfo *pPrev;           /*    .... doubly linked */
25056 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
25057   unsigned long long sharedByte;  /* for AFP simulated shared lock */
25058 #endif
25059 #if OS_VXWORKS
25060   sem_t *pSem;                    /* Named POSIX semaphore */
25061   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25062 #endif
25063 };
25064
25065 /*
25066 ** A lists of all unixInodeInfo objects.
25067 */
25068 static unixInodeInfo *inodeList = 0;
25069
25070 /*
25071 **
25072 ** This function - unixLogError_x(), is only ever called via the macro
25073 ** unixLogError().
25074 **
25075 ** It is invoked after an error occurs in an OS function and errno has been
25076 ** set. It logs a message using sqlite3_log() containing the current value of
25077 ** errno and, if possible, the human-readable equivalent from strerror() or
25078 ** strerror_r().
25079 **
25080 ** The first argument passed to the macro should be the error code that
25081 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
25082 ** The two subsequent arguments should be the name of the OS function that
25083 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25084 ** if any.
25085 */
25086 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25087 static int unixLogErrorAtLine(
25088   int errcode,                    /* SQLite error code */
25089   const char *zFunc,              /* Name of OS function that failed */
25090   const char *zPath,              /* File path associated with error */
25091   int iLine                       /* Source line number where error occurred */
25092 ){
25093   char *zErr;                     /* Message from strerror() or equivalent */
25094   int iErrno = errno;             /* Saved syscall error number */
25095
25096   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25097   ** the strerror() function to obtain the human-readable error message
25098   ** equivalent to errno. Otherwise, use strerror_r().
25099   */ 
25100 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25101   char aErr[80];
25102   memset(aErr, 0, sizeof(aErr));
25103   zErr = aErr;
25104
25105   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25106   ** assume that the system provides the the GNU version of strerror_r() that 
25107   ** returns a pointer to a buffer containing the error message. That pointer 
25108   ** may point to aErr[], or it may point to some static storage somewhere. 
25109   ** Otherwise, assume that the system provides the POSIX version of 
25110   ** strerror_r(), which always writes an error message into aErr[].
25111   **
25112   ** If the code incorrectly assumes that it is the POSIX version that is
25113   ** available, the error message will often be an empty string. Not a
25114   ** huge problem. Incorrectly concluding that the GNU version is available 
25115   ** could lead to a segfault though.
25116   */
25117 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25118   zErr = 
25119 # endif
25120   strerror_r(iErrno, aErr, sizeof(aErr)-1);
25121
25122 #elif SQLITE_THREADSAFE
25123   /* This is a threadsafe build, but strerror_r() is not available. */
25124   zErr = "";
25125 #else
25126   /* Non-threadsafe build, use strerror(). */
25127   zErr = strerror(iErrno);
25128 #endif
25129
25130   assert( errcode!=SQLITE_OK );
25131   if( zPath==0 ) zPath = "";
25132   sqlite3_log(errcode,
25133       "os_unix.c:%d: (%d) %s(%s) - %s",
25134       iLine, iErrno, zFunc, zPath, zErr
25135   );
25136
25137   return errcode;
25138 }
25139
25140 /*
25141 ** Close a file descriptor.
25142 **
25143 ** We assume that close() almost always works, since it is only in a
25144 ** very sick application or on a very sick platform that it might fail.
25145 ** If it does fail, simply leak the file descriptor, but do log the
25146 ** error.
25147 **
25148 ** Note that it is not safe to retry close() after EINTR since the
25149 ** file descriptor might have already been reused by another thread.
25150 ** So we don't even try to recover from an EINTR.  Just log the error
25151 ** and move on.
25152 */
25153 static void robust_close(unixFile *pFile, int h, int lineno){
25154   if( osClose(h) ){
25155     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25156                        pFile ? pFile->zPath : 0, lineno);
25157   }
25158 }
25159
25160 /*
25161 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25162 */ 
25163 static void closePendingFds(unixFile *pFile){
25164   unixInodeInfo *pInode = pFile->pInode;
25165   UnixUnusedFd *p;
25166   UnixUnusedFd *pNext;
25167   for(p=pInode->pUnused; p; p=pNext){
25168     pNext = p->pNext;
25169     robust_close(pFile, p->fd, __LINE__);
25170     sqlite3_free(p);
25171   }
25172   pInode->pUnused = 0;
25173 }
25174
25175 /*
25176 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25177 **
25178 ** The mutex entered using the unixEnterMutex() function must be held
25179 ** when this function is called.
25180 */
25181 static void releaseInodeInfo(unixFile *pFile){
25182   unixInodeInfo *pInode = pFile->pInode;
25183   assert( unixMutexHeld() );
25184   if( ALWAYS(pInode) ){
25185     pInode->nRef--;
25186     if( pInode->nRef==0 ){
25187       assert( pInode->pShmNode==0 );
25188       closePendingFds(pFile);
25189       if( pInode->pPrev ){
25190         assert( pInode->pPrev->pNext==pInode );
25191         pInode->pPrev->pNext = pInode->pNext;
25192       }else{
25193         assert( inodeList==pInode );
25194         inodeList = pInode->pNext;
25195       }
25196       if( pInode->pNext ){
25197         assert( pInode->pNext->pPrev==pInode );
25198         pInode->pNext->pPrev = pInode->pPrev;
25199       }
25200       sqlite3_free(pInode);
25201     }
25202   }
25203 }
25204
25205 /*
25206 ** Given a file descriptor, locate the unixInodeInfo object that
25207 ** describes that file descriptor.  Create a new one if necessary.  The
25208 ** return value might be uninitialized if an error occurs.
25209 **
25210 ** The mutex entered using the unixEnterMutex() function must be held
25211 ** when this function is called.
25212 **
25213 ** Return an appropriate error code.
25214 */
25215 static int findInodeInfo(
25216   unixFile *pFile,               /* Unix file with file desc used in the key */
25217   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25218 ){
25219   int rc;                        /* System call return code */
25220   int fd;                        /* The file descriptor for pFile */
25221   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25222   struct stat statbuf;           /* Low-level file information */
25223   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25224
25225   assert( unixMutexHeld() );
25226
25227   /* Get low-level information about the file that we can used to
25228   ** create a unique name for the file.
25229   */
25230   fd = pFile->h;
25231   rc = osFstat(fd, &statbuf);
25232   if( rc!=0 ){
25233     pFile->lastErrno = errno;
25234 #ifdef EOVERFLOW
25235     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25236 #endif
25237     return SQLITE_IOERR;
25238   }
25239
25240 #ifdef __APPLE__
25241   /* On OS X on an msdos filesystem, the inode number is reported
25242   ** incorrectly for zero-size files.  See ticket #3260.  To work
25243   ** around this problem (we consider it a bug in OS X, not SQLite)
25244   ** we always increase the file size to 1 by writing a single byte
25245   ** prior to accessing the inode number.  The one byte written is
25246   ** an ASCII 'S' character which also happens to be the first byte
25247   ** in the header of every SQLite database.  In this way, if there
25248   ** is a race condition such that another thread has already populated
25249   ** the first page of the database, no damage is done.
25250   */
25251   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25252     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25253     if( rc!=1 ){
25254       pFile->lastErrno = errno;
25255       return SQLITE_IOERR;
25256     }
25257     rc = osFstat(fd, &statbuf);
25258     if( rc!=0 ){
25259       pFile->lastErrno = errno;
25260       return SQLITE_IOERR;
25261     }
25262   }
25263 #endif
25264
25265   memset(&fileId, 0, sizeof(fileId));
25266   fileId.dev = statbuf.st_dev;
25267 #if OS_VXWORKS
25268   fileId.pId = pFile->pId;
25269 #else
25270   fileId.ino = statbuf.st_ino;
25271 #endif
25272   pInode = inodeList;
25273   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25274     pInode = pInode->pNext;
25275   }
25276   if( pInode==0 ){
25277     pInode = sqlite3_malloc( sizeof(*pInode) );
25278     if( pInode==0 ){
25279       return SQLITE_NOMEM;
25280     }
25281     memset(pInode, 0, sizeof(*pInode));
25282     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25283     pInode->nRef = 1;
25284     pInode->pNext = inodeList;
25285     pInode->pPrev = 0;
25286     if( inodeList ) inodeList->pPrev = pInode;
25287     inodeList = pInode;
25288   }else{
25289     pInode->nRef++;
25290   }
25291   *ppInode = pInode;
25292   return SQLITE_OK;
25293 }
25294
25295
25296 /*
25297 ** This routine checks if there is a RESERVED lock held on the specified
25298 ** file by this or any other process. If such a lock is held, set *pResOut
25299 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25300 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25301 */
25302 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25303   int rc = SQLITE_OK;
25304   int reserved = 0;
25305   unixFile *pFile = (unixFile*)id;
25306
25307   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25308
25309   assert( pFile );
25310   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25311
25312   /* Check if a thread in this process holds such a lock */
25313   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25314     reserved = 1;
25315   }
25316
25317   /* Otherwise see if some other process holds it.
25318   */
25319 #ifndef __DJGPP__
25320   if( !reserved && !pFile->pInode->bProcessLock ){
25321     struct flock lock;
25322     lock.l_whence = SEEK_SET;
25323     lock.l_start = RESERVED_BYTE;
25324     lock.l_len = 1;
25325     lock.l_type = F_WRLCK;
25326     if( osFcntl(pFile->h, F_GETLK, &lock) ){
25327       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25328       pFile->lastErrno = errno;
25329     } else if( lock.l_type!=F_UNLCK ){
25330       reserved = 1;
25331     }
25332   }
25333 #endif
25334   
25335   unixLeaveMutex();
25336   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25337
25338   *pResOut = reserved;
25339   return rc;
25340 }
25341
25342 /*
25343 ** Attempt to set a system-lock on the file pFile.  The lock is 
25344 ** described by pLock.
25345 **
25346 ** If the pFile was opened read/write from unix-excl, then the only lock
25347 ** ever obtained is an exclusive lock, and it is obtained exactly once
25348 ** the first time any lock is attempted.  All subsequent system locking
25349 ** operations become no-ops.  Locking operations still happen internally,
25350 ** in order to coordinate access between separate database connections
25351 ** within this process, but all of that is handled in memory and the
25352 ** operating system does not participate.
25353 **
25354 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25355 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25356 ** and is read-only.
25357 **
25358 ** Zero is returned if the call completes successfully, or -1 if a call
25359 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25360 */
25361 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25362   int rc;
25363   unixInodeInfo *pInode = pFile->pInode;
25364   assert( unixMutexHeld() );
25365   assert( pInode!=0 );
25366   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25367    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25368   ){
25369     if( pInode->bProcessLock==0 ){
25370       struct flock lock;
25371       assert( pInode->nLock==0 );
25372       lock.l_whence = SEEK_SET;
25373       lock.l_start = SHARED_FIRST;
25374       lock.l_len = SHARED_SIZE;
25375       lock.l_type = F_WRLCK;
25376       rc = osFcntl(pFile->h, F_SETLK, &lock);
25377       if( rc<0 ) return rc;
25378       pInode->bProcessLock = 1;
25379       pInode->nLock++;
25380     }else{
25381       rc = 0;
25382     }
25383   }else{
25384     rc = osFcntl(pFile->h, F_SETLK, pLock);
25385   }
25386   return rc;
25387 }
25388
25389 /*
25390 ** Lock the file with the lock specified by parameter eFileLock - one
25391 ** of the following:
25392 **
25393 **     (1) SHARED_LOCK
25394 **     (2) RESERVED_LOCK
25395 **     (3) PENDING_LOCK
25396 **     (4) EXCLUSIVE_LOCK
25397 **
25398 ** Sometimes when requesting one lock state, additional lock states
25399 ** are inserted in between.  The locking might fail on one of the later
25400 ** transitions leaving the lock state different from what it started but
25401 ** still short of its goal.  The following chart shows the allowed
25402 ** transitions and the inserted intermediate states:
25403 **
25404 **    UNLOCKED -> SHARED
25405 **    SHARED -> RESERVED
25406 **    SHARED -> (PENDING) -> EXCLUSIVE
25407 **    RESERVED -> (PENDING) -> EXCLUSIVE
25408 **    PENDING -> EXCLUSIVE
25409 **
25410 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25411 ** routine to lower a locking level.
25412 */
25413 static int unixLock(sqlite3_file *id, int eFileLock){
25414   /* The following describes the implementation of the various locks and
25415   ** lock transitions in terms of the POSIX advisory shared and exclusive
25416   ** lock primitives (called read-locks and write-locks below, to avoid
25417   ** confusion with SQLite lock names). The algorithms are complicated
25418   ** slightly in order to be compatible with windows systems simultaneously
25419   ** accessing the same database file, in case that is ever required.
25420   **
25421   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25422   ** byte', each single bytes at well known offsets, and the 'shared byte
25423   ** range', a range of 510 bytes at a well known offset.
25424   **
25425   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25426   ** byte'.  If this is successful, a random byte from the 'shared byte
25427   ** range' is read-locked and the lock on the 'pending byte' released.
25428   **
25429   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25430   ** A RESERVED lock is implemented by grabbing a write-lock on the
25431   ** 'reserved byte'. 
25432   **
25433   ** A process may only obtain a PENDING lock after it has obtained a
25434   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25435   ** on the 'pending byte'. This ensures that no new SHARED locks can be
25436   ** obtained, but existing SHARED locks are allowed to persist. A process
25437   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25438   ** This property is used by the algorithm for rolling back a journal file
25439   ** after a crash.
25440   **
25441   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25442   ** implemented by obtaining a write-lock on the entire 'shared byte
25443   ** range'. Since all other locks require a read-lock on one of the bytes
25444   ** within this range, this ensures that no other locks are held on the
25445   ** database. 
25446   **
25447   ** The reason a single byte cannot be used instead of the 'shared byte
25448   ** range' is that some versions of windows do not support read-locks. By
25449   ** locking a random byte from a range, concurrent SHARED locks may exist
25450   ** even if the locking primitive used is always a write-lock.
25451   */
25452   int rc = SQLITE_OK;
25453   unixFile *pFile = (unixFile*)id;
25454   unixInodeInfo *pInode = pFile->pInode;
25455   struct flock lock;
25456   int tErrno = 0;
25457
25458   assert( pFile );
25459   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25460       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25461       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25462
25463   /* If there is already a lock of this type or more restrictive on the
25464   ** unixFile, do nothing. Don't use the end_lock: exit path, as
25465   ** unixEnterMutex() hasn't been called yet.
25466   */
25467   if( pFile->eFileLock>=eFileLock ){
25468     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25469             azFileLock(eFileLock)));
25470     return SQLITE_OK;
25471   }
25472
25473   /* Make sure the locking sequence is correct.
25474   **  (1) We never move from unlocked to anything higher than shared lock.
25475   **  (2) SQLite never explicitly requests a pendig lock.
25476   **  (3) A shared lock is always held when a reserve lock is requested.
25477   */
25478   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25479   assert( eFileLock!=PENDING_LOCK );
25480   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25481
25482   /* This mutex is needed because pFile->pInode is shared across threads
25483   */
25484   unixEnterMutex();
25485   pInode = pFile->pInode;
25486
25487   /* If some thread using this PID has a lock via a different unixFile*
25488   ** handle that precludes the requested lock, return BUSY.
25489   */
25490   if( (pFile->eFileLock!=pInode->eFileLock && 
25491           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25492   ){
25493     rc = SQLITE_BUSY;
25494     goto end_lock;
25495   }
25496
25497   /* If a SHARED lock is requested, and some thread using this PID already
25498   ** has a SHARED or RESERVED lock, then increment reference counts and
25499   ** return SQLITE_OK.
25500   */
25501   if( eFileLock==SHARED_LOCK && 
25502       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25503     assert( eFileLock==SHARED_LOCK );
25504     assert( pFile->eFileLock==0 );
25505     assert( pInode->nShared>0 );
25506     pFile->eFileLock = SHARED_LOCK;
25507     pInode->nShared++;
25508     pInode->nLock++;
25509     goto end_lock;
25510   }
25511
25512
25513   /* A PENDING lock is needed before acquiring a SHARED lock and before
25514   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25515   ** be released.
25516   */
25517   lock.l_len = 1L;
25518   lock.l_whence = SEEK_SET;
25519   if( eFileLock==SHARED_LOCK 
25520       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25521   ){
25522     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25523     lock.l_start = PENDING_BYTE;
25524     if( unixFileLock(pFile, &lock) ){
25525       tErrno = errno;
25526       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25527       if( rc!=SQLITE_BUSY ){
25528         pFile->lastErrno = tErrno;
25529       }
25530       goto end_lock;
25531     }
25532   }
25533
25534
25535   /* If control gets to this point, then actually go ahead and make
25536   ** operating system calls for the specified lock.
25537   */
25538   if( eFileLock==SHARED_LOCK ){
25539     assert( pInode->nShared==0 );
25540     assert( pInode->eFileLock==0 );
25541     assert( rc==SQLITE_OK );
25542
25543     /* Now get the read-lock */
25544     lock.l_start = SHARED_FIRST;
25545     lock.l_len = SHARED_SIZE;
25546     if( unixFileLock(pFile, &lock) ){
25547       tErrno = errno;
25548       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25549     }
25550
25551     /* Drop the temporary PENDING lock */
25552     lock.l_start = PENDING_BYTE;
25553     lock.l_len = 1L;
25554     lock.l_type = F_UNLCK;
25555     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25556       /* This could happen with a network mount */
25557       tErrno = errno;
25558       rc = SQLITE_IOERR_UNLOCK; 
25559     }
25560
25561     if( rc ){
25562       if( rc!=SQLITE_BUSY ){
25563         pFile->lastErrno = tErrno;
25564       }
25565       goto end_lock;
25566     }else{
25567       pFile->eFileLock = SHARED_LOCK;
25568       pInode->nLock++;
25569       pInode->nShared = 1;
25570     }
25571   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25572     /* We are trying for an exclusive lock but another thread in this
25573     ** same process is still holding a shared lock. */
25574     rc = SQLITE_BUSY;
25575   }else{
25576     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25577     ** assumed that there is a SHARED or greater lock on the file
25578     ** already.
25579     */
25580     assert( 0!=pFile->eFileLock );
25581     lock.l_type = F_WRLCK;
25582
25583     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25584     if( eFileLock==RESERVED_LOCK ){
25585       lock.l_start = RESERVED_BYTE;
25586       lock.l_len = 1L;
25587     }else{
25588       lock.l_start = SHARED_FIRST;
25589       lock.l_len = SHARED_SIZE;
25590     }
25591
25592     if( unixFileLock(pFile, &lock) ){
25593       tErrno = errno;
25594       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25595       if( rc!=SQLITE_BUSY ){
25596         pFile->lastErrno = tErrno;
25597       }
25598     }
25599   }
25600   
25601
25602 #ifndef NDEBUG
25603   /* Set up the transaction-counter change checking flags when
25604   ** transitioning from a SHARED to a RESERVED lock.  The change
25605   ** from SHARED to RESERVED marks the beginning of a normal
25606   ** write operation (not a hot journal rollback).
25607   */
25608   if( rc==SQLITE_OK
25609    && pFile->eFileLock<=SHARED_LOCK
25610    && eFileLock==RESERVED_LOCK
25611   ){
25612     pFile->transCntrChng = 0;
25613     pFile->dbUpdate = 0;
25614     pFile->inNormalWrite = 1;
25615   }
25616 #endif
25617
25618
25619   if( rc==SQLITE_OK ){
25620     pFile->eFileLock = eFileLock;
25621     pInode->eFileLock = eFileLock;
25622   }else if( eFileLock==EXCLUSIVE_LOCK ){
25623     pFile->eFileLock = PENDING_LOCK;
25624     pInode->eFileLock = PENDING_LOCK;
25625   }
25626
25627 end_lock:
25628   unixLeaveMutex();
25629   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
25630       rc==SQLITE_OK ? "ok" : "failed"));
25631   return rc;
25632 }
25633
25634 /*
25635 ** Add the file descriptor used by file handle pFile to the corresponding
25636 ** pUnused list.
25637 */
25638 static void setPendingFd(unixFile *pFile){
25639   unixInodeInfo *pInode = pFile->pInode;
25640   UnixUnusedFd *p = pFile->pUnused;
25641   p->pNext = pInode->pUnused;
25642   pInode->pUnused = p;
25643   pFile->h = -1;
25644   pFile->pUnused = 0;
25645 }
25646
25647 /*
25648 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25649 ** must be either NO_LOCK or SHARED_LOCK.
25650 **
25651 ** If the locking level of the file descriptor is already at or below
25652 ** the requested locking level, this routine is a no-op.
25653 ** 
25654 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25655 ** the byte range is divided into 2 parts and the first part is unlocked then
25656 ** set to a read lock, then the other part is simply unlocked.  This works 
25657 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
25658 ** remove the write lock on a region when a read lock is set.
25659 */
25660 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25661   unixFile *pFile = (unixFile*)id;
25662   unixInodeInfo *pInode;
25663   struct flock lock;
25664   int rc = SQLITE_OK;
25665   int h;
25666
25667   assert( pFile );
25668   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25669       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25670       getpid()));
25671
25672   assert( eFileLock<=SHARED_LOCK );
25673   if( pFile->eFileLock<=eFileLock ){
25674     return SQLITE_OK;
25675   }
25676   unixEnterMutex();
25677   h = pFile->h;
25678   pInode = pFile->pInode;
25679   assert( pInode->nShared!=0 );
25680   if( pFile->eFileLock>SHARED_LOCK ){
25681     assert( pInode->eFileLock==pFile->eFileLock );
25682     SimulateIOErrorBenign(1);
25683     SimulateIOError( h=(-1) )
25684     SimulateIOErrorBenign(0);
25685
25686 #ifndef NDEBUG
25687     /* When reducing a lock such that other processes can start
25688     ** reading the database file again, make sure that the
25689     ** transaction counter was updated if any part of the database
25690     ** file changed.  If the transaction counter is not updated,
25691     ** other connections to the same file might not realize that
25692     ** the file has changed and hence might not know to flush their
25693     ** cache.  The use of a stale cache can lead to database corruption.
25694     */
25695 #if 0
25696     assert( pFile->inNormalWrite==0
25697          || pFile->dbUpdate==0
25698          || pFile->transCntrChng==1 );
25699 #endif
25700     pFile->inNormalWrite = 0;
25701 #endif
25702
25703     /* downgrading to a shared lock on NFS involves clearing the write lock
25704     ** before establishing the readlock - to avoid a race condition we downgrade
25705     ** the lock in 2 blocks, so that part of the range will be covered by a 
25706     ** write lock until the rest is covered by a read lock:
25707     **  1:   [WWWWW]
25708     **  2:   [....W]
25709     **  3:   [RRRRW]
25710     **  4:   [RRRR.]
25711     */
25712     if( eFileLock==SHARED_LOCK ){
25713
25714 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25715       (void)handleNFSUnlock;
25716       assert( handleNFSUnlock==0 );
25717 #endif
25718 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25719       if( handleNFSUnlock ){
25720         int tErrno;               /* Error code from system call errors */
25721         off_t divSize = SHARED_SIZE - 1;
25722         
25723         lock.l_type = F_UNLCK;
25724         lock.l_whence = SEEK_SET;
25725         lock.l_start = SHARED_FIRST;
25726         lock.l_len = divSize;
25727         if( unixFileLock(pFile, &lock)==(-1) ){
25728           tErrno = errno;
25729           rc = SQLITE_IOERR_UNLOCK;
25730           if( IS_LOCK_ERROR(rc) ){
25731             pFile->lastErrno = tErrno;
25732           }
25733           goto end_unlock;
25734         }
25735         lock.l_type = F_RDLCK;
25736         lock.l_whence = SEEK_SET;
25737         lock.l_start = SHARED_FIRST;
25738         lock.l_len = divSize;
25739         if( unixFileLock(pFile, &lock)==(-1) ){
25740           tErrno = errno;
25741           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25742           if( IS_LOCK_ERROR(rc) ){
25743             pFile->lastErrno = tErrno;
25744           }
25745           goto end_unlock;
25746         }
25747         lock.l_type = F_UNLCK;
25748         lock.l_whence = SEEK_SET;
25749         lock.l_start = SHARED_FIRST+divSize;
25750         lock.l_len = SHARED_SIZE-divSize;
25751         if( unixFileLock(pFile, &lock)==(-1) ){
25752           tErrno = errno;
25753           rc = SQLITE_IOERR_UNLOCK;
25754           if( IS_LOCK_ERROR(rc) ){
25755             pFile->lastErrno = tErrno;
25756           }
25757           goto end_unlock;
25758         }
25759       }else
25760 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25761       {
25762         lock.l_type = F_RDLCK;
25763         lock.l_whence = SEEK_SET;
25764         lock.l_start = SHARED_FIRST;
25765         lock.l_len = SHARED_SIZE;
25766         if( unixFileLock(pFile, &lock) ){
25767           /* In theory, the call to unixFileLock() cannot fail because another
25768           ** process is holding an incompatible lock. If it does, this 
25769           ** indicates that the other process is not following the locking
25770           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25771           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
25772           ** an assert to fail). */ 
25773           rc = SQLITE_IOERR_RDLOCK;
25774           pFile->lastErrno = errno;
25775           goto end_unlock;
25776         }
25777       }
25778     }
25779     lock.l_type = F_UNLCK;
25780     lock.l_whence = SEEK_SET;
25781     lock.l_start = PENDING_BYTE;
25782     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
25783     if( unixFileLock(pFile, &lock)==0 ){
25784       pInode->eFileLock = SHARED_LOCK;
25785     }else{
25786       rc = SQLITE_IOERR_UNLOCK;
25787       pFile->lastErrno = errno;
25788       goto end_unlock;
25789     }
25790   }
25791   if( eFileLock==NO_LOCK ){
25792     /* Decrement the shared lock counter.  Release the lock using an
25793     ** OS call only when all threads in this same process have released
25794     ** the lock.
25795     */
25796     pInode->nShared--;
25797     if( pInode->nShared==0 ){
25798       lock.l_type = F_UNLCK;
25799       lock.l_whence = SEEK_SET;
25800       lock.l_start = lock.l_len = 0L;
25801       SimulateIOErrorBenign(1);
25802       SimulateIOError( h=(-1) )
25803       SimulateIOErrorBenign(0);
25804       if( unixFileLock(pFile, &lock)==0 ){
25805         pInode->eFileLock = NO_LOCK;
25806       }else{
25807         rc = SQLITE_IOERR_UNLOCK;
25808         pFile->lastErrno = errno;
25809         pInode->eFileLock = NO_LOCK;
25810         pFile->eFileLock = NO_LOCK;
25811       }
25812     }
25813
25814     /* Decrement the count of locks against this same file.  When the
25815     ** count reaches zero, close any other file descriptors whose close
25816     ** was deferred because of outstanding locks.
25817     */
25818     pInode->nLock--;
25819     assert( pInode->nLock>=0 );
25820     if( pInode->nLock==0 ){
25821       closePendingFds(pFile);
25822     }
25823   }
25824         
25825 end_unlock:
25826   unixLeaveMutex();
25827   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25828   return rc;
25829 }
25830
25831 /*
25832 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25833 ** must be either NO_LOCK or SHARED_LOCK.
25834 **
25835 ** If the locking level of the file descriptor is already at or below
25836 ** the requested locking level, this routine is a no-op.
25837 */
25838 static int unixUnlock(sqlite3_file *id, int eFileLock){
25839   return posixUnlock(id, eFileLock, 0);
25840 }
25841
25842 /*
25843 ** This function performs the parts of the "close file" operation 
25844 ** common to all locking schemes. It closes the directory and file
25845 ** handles, if they are valid, and sets all fields of the unixFile
25846 ** structure to 0.
25847 **
25848 ** It is *not* necessary to hold the mutex when this routine is called,
25849 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
25850 ** vxworksReleaseFileId() routine.
25851 */
25852 static int closeUnixFile(sqlite3_file *id){
25853   unixFile *pFile = (unixFile*)id;
25854   if( pFile->dirfd>=0 ){
25855     robust_close(pFile, pFile->dirfd, __LINE__);
25856     pFile->dirfd=-1;
25857   }
25858   if( pFile->h>=0 ){
25859     robust_close(pFile, pFile->h, __LINE__);
25860     pFile->h = -1;
25861   }
25862 #if OS_VXWORKS
25863   if( pFile->pId ){
25864     if( pFile->isDelete ){
25865       unlink(pFile->pId->zCanonicalName);
25866     }
25867     vxworksReleaseFileId(pFile->pId);
25868     pFile->pId = 0;
25869   }
25870 #endif
25871   OSTRACE(("CLOSE   %-3d\n", pFile->h));
25872   OpenCounter(-1);
25873   sqlite3_free(pFile->pUnused);
25874   memset(pFile, 0, sizeof(unixFile));
25875   return SQLITE_OK;
25876 }
25877
25878 /*
25879 ** Close a file.
25880 */
25881 static int unixClose(sqlite3_file *id){
25882   int rc = SQLITE_OK;
25883   unixFile *pFile = (unixFile *)id;
25884   unixUnlock(id, NO_LOCK);
25885   unixEnterMutex();
25886
25887   /* unixFile.pInode is always valid here. Otherwise, a different close
25888   ** routine (e.g. nolockClose()) would be called instead.
25889   */
25890   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25891   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25892     /* If there are outstanding locks, do not actually close the file just
25893     ** yet because that would clear those locks.  Instead, add the file
25894     ** descriptor to pInode->pUnused list.  It will be automatically closed 
25895     ** when the last lock is cleared.
25896     */
25897     setPendingFd(pFile);
25898   }
25899   releaseInodeInfo(pFile);
25900   rc = closeUnixFile(id);
25901   unixLeaveMutex();
25902   return rc;
25903 }
25904
25905 /************** End of the posix advisory lock implementation *****************
25906 ******************************************************************************/
25907
25908 /******************************************************************************
25909 ****************************** No-op Locking **********************************
25910 **
25911 ** Of the various locking implementations available, this is by far the
25912 ** simplest:  locking is ignored.  No attempt is made to lock the database
25913 ** file for reading or writing.
25914 **
25915 ** This locking mode is appropriate for use on read-only databases
25916 ** (ex: databases that are burned into CD-ROM, for example.)  It can
25917 ** also be used if the application employs some external mechanism to
25918 ** prevent simultaneous access of the same database by two or more
25919 ** database connections.  But there is a serious risk of database
25920 ** corruption if this locking mode is used in situations where multiple
25921 ** database connections are accessing the same database file at the same
25922 ** time and one or more of those connections are writing.
25923 */
25924
25925 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25926   UNUSED_PARAMETER(NotUsed);
25927   *pResOut = 0;
25928   return SQLITE_OK;
25929 }
25930 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25931   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25932   return SQLITE_OK;
25933 }
25934 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25935   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25936   return SQLITE_OK;
25937 }
25938
25939 /*
25940 ** Close the file.
25941 */
25942 static int nolockClose(sqlite3_file *id) {
25943   return closeUnixFile(id);
25944 }
25945
25946 /******************* End of the no-op lock implementation *********************
25947 ******************************************************************************/
25948
25949 /******************************************************************************
25950 ************************* Begin dot-file Locking ******************************
25951 **
25952 ** The dotfile locking implementation uses the existance of separate lock
25953 ** files in order to control access to the database.  This works on just
25954 ** about every filesystem imaginable.  But there are serious downsides:
25955 **
25956 **    (1)  There is zero concurrency.  A single reader blocks all other
25957 **         connections from reading or writing the database.
25958 **
25959 **    (2)  An application crash or power loss can leave stale lock files
25960 **         sitting around that need to be cleared manually.
25961 **
25962 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25963 ** other locking strategy is available.
25964 **
25965 ** Dotfile locking works by creating a file in the same directory as the
25966 ** database and with the same name but with a ".lock" extension added.
25967 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
25968 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25969 */
25970
25971 /*
25972 ** The file suffix added to the data base filename in order to create the
25973 ** lock file.
25974 */
25975 #define DOTLOCK_SUFFIX ".lock"
25976
25977 /*
25978 ** This routine checks if there is a RESERVED lock held on the specified
25979 ** file by this or any other process. If such a lock is held, set *pResOut
25980 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25981 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25982 **
25983 ** In dotfile locking, either a lock exists or it does not.  So in this
25984 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25985 ** is held on the file and false if the file is unlocked.
25986 */
25987 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25988   int rc = SQLITE_OK;
25989   int reserved = 0;
25990   unixFile *pFile = (unixFile*)id;
25991
25992   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25993   
25994   assert( pFile );
25995
25996   /* Check if a thread in this process holds such a lock */
25997   if( pFile->eFileLock>SHARED_LOCK ){
25998     /* Either this connection or some other connection in the same process
25999     ** holds a lock on the file.  No need to check further. */
26000     reserved = 1;
26001   }else{
26002     /* The lock is held if and only if the lockfile exists */
26003     const char *zLockFile = (const char*)pFile->lockingContext;
26004     reserved = osAccess(zLockFile, 0)==0;
26005   }
26006   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26007   *pResOut = reserved;
26008   return rc;
26009 }
26010
26011 /*
26012 ** Lock the file with the lock specified by parameter eFileLock - one
26013 ** of the following:
26014 **
26015 **     (1) SHARED_LOCK
26016 **     (2) RESERVED_LOCK
26017 **     (3) PENDING_LOCK
26018 **     (4) EXCLUSIVE_LOCK
26019 **
26020 ** Sometimes when requesting one lock state, additional lock states
26021 ** are inserted in between.  The locking might fail on one of the later
26022 ** transitions leaving the lock state different from what it started but
26023 ** still short of its goal.  The following chart shows the allowed
26024 ** transitions and the inserted intermediate states:
26025 **
26026 **    UNLOCKED -> SHARED
26027 **    SHARED -> RESERVED
26028 **    SHARED -> (PENDING) -> EXCLUSIVE
26029 **    RESERVED -> (PENDING) -> EXCLUSIVE
26030 **    PENDING -> EXCLUSIVE
26031 **
26032 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26033 ** routine to lower a locking level.
26034 **
26035 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26036 ** But we track the other locking levels internally.
26037 */
26038 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26039   unixFile *pFile = (unixFile*)id;
26040   int fd;
26041   char *zLockFile = (char *)pFile->lockingContext;
26042   int rc = SQLITE_OK;
26043
26044
26045   /* If we have any lock, then the lock file already exists.  All we have
26046   ** to do is adjust our internal record of the lock level.
26047   */
26048   if( pFile->eFileLock > NO_LOCK ){
26049     pFile->eFileLock = eFileLock;
26050 #if !OS_VXWORKS
26051     /* Always update the timestamp on the old file */
26052     utimes(zLockFile, NULL);
26053 #endif
26054     return SQLITE_OK;
26055   }
26056   
26057   /* grab an exclusive lock */
26058   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26059   if( fd<0 ){
26060     /* failed to open/create the file, someone else may have stolen the lock */
26061     int tErrno = errno;
26062     if( EEXIST == tErrno ){
26063       rc = SQLITE_BUSY;
26064     } else {
26065       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26066       if( IS_LOCK_ERROR(rc) ){
26067         pFile->lastErrno = tErrno;
26068       }
26069     }
26070     return rc;
26071   } 
26072   robust_close(pFile, fd, __LINE__);
26073   
26074   /* got it, set the type and return ok */
26075   pFile->eFileLock = eFileLock;
26076   return rc;
26077 }
26078
26079 /*
26080 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26081 ** must be either NO_LOCK or SHARED_LOCK.
26082 **
26083 ** If the locking level of the file descriptor is already at or below
26084 ** the requested locking level, this routine is a no-op.
26085 **
26086 ** When the locking level reaches NO_LOCK, delete the lock file.
26087 */
26088 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26089   unixFile *pFile = (unixFile*)id;
26090   char *zLockFile = (char *)pFile->lockingContext;
26091
26092   assert( pFile );
26093   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26094            pFile->eFileLock, getpid()));
26095   assert( eFileLock<=SHARED_LOCK );
26096   
26097   /* no-op if possible */
26098   if( pFile->eFileLock==eFileLock ){
26099     return SQLITE_OK;
26100   }
26101
26102   /* To downgrade to shared, simply update our internal notion of the
26103   ** lock state.  No need to mess with the file on disk.
26104   */
26105   if( eFileLock==SHARED_LOCK ){
26106     pFile->eFileLock = SHARED_LOCK;
26107     return SQLITE_OK;
26108   }
26109   
26110   /* To fully unlock the database, delete the lock file */
26111   assert( eFileLock==NO_LOCK );
26112   if( unlink(zLockFile) ){
26113     int rc = 0;
26114     int tErrno = errno;
26115     if( ENOENT != tErrno ){
26116       rc = SQLITE_IOERR_UNLOCK;
26117     }
26118     if( IS_LOCK_ERROR(rc) ){
26119       pFile->lastErrno = tErrno;
26120     }
26121     return rc; 
26122   }
26123   pFile->eFileLock = NO_LOCK;
26124   return SQLITE_OK;
26125 }
26126
26127 /*
26128 ** Close a file.  Make sure the lock has been released before closing.
26129 */
26130 static int dotlockClose(sqlite3_file *id) {
26131   int rc;
26132   if( id ){
26133     unixFile *pFile = (unixFile*)id;
26134     dotlockUnlock(id, NO_LOCK);
26135     sqlite3_free(pFile->lockingContext);
26136   }
26137   rc = closeUnixFile(id);
26138   return rc;
26139 }
26140 /****************** End of the dot-file lock implementation *******************
26141 ******************************************************************************/
26142
26143 /******************************************************************************
26144 ************************** Begin flock Locking ********************************
26145 **
26146 ** Use the flock() system call to do file locking.
26147 **
26148 ** flock() locking is like dot-file locking in that the various
26149 ** fine-grain locking levels supported by SQLite are collapsed into
26150 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
26151 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26152 ** still works when you do this, but concurrency is reduced since
26153 ** only a single process can be reading the database at a time.
26154 **
26155 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26156 ** compiling for VXWORKS.
26157 */
26158 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26159
26160 /*
26161 ** Retry flock() calls that fail with EINTR
26162 */
26163 #ifdef EINTR
26164 static int robust_flock(int fd, int op){
26165   int rc;
26166   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26167   return rc;
26168 }
26169 #else
26170 # define robust_flock(a,b) flock(a,b)
26171 #endif
26172      
26173
26174 /*
26175 ** This routine checks if there is a RESERVED lock held on the specified
26176 ** file by this or any other process. If such a lock is held, set *pResOut
26177 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26178 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26179 */
26180 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26181   int rc = SQLITE_OK;
26182   int reserved = 0;
26183   unixFile *pFile = (unixFile*)id;
26184   
26185   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26186   
26187   assert( pFile );
26188   
26189   /* Check if a thread in this process holds such a lock */
26190   if( pFile->eFileLock>SHARED_LOCK ){
26191     reserved = 1;
26192   }
26193   
26194   /* Otherwise see if some other process holds it. */
26195   if( !reserved ){
26196     /* attempt to get the lock */
26197     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26198     if( !lrc ){
26199       /* got the lock, unlock it */
26200       lrc = robust_flock(pFile->h, LOCK_UN);
26201       if ( lrc ) {
26202         int tErrno = errno;
26203         /* unlock failed with an error */
26204         lrc = SQLITE_IOERR_UNLOCK; 
26205         if( IS_LOCK_ERROR(lrc) ){
26206           pFile->lastErrno = tErrno;
26207           rc = lrc;
26208         }
26209       }
26210     } else {
26211       int tErrno = errno;
26212       reserved = 1;
26213       /* someone else might have it reserved */
26214       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
26215       if( IS_LOCK_ERROR(lrc) ){
26216         pFile->lastErrno = tErrno;
26217         rc = lrc;
26218       }
26219     }
26220   }
26221   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26222
26223 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26224   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26225     rc = SQLITE_OK;
26226     reserved=1;
26227   }
26228 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26229   *pResOut = reserved;
26230   return rc;
26231 }
26232
26233 /*
26234 ** Lock the file with the lock specified by parameter eFileLock - one
26235 ** of the following:
26236 **
26237 **     (1) SHARED_LOCK
26238 **     (2) RESERVED_LOCK
26239 **     (3) PENDING_LOCK
26240 **     (4) EXCLUSIVE_LOCK
26241 **
26242 ** Sometimes when requesting one lock state, additional lock states
26243 ** are inserted in between.  The locking might fail on one of the later
26244 ** transitions leaving the lock state different from what it started but
26245 ** still short of its goal.  The following chart shows the allowed
26246 ** transitions and the inserted intermediate states:
26247 **
26248 **    UNLOCKED -> SHARED
26249 **    SHARED -> RESERVED
26250 **    SHARED -> (PENDING) -> EXCLUSIVE
26251 **    RESERVED -> (PENDING) -> EXCLUSIVE
26252 **    PENDING -> EXCLUSIVE
26253 **
26254 ** flock() only really support EXCLUSIVE locks.  We track intermediate
26255 ** lock states in the sqlite3_file structure, but all locks SHARED or
26256 ** above are really EXCLUSIVE locks and exclude all other processes from
26257 ** access the file.
26258 **
26259 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26260 ** routine to lower a locking level.
26261 */
26262 static int flockLock(sqlite3_file *id, int eFileLock) {
26263   int rc = SQLITE_OK;
26264   unixFile *pFile = (unixFile*)id;
26265
26266   assert( pFile );
26267
26268   /* if we already have a lock, it is exclusive.  
26269   ** Just adjust level and punt on outta here. */
26270   if (pFile->eFileLock > NO_LOCK) {
26271     pFile->eFileLock = eFileLock;
26272     return SQLITE_OK;
26273   }
26274   
26275   /* grab an exclusive lock */
26276   
26277   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26278     int tErrno = errno;
26279     /* didn't get, must be busy */
26280     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26281     if( IS_LOCK_ERROR(rc) ){
26282       pFile->lastErrno = tErrno;
26283     }
26284   } else {
26285     /* got it, set the type and return ok */
26286     pFile->eFileLock = eFileLock;
26287   }
26288   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
26289            rc==SQLITE_OK ? "ok" : "failed"));
26290 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26291   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26292     rc = SQLITE_BUSY;
26293   }
26294 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26295   return rc;
26296 }
26297
26298
26299 /*
26300 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26301 ** must be either NO_LOCK or SHARED_LOCK.
26302 **
26303 ** If the locking level of the file descriptor is already at or below
26304 ** the requested locking level, this routine is a no-op.
26305 */
26306 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26307   unixFile *pFile = (unixFile*)id;
26308   
26309   assert( pFile );
26310   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26311            pFile->eFileLock, getpid()));
26312   assert( eFileLock<=SHARED_LOCK );
26313   
26314   /* no-op if possible */
26315   if( pFile->eFileLock==eFileLock ){
26316     return SQLITE_OK;
26317   }
26318   
26319   /* shared can just be set because we always have an exclusive */
26320   if (eFileLock==SHARED_LOCK) {
26321     pFile->eFileLock = eFileLock;
26322     return SQLITE_OK;
26323   }
26324   
26325   /* no, really, unlock. */
26326   if( robust_flock(pFile->h, LOCK_UN) ){
26327 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26328     return SQLITE_OK;
26329 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26330     return SQLITE_IOERR_UNLOCK;
26331   }else{
26332     pFile->eFileLock = NO_LOCK;
26333     return SQLITE_OK;
26334   }
26335 }
26336
26337 /*
26338 ** Close a file.
26339 */
26340 static int flockClose(sqlite3_file *id) {
26341   if( id ){
26342     flockUnlock(id, NO_LOCK);
26343   }
26344   return closeUnixFile(id);
26345 }
26346
26347 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26348
26349 /******************* End of the flock lock implementation *********************
26350 ******************************************************************************/
26351
26352 /******************************************************************************
26353 ************************ Begin Named Semaphore Locking ************************
26354 **
26355 ** Named semaphore locking is only supported on VxWorks.
26356 **
26357 ** Semaphore locking is like dot-lock and flock in that it really only
26358 ** supports EXCLUSIVE locking.  Only a single process can read or write
26359 ** the database file at a time.  This reduces potential concurrency, but
26360 ** makes the lock implementation much easier.
26361 */
26362 #if OS_VXWORKS
26363
26364 /*
26365 ** This routine checks if there is a RESERVED lock held on the specified
26366 ** file by this or any other process. If such a lock is held, set *pResOut
26367 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26368 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26369 */
26370 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26371   int rc = SQLITE_OK;
26372   int reserved = 0;
26373   unixFile *pFile = (unixFile*)id;
26374
26375   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26376   
26377   assert( pFile );
26378
26379   /* Check if a thread in this process holds such a lock */
26380   if( pFile->eFileLock>SHARED_LOCK ){
26381     reserved = 1;
26382   }
26383   
26384   /* Otherwise see if some other process holds it. */
26385   if( !reserved ){
26386     sem_t *pSem = pFile->pInode->pSem;
26387     struct stat statBuf;
26388
26389     if( sem_trywait(pSem)==-1 ){
26390       int tErrno = errno;
26391       if( EAGAIN != tErrno ){
26392         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26393         pFile->lastErrno = tErrno;
26394       } else {
26395         /* someone else has the lock when we are in NO_LOCK */
26396         reserved = (pFile->eFileLock < SHARED_LOCK);
26397       }
26398     }else{
26399       /* we could have it if we want it */
26400       sem_post(pSem);
26401     }
26402   }
26403   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26404
26405   *pResOut = reserved;
26406   return rc;
26407 }
26408
26409 /*
26410 ** Lock the file with the lock specified by parameter eFileLock - one
26411 ** of the following:
26412 **
26413 **     (1) SHARED_LOCK
26414 **     (2) RESERVED_LOCK
26415 **     (3) PENDING_LOCK
26416 **     (4) EXCLUSIVE_LOCK
26417 **
26418 ** Sometimes when requesting one lock state, additional lock states
26419 ** are inserted in between.  The locking might fail on one of the later
26420 ** transitions leaving the lock state different from what it started but
26421 ** still short of its goal.  The following chart shows the allowed
26422 ** transitions and the inserted intermediate states:
26423 **
26424 **    UNLOCKED -> SHARED
26425 **    SHARED -> RESERVED
26426 **    SHARED -> (PENDING) -> EXCLUSIVE
26427 **    RESERVED -> (PENDING) -> EXCLUSIVE
26428 **    PENDING -> EXCLUSIVE
26429 **
26430 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26431 ** lock states in the sqlite3_file structure, but all locks SHARED or
26432 ** above are really EXCLUSIVE locks and exclude all other processes from
26433 ** access the file.
26434 **
26435 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26436 ** routine to lower a locking level.
26437 */
26438 static int semLock(sqlite3_file *id, int eFileLock) {
26439   unixFile *pFile = (unixFile*)id;
26440   int fd;
26441   sem_t *pSem = pFile->pInode->pSem;
26442   int rc = SQLITE_OK;
26443
26444   /* if we already have a lock, it is exclusive.  
26445   ** Just adjust level and punt on outta here. */
26446   if (pFile->eFileLock > NO_LOCK) {
26447     pFile->eFileLock = eFileLock;
26448     rc = SQLITE_OK;
26449     goto sem_end_lock;
26450   }
26451   
26452   /* lock semaphore now but bail out when already locked. */
26453   if( sem_trywait(pSem)==-1 ){
26454     rc = SQLITE_BUSY;
26455     goto sem_end_lock;
26456   }
26457
26458   /* got it, set the type and return ok */
26459   pFile->eFileLock = eFileLock;
26460
26461  sem_end_lock:
26462   return rc;
26463 }
26464
26465 /*
26466 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26467 ** must be either NO_LOCK or SHARED_LOCK.
26468 **
26469 ** If the locking level of the file descriptor is already at or below
26470 ** the requested locking level, this routine is a no-op.
26471 */
26472 static int semUnlock(sqlite3_file *id, int eFileLock) {
26473   unixFile *pFile = (unixFile*)id;
26474   sem_t *pSem = pFile->pInode->pSem;
26475
26476   assert( pFile );
26477   assert( pSem );
26478   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26479            pFile->eFileLock, getpid()));
26480   assert( eFileLock<=SHARED_LOCK );
26481   
26482   /* no-op if possible */
26483   if( pFile->eFileLock==eFileLock ){
26484     return SQLITE_OK;
26485   }
26486   
26487   /* shared can just be set because we always have an exclusive */
26488   if (eFileLock==SHARED_LOCK) {
26489     pFile->eFileLock = eFileLock;
26490     return SQLITE_OK;
26491   }
26492   
26493   /* no, really unlock. */
26494   if ( sem_post(pSem)==-1 ) {
26495     int rc, tErrno = errno;
26496     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26497     if( IS_LOCK_ERROR(rc) ){
26498       pFile->lastErrno = tErrno;
26499     }
26500     return rc; 
26501   }
26502   pFile->eFileLock = NO_LOCK;
26503   return SQLITE_OK;
26504 }
26505
26506 /*
26507  ** Close a file.
26508  */
26509 static int semClose(sqlite3_file *id) {
26510   if( id ){
26511     unixFile *pFile = (unixFile*)id;
26512     semUnlock(id, NO_LOCK);
26513     assert( pFile );
26514     unixEnterMutex();
26515     releaseInodeInfo(pFile);
26516     unixLeaveMutex();
26517     closeUnixFile(id);
26518   }
26519   return SQLITE_OK;
26520 }
26521
26522 #endif /* OS_VXWORKS */
26523 /*
26524 ** Named semaphore locking is only available on VxWorks.
26525 **
26526 *************** End of the named semaphore lock implementation ****************
26527 ******************************************************************************/
26528
26529
26530 /******************************************************************************
26531 *************************** Begin AFP Locking *********************************
26532 **
26533 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
26534 ** on Apple Macintosh computers - both OS9 and OSX.
26535 **
26536 ** Third-party implementations of AFP are available.  But this code here
26537 ** only works on OSX.
26538 */
26539
26540 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26541 /*
26542 ** The afpLockingContext structure contains all afp lock specific state
26543 */
26544 typedef struct afpLockingContext afpLockingContext;
26545 struct afpLockingContext {
26546   int reserved;
26547   const char *dbPath;             /* Name of the open file */
26548 };
26549
26550 struct ByteRangeLockPB2
26551 {
26552   unsigned long long offset;        /* offset to first byte to lock */
26553   unsigned long long length;        /* nbr of bytes to lock */
26554   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26555   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
26556   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
26557   int fd;                           /* file desc to assoc this lock with */
26558 };
26559
26560 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
26561
26562 /*
26563 ** This is a utility for setting or clearing a bit-range lock on an
26564 ** AFP filesystem.
26565 ** 
26566 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26567 */
26568 static int afpSetLock(
26569   const char *path,              /* Name of the file to be locked or unlocked */
26570   unixFile *pFile,               /* Open file descriptor on path */
26571   unsigned long long offset,     /* First byte to be locked */
26572   unsigned long long length,     /* Number of bytes to lock */
26573   int setLockFlag                /* True to set lock.  False to clear lock */
26574 ){
26575   struct ByteRangeLockPB2 pb;
26576   int err;
26577   
26578   pb.unLockFlag = setLockFlag ? 0 : 1;
26579   pb.startEndFlag = 0;
26580   pb.offset = offset;
26581   pb.length = length; 
26582   pb.fd = pFile->h;
26583   
26584   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
26585     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26586     offset, length));
26587   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26588   if ( err==-1 ) {
26589     int rc;
26590     int tErrno = errno;
26591     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26592              path, tErrno, strerror(tErrno)));
26593 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26594     rc = SQLITE_BUSY;
26595 #else
26596     rc = sqliteErrorFromPosixError(tErrno,
26597                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26598 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26599     if( IS_LOCK_ERROR(rc) ){
26600       pFile->lastErrno = tErrno;
26601     }
26602     return rc;
26603   } else {
26604     return SQLITE_OK;
26605   }
26606 }
26607
26608 /*
26609 ** This routine checks if there is a RESERVED lock held on the specified
26610 ** file by this or any other process. If such a lock is held, set *pResOut
26611 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26612 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26613 */
26614 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26615   int rc = SQLITE_OK;
26616   int reserved = 0;
26617   unixFile *pFile = (unixFile*)id;
26618   
26619   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26620   
26621   assert( pFile );
26622   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26623   if( context->reserved ){
26624     *pResOut = 1;
26625     return SQLITE_OK;
26626   }
26627   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26628   
26629   /* Check if a thread in this process holds such a lock */
26630   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26631     reserved = 1;
26632   }
26633   
26634   /* Otherwise see if some other process holds it.
26635    */
26636   if( !reserved ){
26637     /* lock the RESERVED byte */
26638     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
26639     if( SQLITE_OK==lrc ){
26640       /* if we succeeded in taking the reserved lock, unlock it to restore
26641       ** the original state */
26642       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26643     } else {
26644       /* if we failed to get the lock then someone else must have it */
26645       reserved = 1;
26646     }
26647     if( IS_LOCK_ERROR(lrc) ){
26648       rc=lrc;
26649     }
26650   }
26651   
26652   unixLeaveMutex();
26653   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26654   
26655   *pResOut = reserved;
26656   return rc;
26657 }
26658
26659 /*
26660 ** Lock the file with the lock specified by parameter eFileLock - one
26661 ** of the following:
26662 **
26663 **     (1) SHARED_LOCK
26664 **     (2) RESERVED_LOCK
26665 **     (3) PENDING_LOCK
26666 **     (4) EXCLUSIVE_LOCK
26667 **
26668 ** Sometimes when requesting one lock state, additional lock states
26669 ** are inserted in between.  The locking might fail on one of the later
26670 ** transitions leaving the lock state different from what it started but
26671 ** still short of its goal.  The following chart shows the allowed
26672 ** transitions and the inserted intermediate states:
26673 **
26674 **    UNLOCKED -> SHARED
26675 **    SHARED -> RESERVED
26676 **    SHARED -> (PENDING) -> EXCLUSIVE
26677 **    RESERVED -> (PENDING) -> EXCLUSIVE
26678 **    PENDING -> EXCLUSIVE
26679 **
26680 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26681 ** routine to lower a locking level.
26682 */
26683 static int afpLock(sqlite3_file *id, int eFileLock){
26684   int rc = SQLITE_OK;
26685   unixFile *pFile = (unixFile*)id;
26686   unixInodeInfo *pInode = pFile->pInode;
26687   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26688   
26689   assert( pFile );
26690   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26691            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26692            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26693
26694   /* If there is already a lock of this type or more restrictive on the
26695   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26696   ** unixEnterMutex() hasn't been called yet.
26697   */
26698   if( pFile->eFileLock>=eFileLock ){
26699     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
26700            azFileLock(eFileLock)));
26701     return SQLITE_OK;
26702   }
26703
26704   /* Make sure the locking sequence is correct
26705   **  (1) We never move from unlocked to anything higher than shared lock.
26706   **  (2) SQLite never explicitly requests a pendig lock.
26707   **  (3) A shared lock is always held when a reserve lock is requested.
26708   */
26709   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26710   assert( eFileLock!=PENDING_LOCK );
26711   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26712   
26713   /* This mutex is needed because pFile->pInode is shared across threads
26714   */
26715   unixEnterMutex();
26716   pInode = pFile->pInode;
26717
26718   /* If some thread using this PID has a lock via a different unixFile*
26719   ** handle that precludes the requested lock, return BUSY.
26720   */
26721   if( (pFile->eFileLock!=pInode->eFileLock && 
26722        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26723      ){
26724     rc = SQLITE_BUSY;
26725     goto afp_end_lock;
26726   }
26727   
26728   /* If a SHARED lock is requested, and some thread using this PID already
26729   ** has a SHARED or RESERVED lock, then increment reference counts and
26730   ** return SQLITE_OK.
26731   */
26732   if( eFileLock==SHARED_LOCK && 
26733      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26734     assert( eFileLock==SHARED_LOCK );
26735     assert( pFile->eFileLock==0 );
26736     assert( pInode->nShared>0 );
26737     pFile->eFileLock = SHARED_LOCK;
26738     pInode->nShared++;
26739     pInode->nLock++;
26740     goto afp_end_lock;
26741   }
26742     
26743   /* A PENDING lock is needed before acquiring a SHARED lock and before
26744   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26745   ** be released.
26746   */
26747   if( eFileLock==SHARED_LOCK 
26748       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26749   ){
26750     int failed;
26751     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26752     if (failed) {
26753       rc = failed;
26754       goto afp_end_lock;
26755     }
26756   }
26757   
26758   /* If control gets to this point, then actually go ahead and make
26759   ** operating system calls for the specified lock.
26760   */
26761   if( eFileLock==SHARED_LOCK ){
26762     int lrc1, lrc2, lrc1Errno;
26763     long lk, mask;
26764     
26765     assert( pInode->nShared==0 );
26766     assert( pInode->eFileLock==0 );
26767         
26768     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26769     /* Now get the read-lock SHARED_LOCK */
26770     /* note that the quality of the randomness doesn't matter that much */
26771     lk = random(); 
26772     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26773     lrc1 = afpSetLock(context->dbPath, pFile, 
26774           SHARED_FIRST+pInode->sharedByte, 1, 1);
26775     if( IS_LOCK_ERROR(lrc1) ){
26776       lrc1Errno = pFile->lastErrno;
26777     }
26778     /* Drop the temporary PENDING lock */
26779     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26780     
26781     if( IS_LOCK_ERROR(lrc1) ) {
26782       pFile->lastErrno = lrc1Errno;
26783       rc = lrc1;
26784       goto afp_end_lock;
26785     } else if( IS_LOCK_ERROR(lrc2) ){
26786       rc = lrc2;
26787       goto afp_end_lock;
26788     } else if( lrc1 != SQLITE_OK ) {
26789       rc = lrc1;
26790     } else {
26791       pFile->eFileLock = SHARED_LOCK;
26792       pInode->nLock++;
26793       pInode->nShared = 1;
26794     }
26795   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26796     /* We are trying for an exclusive lock but another thread in this
26797      ** same process is still holding a shared lock. */
26798     rc = SQLITE_BUSY;
26799   }else{
26800     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26801     ** assumed that there is a SHARED or greater lock on the file
26802     ** already.
26803     */
26804     int failed = 0;
26805     assert( 0!=pFile->eFileLock );
26806     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26807         /* Acquire a RESERVED lock */
26808         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26809       if( !failed ){
26810         context->reserved = 1;
26811       }
26812     }
26813     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26814       /* Acquire an EXCLUSIVE lock */
26815         
26816       /* Remove the shared lock before trying the range.  we'll need to 
26817       ** reestablish the shared lock if we can't get the  afpUnlock
26818       */
26819       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26820                          pInode->sharedByte, 1, 0)) ){
26821         int failed2 = SQLITE_OK;
26822         /* now attemmpt to get the exclusive lock range */
26823         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
26824                                SHARED_SIZE, 1);
26825         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
26826                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26827           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
26828           ** a critical I/O error
26829           */
26830           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
26831                SQLITE_IOERR_LOCK;
26832           goto afp_end_lock;
26833         } 
26834       }else{
26835         rc = failed; 
26836       }
26837     }
26838     if( failed ){
26839       rc = failed;
26840     }
26841   }
26842   
26843   if( rc==SQLITE_OK ){
26844     pFile->eFileLock = eFileLock;
26845     pInode->eFileLock = eFileLock;
26846   }else if( eFileLock==EXCLUSIVE_LOCK ){
26847     pFile->eFileLock = PENDING_LOCK;
26848     pInode->eFileLock = PENDING_LOCK;
26849   }
26850   
26851 afp_end_lock:
26852   unixLeaveMutex();
26853   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
26854          rc==SQLITE_OK ? "ok" : "failed"));
26855   return rc;
26856 }
26857
26858 /*
26859 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26860 ** must be either NO_LOCK or SHARED_LOCK.
26861 **
26862 ** If the locking level of the file descriptor is already at or below
26863 ** the requested locking level, this routine is a no-op.
26864 */
26865 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26866   int rc = SQLITE_OK;
26867   unixFile *pFile = (unixFile*)id;
26868   unixInodeInfo *pInode;
26869   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26870   int skipShared = 0;
26871 #ifdef SQLITE_TEST
26872   int h = pFile->h;
26873 #endif
26874
26875   assert( pFile );
26876   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26877            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26878            getpid()));
26879
26880   assert( eFileLock<=SHARED_LOCK );
26881   if( pFile->eFileLock<=eFileLock ){
26882     return SQLITE_OK;
26883   }
26884   unixEnterMutex();
26885   pInode = pFile->pInode;
26886   assert( pInode->nShared!=0 );
26887   if( pFile->eFileLock>SHARED_LOCK ){
26888     assert( pInode->eFileLock==pFile->eFileLock );
26889     SimulateIOErrorBenign(1);
26890     SimulateIOError( h=(-1) )
26891     SimulateIOErrorBenign(0);
26892     
26893 #ifndef NDEBUG
26894     /* When reducing a lock such that other processes can start
26895     ** reading the database file again, make sure that the
26896     ** transaction counter was updated if any part of the database
26897     ** file changed.  If the transaction counter is not updated,
26898     ** other connections to the same file might not realize that
26899     ** the file has changed and hence might not know to flush their
26900     ** cache.  The use of a stale cache can lead to database corruption.
26901     */
26902     assert( pFile->inNormalWrite==0
26903            || pFile->dbUpdate==0
26904            || pFile->transCntrChng==1 );
26905     pFile->inNormalWrite = 0;
26906 #endif
26907     
26908     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26909       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26910       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26911         /* only re-establish the shared lock if necessary */
26912         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26913         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26914       } else {
26915         skipShared = 1;
26916       }
26917     }
26918     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26919       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26920     } 
26921     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26922       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26923       if( !rc ){ 
26924         context->reserved = 0; 
26925       }
26926     }
26927     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26928       pInode->eFileLock = SHARED_LOCK;
26929     }
26930   }
26931   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26932
26933     /* Decrement the shared lock counter.  Release the lock using an
26934     ** OS call only when all threads in this same process have released
26935     ** the lock.
26936     */
26937     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26938     pInode->nShared--;
26939     if( pInode->nShared==0 ){
26940       SimulateIOErrorBenign(1);
26941       SimulateIOError( h=(-1) )
26942       SimulateIOErrorBenign(0);
26943       if( !skipShared ){
26944         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26945       }
26946       if( !rc ){
26947         pInode->eFileLock = NO_LOCK;
26948         pFile->eFileLock = NO_LOCK;
26949       }
26950     }
26951     if( rc==SQLITE_OK ){
26952       pInode->nLock--;
26953       assert( pInode->nLock>=0 );
26954       if( pInode->nLock==0 ){
26955         closePendingFds(pFile);
26956       }
26957     }
26958   }
26959   
26960   unixLeaveMutex();
26961   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26962   return rc;
26963 }
26964
26965 /*
26966 ** Close a file & cleanup AFP specific locking context 
26967 */
26968 static int afpClose(sqlite3_file *id) {
26969   int rc = SQLITE_OK;
26970   if( id ){
26971     unixFile *pFile = (unixFile*)id;
26972     afpUnlock(id, NO_LOCK);
26973     unixEnterMutex();
26974     if( pFile->pInode && pFile->pInode->nLock ){
26975       /* If there are outstanding locks, do not actually close the file just
26976       ** yet because that would clear those locks.  Instead, add the file
26977       ** descriptor to pInode->aPending.  It will be automatically closed when
26978       ** the last lock is cleared.
26979       */
26980       setPendingFd(pFile);
26981     }
26982     releaseInodeInfo(pFile);
26983     sqlite3_free(pFile->lockingContext);
26984     rc = closeUnixFile(id);
26985     unixLeaveMutex();
26986   }
26987   return rc;
26988 }
26989
26990 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26991 /*
26992 ** The code above is the AFP lock implementation.  The code is specific
26993 ** to MacOSX and does not work on other unix platforms.  No alternative
26994 ** is available.  If you don't compile for a mac, then the "unix-afp"
26995 ** VFS is not available.
26996 **
26997 ********************* End of the AFP lock implementation **********************
26998 ******************************************************************************/
26999
27000 /******************************************************************************
27001 *************************** Begin NFS Locking ********************************/
27002
27003 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27004 /*
27005  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27006  ** must be either NO_LOCK or SHARED_LOCK.
27007  **
27008  ** If the locking level of the file descriptor is already at or below
27009  ** the requested locking level, this routine is a no-op.
27010  */
27011 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27012   return posixUnlock(id, eFileLock, 1);
27013 }
27014
27015 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27016 /*
27017 ** The code above is the NFS lock implementation.  The code is specific
27018 ** to MacOSX and does not work on other unix platforms.  No alternative
27019 ** is available.  
27020 **
27021 ********************* End of the NFS lock implementation **********************
27022 ******************************************************************************/
27023
27024 /******************************************************************************
27025 **************** Non-locking sqlite3_file methods *****************************
27026 **
27027 ** The next division contains implementations for all methods of the 
27028 ** sqlite3_file object other than the locking methods.  The locking
27029 ** methods were defined in divisions above (one locking method per
27030 ** division).  Those methods that are common to all locking modes
27031 ** are gather together into this division.
27032 */
27033
27034 /*
27035 ** Seek to the offset passed as the second argument, then read cnt 
27036 ** bytes into pBuf. Return the number of bytes actually read.
27037 **
27038 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27039 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27040 ** one system to another.  Since SQLite does not define USE_PREAD
27041 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27042 ** See tickets #2741 and #2681.
27043 **
27044 ** To avoid stomping the errno value on a failed read the lastErrno value
27045 ** is set before returning.
27046 */
27047 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27048   int got;
27049 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27050   i64 newOffset;
27051 #endif
27052   TIMER_START;
27053 #if defined(USE_PREAD)
27054   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27055   SimulateIOError( got = -1 );
27056 #elif defined(USE_PREAD64)
27057   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27058   SimulateIOError( got = -1 );
27059 #else
27060   newOffset = lseek(id->h, offset, SEEK_SET);
27061   SimulateIOError( newOffset-- );
27062   if( newOffset!=offset ){
27063     if( newOffset == -1 ){
27064       ((unixFile*)id)->lastErrno = errno;
27065     }else{
27066       ((unixFile*)id)->lastErrno = 0;                   
27067     }
27068     return -1;
27069   }
27070   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27071 #endif
27072   TIMER_END;
27073   if( got<0 ){
27074     ((unixFile*)id)->lastErrno = errno;
27075   }
27076   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27077   return got;
27078 }
27079
27080 /*
27081 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27082 ** bytes were read successfully and SQLITE_IOERR if anything goes
27083 ** wrong.
27084 */
27085 static int unixRead(
27086   sqlite3_file *id, 
27087   void *pBuf, 
27088   int amt,
27089   sqlite3_int64 offset
27090 ){
27091   unixFile *pFile = (unixFile *)id;
27092   int got;
27093   assert( id );
27094
27095   /* If this is a database file (not a journal, master-journal or temp
27096   ** file), the bytes in the locking range should never be read or written. */
27097 #if 0
27098   assert( pFile->pUnused==0
27099        || offset>=PENDING_BYTE+512
27100        || offset+amt<=PENDING_BYTE 
27101   );
27102 #endif
27103
27104   got = seekAndRead(pFile, offset, pBuf, amt);
27105   if( got==amt ){
27106     return SQLITE_OK;
27107   }else if( got<0 ){
27108     /* lastErrno set by seekAndRead */
27109     return SQLITE_IOERR_READ;
27110   }else{
27111     pFile->lastErrno = 0; /* not a system error */
27112     /* Unread parts of the buffer must be zero-filled */
27113     memset(&((char*)pBuf)[got], 0, amt-got);
27114     return SQLITE_IOERR_SHORT_READ;
27115   }
27116 }
27117
27118 /*
27119 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27120 ** Return the number of bytes actually read.  Update the offset.
27121 **
27122 ** To avoid stomping the errno value on a failed write the lastErrno value
27123 ** is set before returning.
27124 */
27125 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27126   int got;
27127 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27128   i64 newOffset;
27129 #endif
27130   TIMER_START;
27131 #if defined(USE_PREAD)
27132   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27133 #elif defined(USE_PREAD64)
27134   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27135 #else
27136   newOffset = lseek(id->h, offset, SEEK_SET);
27137   SimulateIOError( newOffset-- );
27138   if( newOffset!=offset ){
27139     if( newOffset == -1 ){
27140       ((unixFile*)id)->lastErrno = errno;
27141     }else{
27142       ((unixFile*)id)->lastErrno = 0;                   
27143     }
27144     return -1;
27145   }
27146   do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27147 #endif
27148   TIMER_END;
27149   if( got<0 ){
27150     ((unixFile*)id)->lastErrno = errno;
27151   }
27152
27153   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27154   return got;
27155 }
27156
27157
27158 /*
27159 ** Write data from a buffer into a file.  Return SQLITE_OK on success
27160 ** or some other error code on failure.
27161 */
27162 static int unixWrite(
27163   sqlite3_file *id, 
27164   const void *pBuf, 
27165   int amt,
27166   sqlite3_int64 offset 
27167 ){
27168   unixFile *pFile = (unixFile*)id;
27169   int wrote = 0;
27170   assert( id );
27171   assert( amt>0 );
27172
27173   /* If this is a database file (not a journal, master-journal or temp
27174   ** file), the bytes in the locking range should never be read or written. */
27175 #if 0
27176   assert( pFile->pUnused==0
27177        || offset>=PENDING_BYTE+512
27178        || offset+amt<=PENDING_BYTE 
27179   );
27180 #endif
27181
27182 #ifndef NDEBUG
27183   /* If we are doing a normal write to a database file (as opposed to
27184   ** doing a hot-journal rollback or a write to some file other than a
27185   ** normal database file) then record the fact that the database
27186   ** has changed.  If the transaction counter is modified, record that
27187   ** fact too.
27188   */
27189   if( pFile->inNormalWrite ){
27190     pFile->dbUpdate = 1;  /* The database has been modified */
27191     if( offset<=24 && offset+amt>=27 ){
27192       int rc;
27193       char oldCntr[4];
27194       SimulateIOErrorBenign(1);
27195       rc = seekAndRead(pFile, 24, oldCntr, 4);
27196       SimulateIOErrorBenign(0);
27197       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27198         pFile->transCntrChng = 1;  /* The transaction counter has changed */
27199       }
27200     }
27201   }
27202 #endif
27203
27204   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27205     amt -= wrote;
27206     offset += wrote;
27207     pBuf = &((char*)pBuf)[wrote];
27208   }
27209   SimulateIOError(( wrote=(-1), amt=1 ));
27210   SimulateDiskfullError(( wrote=0, amt=1 ));
27211
27212   if( amt>0 ){
27213     if( wrote<0 ){
27214       /* lastErrno set by seekAndWrite */
27215       return SQLITE_IOERR_WRITE;
27216     }else{
27217       pFile->lastErrno = 0; /* not a system error */
27218       return SQLITE_FULL;
27219     }
27220   }
27221
27222   return SQLITE_OK;
27223 }
27224
27225 #ifdef SQLITE_TEST
27226 /*
27227 ** Count the number of fullsyncs and normal syncs.  This is used to test
27228 ** that syncs and fullsyncs are occurring at the right times.
27229 */
27230 SQLITE_API int sqlite3_sync_count = 0;
27231 SQLITE_API int sqlite3_fullsync_count = 0;
27232 #endif
27233
27234 /*
27235 ** We do not trust systems to provide a working fdatasync().  Some do.
27236 ** Others do no.  To be safe, we will stick with the (slower) fsync().
27237 ** If you know that your system does support fdatasync() correctly,
27238 ** then simply compile with -Dfdatasync=fdatasync
27239 */
27240 #if !defined(fdatasync) && !defined(__linux__)
27241 # define fdatasync fsync
27242 #endif
27243
27244 /*
27245 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27246 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27247 ** only available on Mac OS X.  But that could change.
27248 */
27249 #ifdef F_FULLFSYNC
27250 # define HAVE_FULLFSYNC 1
27251 #else
27252 # define HAVE_FULLFSYNC 0
27253 #endif
27254
27255
27256 /*
27257 ** The fsync() system call does not work as advertised on many
27258 ** unix systems.  The following procedure is an attempt to make
27259 ** it work better.
27260 **
27261 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27262 ** for testing when we want to run through the test suite quickly.
27263 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27264 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27265 ** or power failure will likely corrupt the database file.
27266 **
27267 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27268 ** The idea behind dataOnly is that it should only write the file content
27269 ** to disk, not the inode.  We only set dataOnly if the file size is 
27270 ** unchanged since the file size is part of the inode.  However, 
27271 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27272 ** file size has changed.  The only real difference between fdatasync()
27273 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27274 ** inode if the mtime or owner or other inode attributes have changed.
27275 ** We only care about the file size, not the other file attributes, so
27276 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27277 ** So, we always use fdatasync() if it is available, regardless of
27278 ** the value of the dataOnly flag.
27279 */
27280 static int full_fsync(int fd, int fullSync, int dataOnly){
27281   int rc;
27282
27283   /* The following "ifdef/elif/else/" block has the same structure as
27284   ** the one below. It is replicated here solely to avoid cluttering 
27285   ** up the real code with the UNUSED_PARAMETER() macros.
27286   */
27287 #ifdef SQLITE_NO_SYNC
27288   UNUSED_PARAMETER(fd);
27289   UNUSED_PARAMETER(fullSync);
27290   UNUSED_PARAMETER(dataOnly);
27291 #elif HAVE_FULLFSYNC
27292   UNUSED_PARAMETER(dataOnly);
27293 #else
27294   UNUSED_PARAMETER(fullSync);
27295   UNUSED_PARAMETER(dataOnly);
27296 #endif
27297
27298   /* Record the number of times that we do a normal fsync() and 
27299   ** FULLSYNC.  This is used during testing to verify that this procedure
27300   ** gets called with the correct arguments.
27301   */
27302 #ifdef SQLITE_TEST
27303   if( fullSync ) sqlite3_fullsync_count++;
27304   sqlite3_sync_count++;
27305 #endif
27306
27307   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27308   ** no-op
27309   */
27310 #ifdef SQLITE_NO_SYNC
27311   rc = SQLITE_OK;
27312 #elif HAVE_FULLFSYNC
27313   if( fullSync ){
27314     rc = osFcntl(fd, F_FULLFSYNC, 0);
27315   }else{
27316     rc = 1;
27317   }
27318   /* If the FULLFSYNC failed, fall back to attempting an fsync().
27319   ** It shouldn't be possible for fullfsync to fail on the local 
27320   ** file system (on OSX), so failure indicates that FULLFSYNC
27321   ** isn't supported for this file system. So, attempt an fsync 
27322   ** and (for now) ignore the overhead of a superfluous fcntl call.  
27323   ** It'd be better to detect fullfsync support once and avoid 
27324   ** the fcntl call every time sync is called.
27325   */
27326   if( rc ) rc = fsync(fd);
27327
27328 #elif defined(__APPLE__)
27329   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27330   ** so currently we default to the macro that redefines fdatasync to fsync
27331   */
27332   rc = fsync(fd);
27333 #else 
27334   rc = fdatasync(fd);
27335 #if OS_VXWORKS
27336   if( rc==-1 && errno==ENOTSUP ){
27337     rc = fsync(fd);
27338   }
27339 #endif /* OS_VXWORKS */
27340 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27341
27342   if( OS_VXWORKS && rc!= -1 ){
27343     rc = 0;
27344   }
27345   return rc;
27346 }
27347
27348 /*
27349 ** Make sure all writes to a particular file are committed to disk.
27350 **
27351 ** If dataOnly==0 then both the file itself and its metadata (file
27352 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
27353 ** file data is synced.
27354 **
27355 ** Under Unix, also make sure that the directory entry for the file
27356 ** has been created by fsync-ing the directory that contains the file.
27357 ** If we do not do this and we encounter a power failure, the directory
27358 ** entry for the journal might not exist after we reboot.  The next
27359 ** SQLite to access the file will not know that the journal exists (because
27360 ** the directory entry for the journal was never created) and the transaction
27361 ** will not roll back - possibly leading to database corruption.
27362 */
27363 static int unixSync(sqlite3_file *id, int flags){
27364   int rc;
27365   unixFile *pFile = (unixFile*)id;
27366
27367   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27368   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27369
27370   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27371   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27372       || (flags&0x0F)==SQLITE_SYNC_FULL
27373   );
27374
27375   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27376   ** line is to test that doing so does not cause any problems.
27377   */
27378   SimulateDiskfullError( return SQLITE_FULL );
27379
27380   assert( pFile );
27381   OSTRACE(("SYNC    %-3d\n", pFile->h));
27382   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27383   SimulateIOError( rc=1 );
27384   if( rc ){
27385     pFile->lastErrno = errno;
27386     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27387   }
27388   if( pFile->dirfd>=0 ){
27389     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
27390             HAVE_FULLFSYNC, isFullsync));
27391 #ifndef SQLITE_DISABLE_DIRSYNC
27392     /* The directory sync is only attempted if full_fsync is
27393     ** turned off or unavailable.  If a full_fsync occurred above,
27394     ** then the directory sync is superfluous.
27395     */
27396     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
27397        /*
27398        ** We have received multiple reports of fsync() returning
27399        ** errors when applied to directories on certain file systems.
27400        ** A failed directory sync is not a big deal.  So it seems
27401        ** better to ignore the error.  Ticket #1657
27402        */
27403        /* pFile->lastErrno = errno; */
27404        /* return SQLITE_IOERR; */
27405     }
27406 #endif
27407     /* Only need to sync once, so close the  directory when we are done */
27408     robust_close(pFile, pFile->dirfd, __LINE__);
27409     pFile->dirfd = -1;
27410   }
27411   return rc;
27412 }
27413
27414 /*
27415 ** Truncate an open file to a specified size
27416 */
27417 static int unixTruncate(sqlite3_file *id, i64 nByte){
27418   unixFile *pFile = (unixFile *)id;
27419   int rc;
27420   assert( pFile );
27421   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27422
27423   /* If the user has configured a chunk-size for this file, truncate the
27424   ** file so that it consists of an integer number of chunks (i.e. the
27425   ** actual file size after the operation may be larger than the requested
27426   ** size).
27427   */
27428   if( pFile->szChunk ){
27429     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27430   }
27431
27432   rc = robust_ftruncate(pFile->h, (off_t)nByte);
27433   if( rc ){
27434     pFile->lastErrno = errno;
27435     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27436   }else{
27437 #ifndef NDEBUG
27438     /* If we are doing a normal write to a database file (as opposed to
27439     ** doing a hot-journal rollback or a write to some file other than a
27440     ** normal database file) and we truncate the file to zero length,
27441     ** that effectively updates the change counter.  This might happen
27442     ** when restoring a database using the backup API from a zero-length
27443     ** source.
27444     */
27445     if( pFile->inNormalWrite && nByte==0 ){
27446       pFile->transCntrChng = 1;
27447     }
27448 #endif
27449
27450     return SQLITE_OK;
27451   }
27452 }
27453
27454 /*
27455 ** Determine the current size of a file in bytes
27456 */
27457 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27458   int rc;
27459   struct stat buf;
27460   assert( id );
27461   rc = osFstat(((unixFile*)id)->h, &buf);
27462   SimulateIOError( rc=1 );
27463   if( rc!=0 ){
27464     ((unixFile*)id)->lastErrno = errno;
27465     return SQLITE_IOERR_FSTAT;
27466   }
27467   *pSize = buf.st_size;
27468
27469   /* When opening a zero-size database, the findInodeInfo() procedure
27470   ** writes a single byte into that file in order to work around a bug
27471   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
27472   ** layers, we need to report this file size as zero even though it is
27473   ** really 1.   Ticket #3260.
27474   */
27475   if( *pSize==1 ) *pSize = 0;
27476
27477
27478   return SQLITE_OK;
27479 }
27480
27481 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27482 /*
27483 ** Handler for proxy-locking file-control verbs.  Defined below in the
27484 ** proxying locking division.
27485 */
27486 static int proxyFileControl(sqlite3_file*,int,void*);
27487 #endif
27488
27489 /* 
27490 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
27491 ** file-control operation.
27492 **
27493 ** If the user has configured a chunk-size for this file, it could be
27494 ** that the file needs to be extended at this point. Otherwise, the
27495 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27496 */
27497 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27498   if( pFile->szChunk ){
27499     i64 nSize;                    /* Required file size */
27500     struct stat buf;              /* Used to hold return values of fstat() */
27501    
27502     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27503
27504     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27505     if( nSize>(i64)buf.st_size ){
27506
27507 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27508       /* The code below is handling the return value of osFallocate() 
27509       ** correctly. posix_fallocate() is defined to "returns zero on success, 
27510       ** or an error number on  failure". See the manpage for details. */
27511       int err;
27512       do{
27513         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27514       }while( err==EINTR );
27515       if( err ) return SQLITE_IOERR_WRITE;
27516 #else
27517       /* If the OS does not have posix_fallocate(), fake it. First use
27518       ** ftruncate() to set the file size, then write a single byte to
27519       ** the last byte in each block within the extended region. This
27520       ** is the same technique used by glibc to implement posix_fallocate()
27521       ** on systems that do not have a real fallocate() system call.
27522       */
27523       int nBlk = buf.st_blksize;  /* File-system block size */
27524       i64 iWrite;                 /* Next offset to write to */
27525
27526       if( robust_ftruncate(pFile->h, nSize) ){
27527         pFile->lastErrno = errno;
27528         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27529       }
27530       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27531       while( iWrite<nSize ){
27532         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27533         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27534         iWrite += nBlk;
27535       }
27536 #endif
27537     }
27538   }
27539
27540   return SQLITE_OK;
27541 }
27542
27543 /*
27544 ** Information and control of an open file handle.
27545 */
27546 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27547   switch( op ){
27548     case SQLITE_FCNTL_LOCKSTATE: {
27549       *(int*)pArg = ((unixFile*)id)->eFileLock;
27550       return SQLITE_OK;
27551     }
27552     case SQLITE_LAST_ERRNO: {
27553       *(int*)pArg = ((unixFile*)id)->lastErrno;
27554       return SQLITE_OK;
27555     }
27556     case SQLITE_FCNTL_CHUNK_SIZE: {
27557       ((unixFile*)id)->szChunk = *(int *)pArg;
27558       return SQLITE_OK;
27559     }
27560     case SQLITE_FCNTL_SIZE_HINT: {
27561       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27562     }
27563 #ifndef NDEBUG
27564     /* The pager calls this method to signal that it has done
27565     ** a rollback and that the database is therefore unchanged and
27566     ** it hence it is OK for the transaction change counter to be
27567     ** unchanged.
27568     */
27569     case SQLITE_FCNTL_DB_UNCHANGED: {
27570       ((unixFile*)id)->dbUpdate = 0;
27571       return SQLITE_OK;
27572     }
27573 #endif
27574 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27575     case SQLITE_SET_LOCKPROXYFILE:
27576     case SQLITE_GET_LOCKPROXYFILE: {
27577       return proxyFileControl(id,op,pArg);
27578     }
27579 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27580     case SQLITE_FCNTL_SYNC_OMITTED: {
27581       return SQLITE_OK;  /* A no-op */
27582     }
27583   }
27584   return SQLITE_NOTFOUND;
27585 }
27586
27587 /*
27588 ** Return the sector size in bytes of the underlying block device for
27589 ** the specified file. This is almost always 512 bytes, but may be
27590 ** larger for some devices.
27591 **
27592 ** SQLite code assumes this function cannot fail. It also assumes that
27593 ** if two files are created in the same file-system directory (i.e.
27594 ** a database and its journal file) that the sector size will be the
27595 ** same for both.
27596 */
27597 static int unixSectorSize(sqlite3_file *NotUsed){
27598   UNUSED_PARAMETER(NotUsed);
27599   return SQLITE_DEFAULT_SECTOR_SIZE;
27600 }
27601
27602 /*
27603 ** Return the device characteristics for the file. This is always 0 for unix.
27604 */
27605 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27606   UNUSED_PARAMETER(NotUsed);
27607   return 0;
27608 }
27609
27610 #ifndef SQLITE_OMIT_WAL
27611
27612
27613 /*
27614 ** Object used to represent an shared memory buffer.  
27615 **
27616 ** When multiple threads all reference the same wal-index, each thread
27617 ** has its own unixShm object, but they all point to a single instance
27618 ** of this unixShmNode object.  In other words, each wal-index is opened
27619 ** only once per process.
27620 **
27621 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27622 ** We could coalesce this object into unixInodeInfo, but that would mean
27623 ** every open file that does not use shared memory (in other words, most
27624 ** open files) would have to carry around this extra information.  So
27625 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27626 ** and the unixShmNode object is created only when needed.
27627 **
27628 ** unixMutexHeld() must be true when creating or destroying
27629 ** this object or while reading or writing the following fields:
27630 **
27631 **      nRef
27632 **
27633 ** The following fields are read-only after the object is created:
27634 ** 
27635 **      fid
27636 **      zFilename
27637 **
27638 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27639 ** unixMutexHeld() is true when reading or writing any other field
27640 ** in this structure.
27641 */
27642 struct unixShmNode {
27643   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27644   sqlite3_mutex *mutex;      /* Mutex to access this object */
27645   char *zFilename;           /* Name of the mmapped file */
27646   int h;                     /* Open file descriptor */
27647   int szRegion;              /* Size of shared-memory regions */
27648   int nRegion;               /* Size of array apRegion */
27649   char **apRegion;           /* Array of mapped shared-memory regions */
27650   int nRef;                  /* Number of unixShm objects pointing to this */
27651   unixShm *pFirst;           /* All unixShm objects pointing to this */
27652 #ifdef SQLITE_DEBUG
27653   u8 exclMask;               /* Mask of exclusive locks held */
27654   u8 sharedMask;             /* Mask of shared locks held */
27655   u8 nextShmId;              /* Next available unixShm.id value */
27656 #endif
27657 };
27658
27659 /*
27660 ** Structure used internally by this VFS to record the state of an
27661 ** open shared memory connection.
27662 **
27663 ** The following fields are initialized when this object is created and
27664 ** are read-only thereafter:
27665 **
27666 **    unixShm.pFile
27667 **    unixShm.id
27668 **
27669 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
27670 ** while accessing any read/write fields.
27671 */
27672 struct unixShm {
27673   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27674   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27675   u8 hasMutex;               /* True if holding the unixShmNode mutex */
27676   u16 sharedMask;            /* Mask of shared locks held */
27677   u16 exclMask;              /* Mask of exclusive locks held */
27678 #ifdef SQLITE_DEBUG
27679   u8 id;                     /* Id of this connection within its unixShmNode */
27680 #endif
27681 };
27682
27683 /*
27684 ** Constants used for locking
27685 */
27686 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27687 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27688
27689 /*
27690 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27691 **
27692 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27693 ** otherwise.
27694 */
27695 static int unixShmSystemLock(
27696   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27697   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27698   int ofst,              /* First byte of the locking range */
27699   int n                  /* Number of bytes to lock */
27700 ){
27701   struct flock f;       /* The posix advisory locking structure */
27702   int rc = SQLITE_OK;   /* Result code form fcntl() */
27703
27704   /* Access to the unixShmNode object is serialized by the caller */
27705   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27706
27707   /* Shared locks never span more than one byte */
27708   assert( n==1 || lockType!=F_RDLCK );
27709
27710   /* Locks are within range */
27711   assert( n>=1 && n<SQLITE_SHM_NLOCK );
27712
27713   if( pShmNode->h>=0 ){
27714     /* Initialize the locking parameters */
27715     memset(&f, 0, sizeof(f));
27716     f.l_type = lockType;
27717     f.l_whence = SEEK_SET;
27718     f.l_start = ofst;
27719     f.l_len = n;
27720
27721     rc = osFcntl(pShmNode->h, F_SETLK, &f);
27722     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27723   }
27724
27725   /* Update the global lock state and do debug tracing */
27726 #ifdef SQLITE_DEBUG
27727   { u16 mask;
27728   OSTRACE(("SHM-LOCK "));
27729   mask = (1<<(ofst+n)) - (1<<ofst);
27730   if( rc==SQLITE_OK ){
27731     if( lockType==F_UNLCK ){
27732       OSTRACE(("unlock %d ok", ofst));
27733       pShmNode->exclMask &= ~mask;
27734       pShmNode->sharedMask &= ~mask;
27735     }else if( lockType==F_RDLCK ){
27736       OSTRACE(("read-lock %d ok", ofst));
27737       pShmNode->exclMask &= ~mask;
27738       pShmNode->sharedMask |= mask;
27739     }else{
27740       assert( lockType==F_WRLCK );
27741       OSTRACE(("write-lock %d ok", ofst));
27742       pShmNode->exclMask |= mask;
27743       pShmNode->sharedMask &= ~mask;
27744     }
27745   }else{
27746     if( lockType==F_UNLCK ){
27747       OSTRACE(("unlock %d failed", ofst));
27748     }else if( lockType==F_RDLCK ){
27749       OSTRACE(("read-lock failed"));
27750     }else{
27751       assert( lockType==F_WRLCK );
27752       OSTRACE(("write-lock %d failed", ofst));
27753     }
27754   }
27755   OSTRACE((" - afterwards %03x,%03x\n",
27756            pShmNode->sharedMask, pShmNode->exclMask));
27757   }
27758 #endif
27759
27760   return rc;        
27761 }
27762
27763
27764 /*
27765 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27766 **
27767 ** This is not a VFS shared-memory method; it is a utility function called
27768 ** by VFS shared-memory methods.
27769 */
27770 static void unixShmPurge(unixFile *pFd){
27771   unixShmNode *p = pFd->pInode->pShmNode;
27772   assert( unixMutexHeld() );
27773   if( p && p->nRef==0 ){
27774     int i;
27775     assert( p->pInode==pFd->pInode );
27776     if( p->mutex ) sqlite3_mutex_free(p->mutex);
27777     for(i=0; i<p->nRegion; i++){
27778       if( p->h>=0 ){
27779         munmap(p->apRegion[i], p->szRegion);
27780       }else{
27781         sqlite3_free(p->apRegion[i]);
27782       }
27783     }
27784     sqlite3_free(p->apRegion);
27785     if( p->h>=0 ){
27786       robust_close(pFd, p->h, __LINE__);
27787       p->h = -1;
27788     }
27789     p->pInode->pShmNode = 0;
27790     sqlite3_free(p);
27791   }
27792 }
27793
27794 /*
27795 ** Open a shared-memory area associated with open database file pDbFd.  
27796 ** This particular implementation uses mmapped files.
27797 **
27798 ** The file used to implement shared-memory is in the same directory
27799 ** as the open database file and has the same name as the open database
27800 ** file with the "-shm" suffix added.  For example, if the database file
27801 ** is "/home/user1/config.db" then the file that is created and mmapped
27802 ** for shared memory will be called "/home/user1/config.db-shm".  
27803 **
27804 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27805 ** some other tmpfs mount. But if a file in a different directory
27806 ** from the database file is used, then differing access permissions
27807 ** or a chroot() might cause two different processes on the same
27808 ** database to end up using different files for shared memory - 
27809 ** meaning that their memory would not really be shared - resulting
27810 ** in database corruption.  Nevertheless, this tmpfs file usage
27811 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27812 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27813 ** option results in an incompatible build of SQLite;  builds of SQLite
27814 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27815 ** same database file at the same time, database corruption will likely
27816 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27817 ** "unsupported" and may go away in a future SQLite release.
27818 **
27819 ** When opening a new shared-memory file, if no other instances of that
27820 ** file are currently open, in this process or in other processes, then
27821 ** the file must be truncated to zero length or have its header cleared.
27822 **
27823 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27824 ** that means that an exclusive lock is held on the database file and
27825 ** that no other processes are able to read or write the database.  In
27826 ** that case, we do not really need shared memory.  No shared memory
27827 ** file is created.  The shared memory will be simulated with heap memory.
27828 */
27829 static int unixOpenSharedMemory(unixFile *pDbFd){
27830   struct unixShm *p = 0;          /* The connection to be opened */
27831   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27832   int rc;                         /* Result code */
27833   unixInodeInfo *pInode;          /* The inode of fd */
27834   char *zShmFilename;             /* Name of the file used for SHM */
27835   int nShmFilename;               /* Size of the SHM filename in bytes */
27836
27837   /* Allocate space for the new unixShm object. */
27838   p = sqlite3_malloc( sizeof(*p) );
27839   if( p==0 ) return SQLITE_NOMEM;
27840   memset(p, 0, sizeof(*p));
27841   assert( pDbFd->pShm==0 );
27842
27843   /* Check to see if a unixShmNode object already exists. Reuse an existing
27844   ** one if present. Create a new one if necessary.
27845   */
27846   unixEnterMutex();
27847   pInode = pDbFd->pInode;
27848   pShmNode = pInode->pShmNode;
27849   if( pShmNode==0 ){
27850     struct stat sStat;                 /* fstat() info for database file */
27851
27852     /* Call fstat() to figure out the permissions on the database file. If
27853     ** a new *-shm file is created, an attempt will be made to create it
27854     ** with the same permissions. The actual permissions the file is created
27855     ** with are subject to the current umask setting.
27856     */
27857     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27858       rc = SQLITE_IOERR_FSTAT;
27859       goto shm_open_err;
27860     }
27861
27862 #ifdef SQLITE_SHM_DIRECTORY
27863     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
27864 #else
27865     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
27866 #endif
27867     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27868     if( pShmNode==0 ){
27869       rc = SQLITE_NOMEM;
27870       goto shm_open_err;
27871     }
27872     memset(pShmNode, 0, sizeof(*pShmNode));
27873     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27874 #ifdef SQLITE_SHM_DIRECTORY
27875     sqlite3_snprintf(nShmFilename, zShmFilename, 
27876                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27877                      (u32)sStat.st_ino, (u32)sStat.st_dev);
27878 #else
27879     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27880 #endif
27881     pShmNode->h = -1;
27882     pDbFd->pInode->pShmNode = pShmNode;
27883     pShmNode->pInode = pDbFd->pInode;
27884     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27885     if( pShmNode->mutex==0 ){
27886       rc = SQLITE_NOMEM;
27887       goto shm_open_err;
27888     }
27889
27890     if( pInode->bProcessLock==0 ){
27891       pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
27892                                (sStat.st_mode & 0777));
27893       if( pShmNode->h<0 ){
27894         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27895         goto shm_open_err;
27896       }
27897   
27898       /* Check to see if another process is holding the dead-man switch.
27899       ** If not, truncate the file to zero length. 
27900       */
27901       rc = SQLITE_OK;
27902       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27903         if( robust_ftruncate(pShmNode->h, 0) ){
27904           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27905         }
27906       }
27907       if( rc==SQLITE_OK ){
27908         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27909       }
27910       if( rc ) goto shm_open_err;
27911     }
27912   }
27913
27914   /* Make the new connection a child of the unixShmNode */
27915   p->pShmNode = pShmNode;
27916 #ifdef SQLITE_DEBUG
27917   p->id = pShmNode->nextShmId++;
27918 #endif
27919   pShmNode->nRef++;
27920   pDbFd->pShm = p;
27921   unixLeaveMutex();
27922
27923   /* The reference count on pShmNode has already been incremented under
27924   ** the cover of the unixEnterMutex() mutex and the pointer from the
27925   ** new (struct unixShm) object to the pShmNode has been set. All that is
27926   ** left to do is to link the new object into the linked list starting
27927   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
27928   ** mutex.
27929   */
27930   sqlite3_mutex_enter(pShmNode->mutex);
27931   p->pNext = pShmNode->pFirst;
27932   pShmNode->pFirst = p;
27933   sqlite3_mutex_leave(pShmNode->mutex);
27934   return SQLITE_OK;
27935
27936   /* Jump here on any error */
27937 shm_open_err:
27938   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27939   sqlite3_free(p);
27940   unixLeaveMutex();
27941   return rc;
27942 }
27943
27944 /*
27945 ** This function is called to obtain a pointer to region iRegion of the 
27946 ** shared-memory associated with the database file fd. Shared-memory regions 
27947 ** are numbered starting from zero. Each shared-memory region is szRegion 
27948 ** bytes in size.
27949 **
27950 ** If an error occurs, an error code is returned and *pp is set to NULL.
27951 **
27952 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27953 ** region has not been allocated (by any client, including one running in a
27954 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27955 ** bExtend is non-zero and the requested shared-memory region has not yet 
27956 ** been allocated, it is allocated by this function.
27957 **
27958 ** If the shared-memory region has already been allocated or is allocated by
27959 ** this call as described above, then it is mapped into this processes 
27960 ** address space (if it is not already), *pp is set to point to the mapped 
27961 ** memory and SQLITE_OK returned.
27962 */
27963 static int unixShmMap(
27964   sqlite3_file *fd,               /* Handle open on database file */
27965   int iRegion,                    /* Region to retrieve */
27966   int szRegion,                   /* Size of regions */
27967   int bExtend,                    /* True to extend file if necessary */
27968   void volatile **pp              /* OUT: Mapped memory */
27969 ){
27970   unixFile *pDbFd = (unixFile*)fd;
27971   unixShm *p;
27972   unixShmNode *pShmNode;
27973   int rc = SQLITE_OK;
27974
27975   /* If the shared-memory file has not yet been opened, open it now. */
27976   if( pDbFd->pShm==0 ){
27977     rc = unixOpenSharedMemory(pDbFd);
27978     if( rc!=SQLITE_OK ) return rc;
27979   }
27980
27981   p = pDbFd->pShm;
27982   pShmNode = p->pShmNode;
27983   sqlite3_mutex_enter(pShmNode->mutex);
27984   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27985   assert( pShmNode->pInode==pDbFd->pInode );
27986   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27987   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27988
27989   if( pShmNode->nRegion<=iRegion ){
27990     char **apNew;                      /* New apRegion[] array */
27991     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27992     struct stat sStat;                 /* Used by fstat() */
27993
27994     pShmNode->szRegion = szRegion;
27995
27996     if( pShmNode->h>=0 ){
27997       /* The requested region is not mapped into this processes address space.
27998       ** Check to see if it has been allocated (i.e. if the wal-index file is
27999       ** large enough to contain the requested region).
28000       */
28001       if( osFstat(pShmNode->h, &sStat) ){
28002         rc = SQLITE_IOERR_SHMSIZE;
28003         goto shmpage_out;
28004       }
28005   
28006       if( sStat.st_size<nByte ){
28007         /* The requested memory region does not exist. If bExtend is set to
28008         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28009         **
28010         ** Alternatively, if bExtend is true, use ftruncate() to allocate
28011         ** the requested memory region.
28012         */
28013         if( !bExtend ) goto shmpage_out;
28014         if( robust_ftruncate(pShmNode->h, nByte) ){
28015           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28016                             pShmNode->zFilename);
28017           goto shmpage_out;
28018         }
28019       }
28020     }
28021
28022     /* Map the requested memory region into this processes address space. */
28023     apNew = (char **)sqlite3_realloc(
28024         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28025     );
28026     if( !apNew ){
28027       rc = SQLITE_IOERR_NOMEM;
28028       goto shmpage_out;
28029     }
28030     pShmNode->apRegion = apNew;
28031     while(pShmNode->nRegion<=iRegion){
28032       void *pMem;
28033       if( pShmNode->h>=0 ){
28034         pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
28035             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28036         );
28037         if( pMem==MAP_FAILED ){
28038           rc = SQLITE_IOERR;
28039           goto shmpage_out;
28040         }
28041       }else{
28042         pMem = sqlite3_malloc(szRegion);
28043         if( pMem==0 ){
28044           rc = SQLITE_NOMEM;
28045           goto shmpage_out;
28046         }
28047         memset(pMem, 0, szRegion);
28048       }
28049       pShmNode->apRegion[pShmNode->nRegion] = pMem;
28050       pShmNode->nRegion++;
28051     }
28052   }
28053
28054 shmpage_out:
28055   if( pShmNode->nRegion>iRegion ){
28056     *pp = pShmNode->apRegion[iRegion];
28057   }else{
28058     *pp = 0;
28059   }
28060   sqlite3_mutex_leave(pShmNode->mutex);
28061   return rc;
28062 }
28063
28064 /*
28065 ** Change the lock state for a shared-memory segment.
28066 **
28067 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28068 ** different here than in posix.  In xShmLock(), one can go from unlocked
28069 ** to shared and back or from unlocked to exclusive and back.  But one may
28070 ** not go from shared to exclusive or from exclusive to shared.
28071 */
28072 static int unixShmLock(
28073   sqlite3_file *fd,          /* Database file holding the shared memory */
28074   int ofst,                  /* First lock to acquire or release */
28075   int n,                     /* Number of locks to acquire or release */
28076   int flags                  /* What to do with the lock */
28077 ){
28078   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28079   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28080   unixShm *pX;                          /* For looping over all siblings */
28081   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28082   int rc = SQLITE_OK;                   /* Result code */
28083   u16 mask;                             /* Mask of locks to take or release */
28084
28085   assert( pShmNode==pDbFd->pInode->pShmNode );
28086   assert( pShmNode->pInode==pDbFd->pInode );
28087   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28088   assert( n>=1 );
28089   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28090        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28091        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28092        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28093   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28094   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28095   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28096
28097   mask = (1<<(ofst+n)) - (1<<ofst);
28098   assert( n>1 || mask==(1<<ofst) );
28099   sqlite3_mutex_enter(pShmNode->mutex);
28100   if( flags & SQLITE_SHM_UNLOCK ){
28101     u16 allMask = 0; /* Mask of locks held by siblings */
28102
28103     /* See if any siblings hold this same lock */
28104     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28105       if( pX==p ) continue;
28106       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28107       allMask |= pX->sharedMask;
28108     }
28109
28110     /* Unlock the system-level locks */
28111     if( (mask & allMask)==0 ){
28112       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28113     }else{
28114       rc = SQLITE_OK;
28115     }
28116
28117     /* Undo the local locks */
28118     if( rc==SQLITE_OK ){
28119       p->exclMask &= ~mask;
28120       p->sharedMask &= ~mask;
28121     } 
28122   }else if( flags & SQLITE_SHM_SHARED ){
28123     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28124
28125     /* Find out which shared locks are already held by sibling connections.
28126     ** If any sibling already holds an exclusive lock, go ahead and return
28127     ** SQLITE_BUSY.
28128     */
28129     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28130       if( (pX->exclMask & mask)!=0 ){
28131         rc = SQLITE_BUSY;
28132         break;
28133       }
28134       allShared |= pX->sharedMask;
28135     }
28136
28137     /* Get shared locks at the system level, if necessary */
28138     if( rc==SQLITE_OK ){
28139       if( (allShared & mask)==0 ){
28140         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28141       }else{
28142         rc = SQLITE_OK;
28143       }
28144     }
28145
28146     /* Get the local shared locks */
28147     if( rc==SQLITE_OK ){
28148       p->sharedMask |= mask;
28149     }
28150   }else{
28151     /* Make sure no sibling connections hold locks that will block this
28152     ** lock.  If any do, return SQLITE_BUSY right away.
28153     */
28154     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28155       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28156         rc = SQLITE_BUSY;
28157         break;
28158       }
28159     }
28160   
28161     /* Get the exclusive locks at the system level.  Then if successful
28162     ** also mark the local connection as being locked.
28163     */
28164     if( rc==SQLITE_OK ){
28165       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28166       if( rc==SQLITE_OK ){
28167         assert( (p->sharedMask & mask)==0 );
28168         p->exclMask |= mask;
28169       }
28170     }
28171   }
28172   sqlite3_mutex_leave(pShmNode->mutex);
28173   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28174            p->id, getpid(), p->sharedMask, p->exclMask));
28175   return rc;
28176 }
28177
28178 /*
28179 ** Implement a memory barrier or memory fence on shared memory.  
28180 **
28181 ** All loads and stores begun before the barrier must complete before
28182 ** any load or store begun after the barrier.
28183 */
28184 static void unixShmBarrier(
28185   sqlite3_file *fd                /* Database file holding the shared memory */
28186 ){
28187   UNUSED_PARAMETER(fd);
28188   unixEnterMutex();
28189   unixLeaveMutex();
28190 }
28191
28192 /*
28193 ** Close a connection to shared-memory.  Delete the underlying 
28194 ** storage if deleteFlag is true.
28195 **
28196 ** If there is no shared memory associated with the connection then this
28197 ** routine is a harmless no-op.
28198 */
28199 static int unixShmUnmap(
28200   sqlite3_file *fd,               /* The underlying database file */
28201   int deleteFlag                  /* Delete shared-memory if true */
28202 ){
28203   unixShm *p;                     /* The connection to be closed */
28204   unixShmNode *pShmNode;          /* The underlying shared-memory file */
28205   unixShm **pp;                   /* For looping over sibling connections */
28206   unixFile *pDbFd;                /* The underlying database file */
28207
28208   pDbFd = (unixFile*)fd;
28209   p = pDbFd->pShm;
28210   if( p==0 ) return SQLITE_OK;
28211   pShmNode = p->pShmNode;
28212
28213   assert( pShmNode==pDbFd->pInode->pShmNode );
28214   assert( pShmNode->pInode==pDbFd->pInode );
28215
28216   /* Remove connection p from the set of connections associated
28217   ** with pShmNode */
28218   sqlite3_mutex_enter(pShmNode->mutex);
28219   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28220   *pp = p->pNext;
28221
28222   /* Free the connection p */
28223   sqlite3_free(p);
28224   pDbFd->pShm = 0;
28225   sqlite3_mutex_leave(pShmNode->mutex);
28226
28227   /* If pShmNode->nRef has reached 0, then close the underlying
28228   ** shared-memory file, too */
28229   unixEnterMutex();
28230   assert( pShmNode->nRef>0 );
28231   pShmNode->nRef--;
28232   if( pShmNode->nRef==0 ){
28233     if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
28234     unixShmPurge(pDbFd);
28235   }
28236   unixLeaveMutex();
28237
28238   return SQLITE_OK;
28239 }
28240
28241
28242 #else
28243 # define unixShmMap     0
28244 # define unixShmLock    0
28245 # define unixShmBarrier 0
28246 # define unixShmUnmap   0
28247 #endif /* #ifndef SQLITE_OMIT_WAL */
28248
28249 /*
28250 ** Here ends the implementation of all sqlite3_file methods.
28251 **
28252 ********************** End sqlite3_file Methods *******************************
28253 ******************************************************************************/
28254
28255 /*
28256 ** This division contains definitions of sqlite3_io_methods objects that
28257 ** implement various file locking strategies.  It also contains definitions
28258 ** of "finder" functions.  A finder-function is used to locate the appropriate
28259 ** sqlite3_io_methods object for a particular database file.  The pAppData
28260 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28261 ** the correct finder-function for that VFS.
28262 **
28263 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28264 ** object.  The only interesting finder-function is autolockIoFinder, which
28265 ** looks at the filesystem type and tries to guess the best locking
28266 ** strategy from that.
28267 **
28268 ** For finder-funtion F, two objects are created:
28269 **
28270 **    (1) The real finder-function named "FImpt()".
28271 **
28272 **    (2) A constant pointer to this function named just "F".
28273 **
28274 **
28275 ** A pointer to the F pointer is used as the pAppData value for VFS
28276 ** objects.  We have to do this instead of letting pAppData point
28277 ** directly at the finder-function since C90 rules prevent a void*
28278 ** from be cast into a function pointer.
28279 **
28280 **
28281 ** Each instance of this macro generates two objects:
28282 **
28283 **   *  A constant sqlite3_io_methods object call METHOD that has locking
28284 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28285 **
28286 **   *  An I/O method finder function called FINDER that returns a pointer
28287 **      to the METHOD object in the previous bullet.
28288 */
28289 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28290 static const sqlite3_io_methods METHOD = {                                   \
28291    VERSION,                    /* iVersion */                                \
28292    CLOSE,                      /* xClose */                                  \
28293    unixRead,                   /* xRead */                                   \
28294    unixWrite,                  /* xWrite */                                  \
28295    unixTruncate,               /* xTruncate */                               \
28296    unixSync,                   /* xSync */                                   \
28297    unixFileSize,               /* xFileSize */                               \
28298    LOCK,                       /* xLock */                                   \
28299    UNLOCK,                     /* xUnlock */                                 \
28300    CKLOCK,                     /* xCheckReservedLock */                      \
28301    unixFileControl,            /* xFileControl */                            \
28302    unixSectorSize,             /* xSectorSize */                             \
28303    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28304    unixShmMap,                 /* xShmMap */                                 \
28305    unixShmLock,                /* xShmLock */                                \
28306    unixShmBarrier,             /* xShmBarrier */                             \
28307    unixShmUnmap                /* xShmUnmap */                               \
28308 };                                                                           \
28309 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28310   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28311   return &METHOD;                                                            \
28312 }                                                                            \
28313 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28314     = FINDER##Impl;
28315
28316 /*
28317 ** Here are all of the sqlite3_io_methods objects for each of the
28318 ** locking strategies.  Functions that return pointers to these methods
28319 ** are also created.
28320 */
28321 IOMETHODS(
28322   posixIoFinder,            /* Finder function name */
28323   posixIoMethods,           /* sqlite3_io_methods object name */
28324   2,                        /* shared memory is enabled */
28325   unixClose,                /* xClose method */
28326   unixLock,                 /* xLock method */
28327   unixUnlock,               /* xUnlock method */
28328   unixCheckReservedLock     /* xCheckReservedLock method */
28329 )
28330 IOMETHODS(
28331   nolockIoFinder,           /* Finder function name */
28332   nolockIoMethods,          /* sqlite3_io_methods object name */
28333   1,                        /* shared memory is disabled */
28334   nolockClose,              /* xClose method */
28335   nolockLock,               /* xLock method */
28336   nolockUnlock,             /* xUnlock method */
28337   nolockCheckReservedLock   /* xCheckReservedLock method */
28338 )
28339 IOMETHODS(
28340   dotlockIoFinder,          /* Finder function name */
28341   dotlockIoMethods,         /* sqlite3_io_methods object name */
28342   1,                        /* shared memory is disabled */
28343   dotlockClose,             /* xClose method */
28344   dotlockLock,              /* xLock method */
28345   dotlockUnlock,            /* xUnlock method */
28346   dotlockCheckReservedLock  /* xCheckReservedLock method */
28347 )
28348
28349 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28350 IOMETHODS(
28351   flockIoFinder,            /* Finder function name */
28352   flockIoMethods,           /* sqlite3_io_methods object name */
28353   1,                        /* shared memory is disabled */
28354   flockClose,               /* xClose method */
28355   flockLock,                /* xLock method */
28356   flockUnlock,              /* xUnlock method */
28357   flockCheckReservedLock    /* xCheckReservedLock method */
28358 )
28359 #endif
28360
28361 #if OS_VXWORKS
28362 IOMETHODS(
28363   semIoFinder,              /* Finder function name */
28364   semIoMethods,             /* sqlite3_io_methods object name */
28365   1,                        /* shared memory is disabled */
28366   semClose,                 /* xClose method */
28367   semLock,                  /* xLock method */
28368   semUnlock,                /* xUnlock method */
28369   semCheckReservedLock      /* xCheckReservedLock method */
28370 )
28371 #endif
28372
28373 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28374 IOMETHODS(
28375   afpIoFinder,              /* Finder function name */
28376   afpIoMethods,             /* sqlite3_io_methods object name */
28377   1,                        /* shared memory is disabled */
28378   afpClose,                 /* xClose method */
28379   afpLock,                  /* xLock method */
28380   afpUnlock,                /* xUnlock method */
28381   afpCheckReservedLock      /* xCheckReservedLock method */
28382 )
28383 #endif
28384
28385 /*
28386 ** The proxy locking method is a "super-method" in the sense that it
28387 ** opens secondary file descriptors for the conch and lock files and
28388 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28389 ** secondary files.  For this reason, the division that implements
28390 ** proxy locking is located much further down in the file.  But we need
28391 ** to go ahead and define the sqlite3_io_methods and finder function
28392 ** for proxy locking here.  So we forward declare the I/O methods.
28393 */
28394 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28395 static int proxyClose(sqlite3_file*);
28396 static int proxyLock(sqlite3_file*, int);
28397 static int proxyUnlock(sqlite3_file*, int);
28398 static int proxyCheckReservedLock(sqlite3_file*, int*);
28399 IOMETHODS(
28400   proxyIoFinder,            /* Finder function name */
28401   proxyIoMethods,           /* sqlite3_io_methods object name */
28402   1,                        /* shared memory is disabled */
28403   proxyClose,               /* xClose method */
28404   proxyLock,                /* xLock method */
28405   proxyUnlock,              /* xUnlock method */
28406   proxyCheckReservedLock    /* xCheckReservedLock method */
28407 )
28408 #endif
28409
28410 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28411 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28412 IOMETHODS(
28413   nfsIoFinder,               /* Finder function name */
28414   nfsIoMethods,              /* sqlite3_io_methods object name */
28415   1,                         /* shared memory is disabled */
28416   unixClose,                 /* xClose method */
28417   unixLock,                  /* xLock method */
28418   nfsUnlock,                 /* xUnlock method */
28419   unixCheckReservedLock      /* xCheckReservedLock method */
28420 )
28421 #endif
28422
28423 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28424 /* 
28425 ** This "finder" function attempts to determine the best locking strategy 
28426 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28427 ** object that implements that strategy.
28428 **
28429 ** This is for MacOSX only.
28430 */
28431 static const sqlite3_io_methods *autolockIoFinderImpl(
28432   const char *filePath,    /* name of the database file */
28433   unixFile *pNew           /* open file object for the database file */
28434 ){
28435   static const struct Mapping {
28436     const char *zFilesystem;              /* Filesystem type name */
28437     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28438   } aMap[] = {
28439     { "hfs",    &posixIoMethods },
28440     { "ufs",    &posixIoMethods },
28441     { "afpfs",  &afpIoMethods },
28442     { "smbfs",  &afpIoMethods },
28443     { "webdav", &nolockIoMethods },
28444     { 0, 0 }
28445   };
28446   int i;
28447   struct statfs fsInfo;
28448   struct flock lockInfo;
28449
28450   if( !filePath ){
28451     /* If filePath==NULL that means we are dealing with a transient file
28452     ** that does not need to be locked. */
28453     return &nolockIoMethods;
28454   }
28455   if( statfs(filePath, &fsInfo) != -1 ){
28456     if( fsInfo.f_flags & MNT_RDONLY ){
28457       return &nolockIoMethods;
28458     }
28459     for(i=0; aMap[i].zFilesystem; i++){
28460       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28461         return aMap[i].pMethods;
28462       }
28463     }
28464   }
28465
28466   /* Default case. Handles, amongst others, "nfs".
28467   ** Test byte-range lock using fcntl(). If the call succeeds, 
28468   ** assume that the file-system supports POSIX style locks. 
28469   */
28470   lockInfo.l_len = 1;
28471   lockInfo.l_start = 0;
28472   lockInfo.l_whence = SEEK_SET;
28473   lockInfo.l_type = F_RDLCK;
28474   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28475     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28476       return &nfsIoMethods;
28477     } else {
28478       return &posixIoMethods;
28479     }
28480   }else{
28481     return &dotlockIoMethods;
28482   }
28483 }
28484 static const sqlite3_io_methods 
28485   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28486
28487 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28488
28489 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28490 /* 
28491 ** This "finder" function attempts to determine the best locking strategy 
28492 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28493 ** object that implements that strategy.
28494 **
28495 ** This is for VXWorks only.
28496 */
28497 static const sqlite3_io_methods *autolockIoFinderImpl(
28498   const char *filePath,    /* name of the database file */
28499   unixFile *pNew           /* the open file object */
28500 ){
28501   struct flock lockInfo;
28502
28503   if( !filePath ){
28504     /* If filePath==NULL that means we are dealing with a transient file
28505     ** that does not need to be locked. */
28506     return &nolockIoMethods;
28507   }
28508
28509   /* Test if fcntl() is supported and use POSIX style locks.
28510   ** Otherwise fall back to the named semaphore method.
28511   */
28512   lockInfo.l_len = 1;
28513   lockInfo.l_start = 0;
28514   lockInfo.l_whence = SEEK_SET;
28515   lockInfo.l_type = F_RDLCK;
28516   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28517     return &posixIoMethods;
28518   }else{
28519     return &semIoMethods;
28520   }
28521 }
28522 static const sqlite3_io_methods 
28523   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28524
28525 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28526
28527 /*
28528 ** An abstract type for a pointer to a IO method finder function:
28529 */
28530 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28531
28532
28533 /****************************************************************************
28534 **************************** sqlite3_vfs methods ****************************
28535 **
28536 ** This division contains the implementation of methods on the
28537 ** sqlite3_vfs object.
28538 */
28539
28540 /*
28541 ** Initialize the contents of the unixFile structure pointed to by pId.
28542 */
28543 static int fillInUnixFile(
28544   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28545   int h,                  /* Open file descriptor of file being opened */
28546   int dirfd,              /* Directory file descriptor */
28547   sqlite3_file *pId,      /* Write to the unixFile structure here */
28548   const char *zFilename,  /* Name of the file being opened */
28549   int noLock,             /* Omit locking if true */
28550   int isDelete,           /* Delete on close if true */
28551   int isReadOnly          /* True if the file is opened read-only */
28552 ){
28553   const sqlite3_io_methods *pLockingStyle;
28554   unixFile *pNew = (unixFile *)pId;
28555   int rc = SQLITE_OK;
28556
28557   assert( pNew->pInode==NULL );
28558
28559   /* Parameter isDelete is only used on vxworks. Express this explicitly 
28560   ** here to prevent compiler warnings about unused parameters.
28561   */
28562   UNUSED_PARAMETER(isDelete);
28563
28564   /* Usually the path zFilename should not be a relative pathname. The
28565   ** exception is when opening the proxy "conch" file in builds that
28566   ** include the special Apple locking styles.
28567   */
28568 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28569   assert( zFilename==0 || zFilename[0]=='/' 
28570     || pVfs->pAppData==(void*)&autolockIoFinder );
28571 #else
28572   assert( zFilename==0 || zFilename[0]=='/' );
28573 #endif
28574
28575   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28576   pNew->h = h;
28577   pNew->dirfd = dirfd;
28578   pNew->zPath = zFilename;
28579   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
28580     pNew->ctrlFlags = UNIXFILE_EXCL;
28581   }else{
28582     pNew->ctrlFlags = 0;
28583   }
28584   if( isReadOnly ){
28585     pNew->ctrlFlags |= UNIXFILE_RDONLY;
28586   }
28587
28588 #if OS_VXWORKS
28589   pNew->pId = vxworksFindFileId(zFilename);
28590   if( pNew->pId==0 ){
28591     noLock = 1;
28592     rc = SQLITE_NOMEM;
28593   }
28594 #endif
28595
28596   if( noLock ){
28597     pLockingStyle = &nolockIoMethods;
28598   }else{
28599     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28600 #if SQLITE_ENABLE_LOCKING_STYLE
28601     /* Cache zFilename in the locking context (AFP and dotlock override) for
28602     ** proxyLock activation is possible (remote proxy is based on db name)
28603     ** zFilename remains valid until file is closed, to support */
28604     pNew->lockingContext = (void*)zFilename;
28605 #endif
28606   }
28607
28608   if( pLockingStyle == &posixIoMethods
28609 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28610     || pLockingStyle == &nfsIoMethods
28611 #endif
28612   ){
28613     unixEnterMutex();
28614     rc = findInodeInfo(pNew, &pNew->pInode);
28615     if( rc!=SQLITE_OK ){
28616       /* If an error occured in findInodeInfo(), close the file descriptor
28617       ** immediately, before releasing the mutex. findInodeInfo() may fail
28618       ** in two scenarios:
28619       **
28620       **   (a) A call to fstat() failed.
28621       **   (b) A malloc failed.
28622       **
28623       ** Scenario (b) may only occur if the process is holding no other
28624       ** file descriptors open on the same file. If there were other file
28625       ** descriptors on this file, then no malloc would be required by
28626       ** findInodeInfo(). If this is the case, it is quite safe to close
28627       ** handle h - as it is guaranteed that no posix locks will be released
28628       ** by doing so.
28629       **
28630       ** If scenario (a) caused the error then things are not so safe. The
28631       ** implicit assumption here is that if fstat() fails, things are in
28632       ** such bad shape that dropping a lock or two doesn't matter much.
28633       */
28634       robust_close(pNew, h, __LINE__);
28635       h = -1;
28636     }
28637     unixLeaveMutex();
28638   }
28639
28640 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28641   else if( pLockingStyle == &afpIoMethods ){
28642     /* AFP locking uses the file path so it needs to be included in
28643     ** the afpLockingContext.
28644     */
28645     afpLockingContext *pCtx;
28646     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28647     if( pCtx==0 ){
28648       rc = SQLITE_NOMEM;
28649     }else{
28650       /* NB: zFilename exists and remains valid until the file is closed
28651       ** according to requirement F11141.  So we do not need to make a
28652       ** copy of the filename. */
28653       pCtx->dbPath = zFilename;
28654       pCtx->reserved = 0;
28655       srandomdev();
28656       unixEnterMutex();
28657       rc = findInodeInfo(pNew, &pNew->pInode);
28658       if( rc!=SQLITE_OK ){
28659         sqlite3_free(pNew->lockingContext);
28660         robust_close(pNew, h, __LINE__);
28661         h = -1;
28662       }
28663       unixLeaveMutex();        
28664     }
28665   }
28666 #endif
28667
28668   else if( pLockingStyle == &dotlockIoMethods ){
28669     /* Dotfile locking uses the file path so it needs to be included in
28670     ** the dotlockLockingContext 
28671     */
28672     char *zLockFile;
28673     int nFilename;
28674     nFilename = (int)strlen(zFilename) + 6;
28675     zLockFile = (char *)sqlite3_malloc(nFilename);
28676     if( zLockFile==0 ){
28677       rc = SQLITE_NOMEM;
28678     }else{
28679       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28680     }
28681     pNew->lockingContext = zLockFile;
28682   }
28683
28684 #if OS_VXWORKS
28685   else if( pLockingStyle == &semIoMethods ){
28686     /* Named semaphore locking uses the file path so it needs to be
28687     ** included in the semLockingContext
28688     */
28689     unixEnterMutex();
28690     rc = findInodeInfo(pNew, &pNew->pInode);
28691     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28692       char *zSemName = pNew->pInode->aSemName;
28693       int n;
28694       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28695                        pNew->pId->zCanonicalName);
28696       for( n=1; zSemName[n]; n++ )
28697         if( zSemName[n]=='/' ) zSemName[n] = '_';
28698       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28699       if( pNew->pInode->pSem == SEM_FAILED ){
28700         rc = SQLITE_NOMEM;
28701         pNew->pInode->aSemName[0] = '\0';
28702       }
28703     }
28704     unixLeaveMutex();
28705   }
28706 #endif
28707   
28708   pNew->lastErrno = 0;
28709 #if OS_VXWORKS
28710   if( rc!=SQLITE_OK ){
28711     if( h>=0 ) robust_close(pNew, h, __LINE__);
28712     h = -1;
28713     unlink(zFilename);
28714     isDelete = 0;
28715   }
28716   pNew->isDelete = isDelete;
28717 #endif
28718   if( rc!=SQLITE_OK ){
28719     if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
28720     if( h>=0 ) robust_close(pNew, h, __LINE__);
28721   }else{
28722     pNew->pMethod = pLockingStyle;
28723     OpenCounter(+1);
28724   }
28725   return rc;
28726 }
28727
28728 /*
28729 ** Open a file descriptor to the directory containing file zFilename.
28730 ** If successful, *pFd is set to the opened file descriptor and
28731 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28732 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28733 ** value.
28734 **
28735 ** If SQLITE_OK is returned, the caller is responsible for closing
28736 ** the file descriptor *pFd using close().
28737 */
28738 static int openDirectory(const char *zFilename, int *pFd){
28739   int ii;
28740   int fd = -1;
28741   char zDirname[MAX_PATHNAME+1];
28742
28743   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28744   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28745   if( ii>0 ){
28746     zDirname[ii] = '\0';
28747     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28748     if( fd>=0 ){
28749 #ifdef FD_CLOEXEC
28750       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
28751 #endif
28752       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28753     }
28754   }
28755   *pFd = fd;
28756   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28757 }
28758
28759 /*
28760 ** Return the name of a directory in which to put temporary files.
28761 ** If no suitable temporary file directory can be found, return NULL.
28762 */
28763 static const char *unixTempFileDir(void){
28764   static const char *azDirs[] = {
28765      0,
28766      0,
28767      "/var/tmp",
28768      "/usr/tmp",
28769      "/tmp",
28770      0        /* List terminator */
28771   };
28772   unsigned int i;
28773   struct stat buf;
28774   const char *zDir = 0;
28775
28776   azDirs[0] = sqlite3_temp_directory;
28777   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28778   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28779     if( zDir==0 ) continue;
28780     if( osStat(zDir, &buf) ) continue;
28781     if( !S_ISDIR(buf.st_mode) ) continue;
28782     if( osAccess(zDir, 07) ) continue;
28783     break;
28784   }
28785   return zDir;
28786 }
28787
28788 /*
28789 ** Create a temporary file name in zBuf.  zBuf must be allocated
28790 ** by the calling process and must be big enough to hold at least
28791 ** pVfs->mxPathname bytes.
28792 */
28793 static int unixGetTempname(int nBuf, char *zBuf){
28794   static const unsigned char zChars[] =
28795     "abcdefghijklmnopqrstuvwxyz"
28796     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28797     "0123456789";
28798   unsigned int i, j;
28799   const char *zDir;
28800
28801   /* It's odd to simulate an io-error here, but really this is just
28802   ** using the io-error infrastructure to test that SQLite handles this
28803   ** function failing. 
28804   */
28805   SimulateIOError( return SQLITE_IOERR );
28806
28807   zDir = unixTempFileDir();
28808   if( zDir==0 ) zDir = ".";
28809
28810   /* Check that the output buffer is large enough for the temporary file 
28811   ** name. If it is not, return SQLITE_ERROR.
28812   */
28813   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
28814     return SQLITE_ERROR;
28815   }
28816
28817   do{
28818     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28819     j = (int)strlen(zBuf);
28820     sqlite3_randomness(15, &zBuf[j]);
28821     for(i=0; i<15; i++, j++){
28822       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28823     }
28824     zBuf[j] = 0;
28825   }while( osAccess(zBuf,0)==0 );
28826   return SQLITE_OK;
28827 }
28828
28829 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28830 /*
28831 ** Routine to transform a unixFile into a proxy-locking unixFile.
28832 ** Implementation in the proxy-lock division, but used by unixOpen()
28833 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28834 */
28835 static int proxyTransformUnixFile(unixFile*, const char*);
28836 #endif
28837
28838 /*
28839 ** Search for an unused file descriptor that was opened on the database 
28840 ** file (not a journal or master-journal file) identified by pathname
28841 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28842 ** argument to this function.
28843 **
28844 ** Such a file descriptor may exist if a database connection was closed
28845 ** but the associated file descriptor could not be closed because some
28846 ** other file descriptor open on the same file is holding a file-lock.
28847 ** Refer to comments in the unixClose() function and the lengthy comment
28848 ** describing "Posix Advisory Locking" at the start of this file for 
28849 ** further details. Also, ticket #4018.
28850 **
28851 ** If a suitable file descriptor is found, then it is returned. If no
28852 ** such file descriptor is located, -1 is returned.
28853 */
28854 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28855   UnixUnusedFd *pUnused = 0;
28856
28857   /* Do not search for an unused file descriptor on vxworks. Not because
28858   ** vxworks would not benefit from the change (it might, we're not sure),
28859   ** but because no way to test it is currently available. It is better 
28860   ** not to risk breaking vxworks support for the sake of such an obscure 
28861   ** feature.  */
28862 #if !OS_VXWORKS
28863   struct stat sStat;                   /* Results of stat() call */
28864
28865   /* A stat() call may fail for various reasons. If this happens, it is
28866   ** almost certain that an open() call on the same path will also fail.
28867   ** For this reason, if an error occurs in the stat() call here, it is
28868   ** ignored and -1 is returned. The caller will try to open a new file
28869   ** descriptor on the same path, fail, and return an error to SQLite.
28870   **
28871   ** Even if a subsequent open() call does succeed, the consequences of
28872   ** not searching for a resusable file descriptor are not dire.  */
28873   if( 0==stat(zPath, &sStat) ){
28874     unixInodeInfo *pInode;
28875
28876     unixEnterMutex();
28877     pInode = inodeList;
28878     while( pInode && (pInode->fileId.dev!=sStat.st_dev
28879                      || pInode->fileId.ino!=sStat.st_ino) ){
28880        pInode = pInode->pNext;
28881     }
28882     if( pInode ){
28883       UnixUnusedFd **pp;
28884       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28885       pUnused = *pp;
28886       if( pUnused ){
28887         *pp = pUnused->pNext;
28888       }
28889     }
28890     unixLeaveMutex();
28891   }
28892 #endif    /* if !OS_VXWORKS */
28893   return pUnused;
28894 }
28895
28896 /*
28897 ** This function is called by unixOpen() to determine the unix permissions
28898 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28899 ** and a value suitable for passing as the third argument to open(2) is
28900 ** written to *pMode. If an IO error occurs, an SQLite error code is 
28901 ** returned and the value of *pMode is not modified.
28902 **
28903 ** If the file being opened is a temporary file, it is always created with
28904 ** the octal permissions 0600 (read/writable by owner only). If the file
28905 ** is a database or master journal file, it is created with the permissions 
28906 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
28907 **
28908 ** Finally, if the file being opened is a WAL or regular journal file, then 
28909 ** this function queries the file-system for the permissions on the 
28910 ** corresponding database file and sets *pMode to this value. Whenever 
28911 ** possible, WAL and journal files are created using the same permissions 
28912 ** as the associated database file.
28913 */
28914 static int findCreateFileMode(
28915   const char *zPath,              /* Path of file (possibly) being created */
28916   int flags,                      /* Flags passed as 4th argument to xOpen() */
28917   mode_t *pMode                   /* OUT: Permissions to open file with */
28918 ){
28919   int rc = SQLITE_OK;             /* Return Code */
28920   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28921     char zDb[MAX_PATHNAME+1];     /* Database file path */
28922     int nDb;                      /* Number of valid bytes in zDb */
28923     struct stat sStat;            /* Output of stat() on database file */
28924
28925     /* zPath is a path to a WAL or journal file. The following block derives
28926     ** the path to the associated database file from zPath. This block handles
28927     ** the following naming conventions:
28928     **
28929     **   "<path to db>-journal"
28930     **   "<path to db>-wal"
28931     **   "<path to db>-journal-NNNN"
28932     **   "<path to db>-wal-NNNN"
28933     **
28934     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are 
28935     ** used by the test_multiplex.c module.
28936     */
28937     nDb = sqlite3Strlen30(zPath) - 1; 
28938     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
28939     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
28940     memcpy(zDb, zPath, nDb);
28941     zDb[nDb] = '\0';
28942
28943     if( 0==stat(zDb, &sStat) ){
28944       *pMode = sStat.st_mode & 0777;
28945     }else{
28946       rc = SQLITE_IOERR_FSTAT;
28947     }
28948   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28949     *pMode = 0600;
28950   }else{
28951     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
28952   }
28953   return rc;
28954 }
28955
28956 /*
28957 ** Open the file zPath.
28958 ** 
28959 ** Previously, the SQLite OS layer used three functions in place of this
28960 ** one:
28961 **
28962 **     sqlite3OsOpenReadWrite();
28963 **     sqlite3OsOpenReadOnly();
28964 **     sqlite3OsOpenExclusive();
28965 **
28966 ** These calls correspond to the following combinations of flags:
28967 **
28968 **     ReadWrite() ->     (READWRITE | CREATE)
28969 **     ReadOnly()  ->     (READONLY) 
28970 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28971 **
28972 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28973 ** true, the file was configured to be automatically deleted when the
28974 ** file handle closed. To achieve the same effect using this new 
28975 ** interface, add the DELETEONCLOSE flag to those specified above for 
28976 ** OpenExclusive().
28977 */
28978 static int unixOpen(
28979   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28980   const char *zPath,           /* Pathname of file to be opened */
28981   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28982   int flags,                   /* Input flags to control the opening */
28983   int *pOutFlags               /* Output flags returned to SQLite core */
28984 ){
28985   unixFile *p = (unixFile *)pFile;
28986   int fd = -1;                   /* File descriptor returned by open() */
28987   int dirfd = -1;                /* Directory file descriptor */
28988   int openFlags = 0;             /* Flags to pass to open() */
28989   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28990   int noLock;                    /* True to omit locking primitives */
28991   int rc = SQLITE_OK;            /* Function Return Code */
28992
28993   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28994   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28995   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28996   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28997   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28998 #if SQLITE_ENABLE_LOCKING_STYLE
28999   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29000 #endif
29001
29002   /* If creating a master or main-file journal, this function will open
29003   ** a file-descriptor on the directory too. The first time unixSync()
29004   ** is called the directory file descriptor will be fsync()ed and close()d.
29005   */
29006   int isOpenDirectory = (isCreate && (
29007         eType==SQLITE_OPEN_MASTER_JOURNAL 
29008      || eType==SQLITE_OPEN_MAIN_JOURNAL 
29009      || eType==SQLITE_OPEN_WAL
29010   ));
29011
29012   /* If argument zPath is a NULL pointer, this function is required to open
29013   ** a temporary file. Use this buffer to store the file name in.
29014   */
29015   char zTmpname[MAX_PATHNAME+1];
29016   const char *zName = zPath;
29017
29018   /* Check the following statements are true: 
29019   **
29020   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
29021   **   (b) if CREATE is set, then READWRITE must also be set, and
29022   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29023   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29024   */
29025   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29026   assert(isCreate==0 || isReadWrite);
29027   assert(isExclusive==0 || isCreate);
29028   assert(isDelete==0 || isCreate);
29029
29030   /* The main DB, main journal, WAL file and master journal are never 
29031   ** automatically deleted. Nor are they ever temporary files.  */
29032   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29033   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29034   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29035   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29036
29037   /* Assert that the upper layer has set one of the "file-type" flags. */
29038   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
29039        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
29040        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
29041        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29042   );
29043
29044   memset(p, 0, sizeof(unixFile));
29045
29046   if( eType==SQLITE_OPEN_MAIN_DB ){
29047     UnixUnusedFd *pUnused;
29048     pUnused = findReusableFd(zName, flags);
29049     if( pUnused ){
29050       fd = pUnused->fd;
29051     }else{
29052       pUnused = sqlite3_malloc(sizeof(*pUnused));
29053       if( !pUnused ){
29054         return SQLITE_NOMEM;
29055       }
29056     }
29057     p->pUnused = pUnused;
29058   }else if( !zName ){
29059     /* If zName is NULL, the upper layer is requesting a temp file. */
29060     assert(isDelete && !isOpenDirectory);
29061     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29062     if( rc!=SQLITE_OK ){
29063       return rc;
29064     }
29065     zName = zTmpname;
29066   }
29067
29068   /* Determine the value of the flags parameter passed to POSIX function
29069   ** open(). These must be calculated even if open() is not called, as
29070   ** they may be stored as part of the file handle and used by the 
29071   ** 'conch file' locking functions later on.  */
29072   if( isReadonly )  openFlags |= O_RDONLY;
29073   if( isReadWrite ) openFlags |= O_RDWR;
29074   if( isCreate )    openFlags |= O_CREAT;
29075   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29076   openFlags |= (O_LARGEFILE|O_BINARY);
29077
29078   if( fd<0 ){
29079     mode_t openMode;              /* Permissions to create file with */
29080     rc = findCreateFileMode(zName, flags, &openMode);
29081     if( rc!=SQLITE_OK ){
29082       assert( !p->pUnused );
29083       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29084       return rc;
29085     }
29086     fd = robust_open(zName, openFlags, openMode);
29087     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29088     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29089       /* Failed to open the file for read/write access. Try read-only. */
29090       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29091       openFlags &= ~(O_RDWR|O_CREAT);
29092       flags |= SQLITE_OPEN_READONLY;
29093       openFlags |= O_RDONLY;
29094       isReadonly = 1;
29095       fd = robust_open(zName, openFlags, openMode);
29096     }
29097     if( fd<0 ){
29098       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29099       goto open_finished;
29100     }
29101   }
29102   assert( fd>=0 );
29103   if( pOutFlags ){
29104     *pOutFlags = flags;
29105   }
29106
29107   if( p->pUnused ){
29108     p->pUnused->fd = fd;
29109     p->pUnused->flags = flags;
29110   }
29111
29112   if( isDelete ){
29113 #if OS_VXWORKS
29114     zPath = zName;
29115 #else
29116     unlink(zName);
29117 #endif
29118   }
29119 #if SQLITE_ENABLE_LOCKING_STYLE
29120   else{
29121     p->openFlags = openFlags;
29122   }
29123 #endif
29124
29125   if( isOpenDirectory ){
29126     rc = openDirectory(zPath, &dirfd);
29127     if( rc!=SQLITE_OK ){
29128       /* It is safe to close fd at this point, because it is guaranteed not
29129       ** to be open on a database file. If it were open on a database file,
29130       ** it would not be safe to close as this would release any locks held
29131       ** on the file by this process.  */
29132       assert( eType!=SQLITE_OPEN_MAIN_DB );
29133       robust_close(p, fd, __LINE__);
29134       goto open_finished;
29135     }
29136   }
29137
29138 #ifdef FD_CLOEXEC
29139   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29140 #endif
29141
29142   noLock = eType!=SQLITE_OPEN_MAIN_DB;
29143
29144   
29145 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29146   struct statfs fsInfo;
29147   if( fstatfs(fd, &fsInfo) == -1 ){
29148     ((unixFile*)pFile)->lastErrno = errno;
29149     if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
29150     robust_close(p, fd, __LINE__);
29151     return SQLITE_IOERR_ACCESS;
29152   }
29153   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29154     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29155   }
29156 #endif
29157   
29158 #if SQLITE_ENABLE_LOCKING_STYLE
29159 #if SQLITE_PREFER_PROXY_LOCKING
29160   isAutoProxy = 1;
29161 #endif
29162   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29163     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29164     int useProxy = 0;
29165
29166     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
29167     ** never use proxy, NULL means use proxy for non-local files only.  */
29168     if( envforce!=NULL ){
29169       useProxy = atoi(envforce)>0;
29170     }else{
29171       struct statfs fsInfo;
29172       if( statfs(zPath, &fsInfo) == -1 ){
29173         /* In theory, the close(fd) call is sub-optimal. If the file opened
29174         ** with fd is a database file, and there are other connections open
29175         ** on that file that are currently holding advisory locks on it,
29176         ** then the call to close() will cancel those locks. In practice,
29177         ** we're assuming that statfs() doesn't fail very often. At least
29178         ** not while other file descriptors opened by the same process on
29179         ** the same file are working.  */
29180         p->lastErrno = errno;
29181         if( dirfd>=0 ){
29182           robust_close(p, dirfd, __LINE__);
29183         }
29184         robust_close(p, fd, __LINE__);
29185         rc = SQLITE_IOERR_ACCESS;
29186         goto open_finished;
29187       }
29188       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29189     }
29190     if( useProxy ){
29191       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29192                           isDelete, isReadonly);
29193       if( rc==SQLITE_OK ){
29194         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29195         if( rc!=SQLITE_OK ){
29196           /* Use unixClose to clean up the resources added in fillInUnixFile 
29197           ** and clear all the structure's references.  Specifically, 
29198           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
29199           */
29200           unixClose(pFile);
29201           return rc;
29202         }
29203       }
29204       goto open_finished;
29205     }
29206   }
29207 #endif
29208   
29209   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29210                       isDelete, isReadonly);
29211 open_finished:
29212   if( rc!=SQLITE_OK ){
29213     sqlite3_free(p->pUnused);
29214   }
29215   return rc;
29216 }
29217
29218
29219 /*
29220 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29221 ** the directory after deleting the file.
29222 */
29223 static int unixDelete(
29224   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29225   const char *zPath,        /* Name of file to be deleted */
29226   int dirSync               /* If true, fsync() directory after deleting file */
29227 ){
29228   int rc = SQLITE_OK;
29229   UNUSED_PARAMETER(NotUsed);
29230   SimulateIOError(return SQLITE_IOERR_DELETE);
29231   if( unlink(zPath)==(-1) && errno!=ENOENT ){
29232     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29233   }
29234 #ifndef SQLITE_DISABLE_DIRSYNC
29235   if( dirSync ){
29236     int fd;
29237     rc = openDirectory(zPath, &fd);
29238     if( rc==SQLITE_OK ){
29239 #if OS_VXWORKS
29240       if( fsync(fd)==-1 )
29241 #else
29242       if( fsync(fd) )
29243 #endif
29244       {
29245         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29246       }
29247       robust_close(0, fd, __LINE__);
29248     }
29249   }
29250 #endif
29251   return rc;
29252 }
29253
29254 /*
29255 ** Test the existance of or access permissions of file zPath. The
29256 ** test performed depends on the value of flags:
29257 **
29258 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29259 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29260 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29261 **
29262 ** Otherwise return 0.
29263 */
29264 static int unixAccess(
29265   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29266   const char *zPath,      /* Path of the file to examine */
29267   int flags,              /* What do we want to learn about the zPath file? */
29268   int *pResOut            /* Write result boolean here */
29269 ){
29270   int amode = 0;
29271   UNUSED_PARAMETER(NotUsed);
29272   SimulateIOError( return SQLITE_IOERR_ACCESS; );
29273   switch( flags ){
29274     case SQLITE_ACCESS_EXISTS:
29275       amode = F_OK;
29276       break;
29277     case SQLITE_ACCESS_READWRITE:
29278       amode = W_OK|R_OK;
29279       break;
29280     case SQLITE_ACCESS_READ:
29281       amode = R_OK;
29282       break;
29283
29284     default:
29285       assert(!"Invalid flags argument");
29286   }
29287   *pResOut = (osAccess(zPath, amode)==0);
29288   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29289     struct stat buf;
29290     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
29291       *pResOut = 0;
29292     }
29293   }
29294   return SQLITE_OK;
29295 }
29296
29297
29298 /*
29299 ** Turn a relative pathname into a full pathname. The relative path
29300 ** is stored as a nul-terminated string in the buffer pointed to by
29301 ** zPath. 
29302 **
29303 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
29304 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29305 ** this buffer before returning.
29306 */
29307 static int unixFullPathname(
29308   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29309   const char *zPath,            /* Possibly relative input path */
29310   int nOut,                     /* Size of output buffer in bytes */
29311   char *zOut                    /* Output buffer */
29312 ){
29313
29314   /* It's odd to simulate an io-error here, but really this is just
29315   ** using the io-error infrastructure to test that SQLite handles this
29316   ** function failing. This function could fail if, for example, the
29317   ** current working directory has been unlinked.
29318   */
29319   SimulateIOError( return SQLITE_ERROR );
29320
29321   assert( pVfs->mxPathname==MAX_PATHNAME );
29322   UNUSED_PARAMETER(pVfs);
29323
29324   zOut[nOut-1] = '\0';
29325   if( zPath[0]=='/' ){
29326     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29327   }else{
29328     int nCwd;
29329     if( osGetcwd(zOut, nOut-1)==0 ){
29330       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29331     }
29332     nCwd = (int)strlen(zOut);
29333     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29334   }
29335   return SQLITE_OK;
29336 }
29337
29338
29339 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29340 /*
29341 ** Interfaces for opening a shared library, finding entry points
29342 ** within the shared library, and closing the shared library.
29343 */
29344 #include <dlfcn.h>
29345 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29346   UNUSED_PARAMETER(NotUsed);
29347   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29348 }
29349
29350 /*
29351 ** SQLite calls this function immediately after a call to unixDlSym() or
29352 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29353 ** message is available, it is written to zBufOut. If no error message
29354 ** is available, zBufOut is left unmodified and SQLite uses a default
29355 ** error message.
29356 */
29357 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29358   const char *zErr;
29359   UNUSED_PARAMETER(NotUsed);
29360   unixEnterMutex();
29361   zErr = dlerror();
29362   if( zErr ){
29363     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29364   }
29365   unixLeaveMutex();
29366 }
29367 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29368   /* 
29369   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29370   ** cast into a pointer to a function.  And yet the library dlsym() routine
29371   ** returns a void* which is really a pointer to a function.  So how do we
29372   ** use dlsym() with -pedantic-errors?
29373   **
29374   ** Variable x below is defined to be a pointer to a function taking
29375   ** parameters void* and const char* and returning a pointer to a function.
29376   ** We initialize x by assigning it a pointer to the dlsym() function.
29377   ** (That assignment requires a cast.)  Then we call the function that
29378   ** x points to.  
29379   **
29380   ** This work-around is unlikely to work correctly on any system where
29381   ** you really cannot cast a function pointer into void*.  But then, on the
29382   ** other hand, dlsym() will not work on such a system either, so we have
29383   ** not really lost anything.
29384   */
29385   void (*(*x)(void*,const char*))(void);
29386   UNUSED_PARAMETER(NotUsed);
29387   x = (void(*(*)(void*,const char*))(void))dlsym;
29388   return (*x)(p, zSym);
29389 }
29390 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29391   UNUSED_PARAMETER(NotUsed);
29392   dlclose(pHandle);
29393 }
29394 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29395   #define unixDlOpen  0
29396   #define unixDlError 0
29397   #define unixDlSym   0
29398   #define unixDlClose 0
29399 #endif
29400
29401 /*
29402 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29403 */
29404 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29405   UNUSED_PARAMETER(NotUsed);
29406   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29407
29408   /* We have to initialize zBuf to prevent valgrind from reporting
29409   ** errors.  The reports issued by valgrind are incorrect - we would
29410   ** prefer that the randomness be increased by making use of the
29411   ** uninitialized space in zBuf - but valgrind errors tend to worry
29412   ** some users.  Rather than argue, it seems easier just to initialize
29413   ** the whole array and silence valgrind, even if that means less randomness
29414   ** in the random seed.
29415   **
29416   ** When testing, initializing zBuf[] to zero is all we do.  That means
29417   ** that we always use the same random number sequence.  This makes the
29418   ** tests repeatable.
29419   */
29420   memset(zBuf, 0, nBuf);
29421 #if !defined(SQLITE_TEST)
29422   {
29423     int pid, fd;
29424     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29425     if( fd<0 ){
29426       time_t t;
29427       time(&t);
29428       memcpy(zBuf, &t, sizeof(t));
29429       pid = getpid();
29430       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29431       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29432       nBuf = sizeof(t) + sizeof(pid);
29433     }else{
29434       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29435       robust_close(0, fd, __LINE__);
29436     }
29437   }
29438 #endif
29439   return nBuf;
29440 }
29441
29442
29443 /*
29444 ** Sleep for a little while.  Return the amount of time slept.
29445 ** The argument is the number of microseconds we want to sleep.
29446 ** The return value is the number of microseconds of sleep actually
29447 ** requested from the underlying operating system, a number which
29448 ** might be greater than or equal to the argument, but not less
29449 ** than the argument.
29450 */
29451 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29452 #if OS_VXWORKS
29453   struct timespec sp;
29454
29455   sp.tv_sec = microseconds / 1000000;
29456   sp.tv_nsec = (microseconds % 1000000) * 1000;
29457   nanosleep(&sp, NULL);
29458   UNUSED_PARAMETER(NotUsed);
29459   return microseconds;
29460 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29461   usleep(microseconds);
29462   UNUSED_PARAMETER(NotUsed);
29463   return microseconds;
29464 #else
29465   int seconds = (microseconds+999999)/1000000;
29466   sleep(seconds);
29467   UNUSED_PARAMETER(NotUsed);
29468   return seconds*1000000;
29469 #endif
29470 }
29471
29472 /*
29473 ** The following variable, if set to a non-zero value, is interpreted as
29474 ** the number of seconds since 1970 and is used to set the result of
29475 ** sqlite3OsCurrentTime() during testing.
29476 */
29477 #ifdef SQLITE_TEST
29478 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29479 #endif
29480
29481 /*
29482 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29483 ** the current time and date as a Julian Day number times 86_400_000.  In
29484 ** other words, write into *piNow the number of milliseconds since the Julian
29485 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29486 ** proleptic Gregorian calendar.
29487 **
29488 ** On success, return 0.  Return 1 if the time and date cannot be found.
29489 */
29490 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29491   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29492 #if defined(NO_GETTOD)
29493   time_t t;
29494   time(&t);
29495   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29496 #elif OS_VXWORKS
29497   struct timespec sNow;
29498   clock_gettime(CLOCK_REALTIME, &sNow);
29499   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29500 #else
29501   struct timeval sNow;
29502   gettimeofday(&sNow, 0);
29503   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29504 #endif
29505
29506 #ifdef SQLITE_TEST
29507   if( sqlite3_current_time ){
29508     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29509   }
29510 #endif
29511   UNUSED_PARAMETER(NotUsed);
29512   return 0;
29513 }
29514
29515 /*
29516 ** Find the current time (in Universal Coordinated Time).  Write the
29517 ** current time and date as a Julian Day number into *prNow and
29518 ** return 0.  Return 1 if the time and date cannot be found.
29519 */
29520 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29521   sqlite3_int64 i;
29522   UNUSED_PARAMETER(NotUsed);
29523   unixCurrentTimeInt64(0, &i);
29524   *prNow = i/86400000.0;
29525   return 0;
29526 }
29527
29528 /*
29529 ** We added the xGetLastError() method with the intention of providing
29530 ** better low-level error messages when operating-system problems come up
29531 ** during SQLite operation.  But so far, none of that has been implemented
29532 ** in the core.  So this routine is never called.  For now, it is merely
29533 ** a place-holder.
29534 */
29535 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29536   UNUSED_PARAMETER(NotUsed);
29537   UNUSED_PARAMETER(NotUsed2);
29538   UNUSED_PARAMETER(NotUsed3);
29539   return 0;
29540 }
29541
29542
29543 /*
29544 ************************ End of sqlite3_vfs methods ***************************
29545 ******************************************************************************/
29546
29547 /******************************************************************************
29548 ************************** Begin Proxy Locking ********************************
29549 **
29550 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29551 ** other locking methods on secondary lock files.  Proxy locking is a
29552 ** meta-layer over top of the primitive locking implemented above.  For
29553 ** this reason, the division that implements of proxy locking is deferred
29554 ** until late in the file (here) after all of the other I/O methods have
29555 ** been defined - so that the primitive locking methods are available
29556 ** as services to help with the implementation of proxy locking.
29557 **
29558 ****
29559 **
29560 ** The default locking schemes in SQLite use byte-range locks on the
29561 ** database file to coordinate safe, concurrent access by multiple readers
29562 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29563 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29564 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29565 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29566 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29567 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29568 ** address in the shared range is taken for a SHARED lock, the entire
29569 ** shared range is taken for an EXCLUSIVE lock):
29570 **
29571 **      PENDING_BYTE        0x40000000                  
29572 **      RESERVED_BYTE       0x40000001
29573 **      SHARED_RANGE        0x40000002 -> 0x40000200
29574 **
29575 ** This works well on the local file system, but shows a nearly 100x
29576 ** slowdown in read performance on AFP because the AFP client disables
29577 ** the read cache when byte-range locks are present.  Enabling the read
29578 ** cache exposes a cache coherency problem that is present on all OS X
29579 ** supported network file systems.  NFS and AFP both observe the
29580 ** close-to-open semantics for ensuring cache coherency
29581 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29582 ** address the requirements for concurrent database access by multiple
29583 ** readers and writers
29584 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29585 **
29586 ** To address the performance and cache coherency issues, proxy file locking
29587 ** changes the way database access is controlled by limiting access to a
29588 ** single host at a time and moving file locks off of the database file
29589 ** and onto a proxy file on the local file system.  
29590 **
29591 **
29592 ** Using proxy locks
29593 ** -----------------
29594 **
29595 ** C APIs
29596 **
29597 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29598 **                       <proxy_path> | ":auto:");
29599 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29600 **
29601 **
29602 ** SQL pragmas
29603 **
29604 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29605 **  PRAGMA [database.]lock_proxy_file
29606 **
29607 ** Specifying ":auto:" means that if there is a conch file with a matching
29608 ** host ID in it, the proxy path in the conch file will be used, otherwise
29609 ** a proxy path based on the user's temp dir
29610 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29611 ** actual proxy file name is generated from the name and path of the
29612 ** database file.  For example:
29613 **
29614 **       For database path "/Users/me/foo.db" 
29615 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29616 **
29617 ** Once a lock proxy is configured for a database connection, it can not
29618 ** be removed, however it may be switched to a different proxy path via
29619 ** the above APIs (assuming the conch file is not being held by another
29620 ** connection or process). 
29621 **
29622 **
29623 ** How proxy locking works
29624 ** -----------------------
29625 **
29626 ** Proxy file locking relies primarily on two new supporting files: 
29627 **
29628 **   *  conch file to limit access to the database file to a single host
29629 **      at a time
29630 **
29631 **   *  proxy file to act as a proxy for the advisory locks normally
29632 **      taken on the database
29633 **
29634 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29635 ** by taking an sqlite-style shared lock on the conch file, reading the
29636 ** contents and comparing the host's unique host ID (see below) and lock
29637 ** proxy path against the values stored in the conch.  The conch file is
29638 ** stored in the same directory as the database file and the file name
29639 ** is patterned after the database file name as ".<databasename>-conch".
29640 ** If the conch file does not exist, or it's contents do not match the
29641 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29642 ** lock and the conch file contents is updated with the host ID and proxy
29643 ** path and the lock is downgraded to a shared lock again.  If the conch
29644 ** is held by another process (with a shared lock), the exclusive lock
29645 ** will fail and SQLITE_BUSY is returned.
29646 **
29647 ** The proxy file - a single-byte file used for all advisory file locks
29648 ** normally taken on the database file.   This allows for safe sharing
29649 ** of the database file for multiple readers and writers on the same
29650 ** host (the conch ensures that they all use the same local lock file).
29651 **
29652 ** Requesting the lock proxy does not immediately take the conch, it is
29653 ** only taken when the first request to lock database file is made.  
29654 ** This matches the semantics of the traditional locking behavior, where
29655 ** opening a connection to a database file does not take a lock on it.
29656 ** The shared lock and an open file descriptor are maintained until 
29657 ** the connection to the database is closed. 
29658 **
29659 ** The proxy file and the lock file are never deleted so they only need
29660 ** to be created the first time they are used.
29661 **
29662 ** Configuration options
29663 ** ---------------------
29664 **
29665 **  SQLITE_PREFER_PROXY_LOCKING
29666 **
29667 **       Database files accessed on non-local file systems are
29668 **       automatically configured for proxy locking, lock files are
29669 **       named automatically using the same logic as
29670 **       PRAGMA lock_proxy_file=":auto:"
29671 **    
29672 **  SQLITE_PROXY_DEBUG
29673 **
29674 **       Enables the logging of error messages during host id file
29675 **       retrieval and creation
29676 **
29677 **  LOCKPROXYDIR
29678 **
29679 **       Overrides the default directory used for lock proxy files that
29680 **       are named automatically via the ":auto:" setting
29681 **
29682 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29683 **
29684 **       Permissions to use when creating a directory for storing the
29685 **       lock proxy files, only used when LOCKPROXYDIR is not set.
29686 **    
29687 **    
29688 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29689 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29690 ** force proxy locking to be used for every database file opened, and 0
29691 ** will force automatic proxy locking to be disabled for all database
29692 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29693 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29694 */
29695
29696 /*
29697 ** Proxy locking is only available on MacOSX 
29698 */
29699 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29700
29701 /*
29702 ** The proxyLockingContext has the path and file structures for the remote 
29703 ** and local proxy files in it
29704 */
29705 typedef struct proxyLockingContext proxyLockingContext;
29706 struct proxyLockingContext {
29707   unixFile *conchFile;         /* Open conch file */
29708   char *conchFilePath;         /* Name of the conch file */
29709   unixFile *lockProxy;         /* Open proxy lock file */
29710   char *lockProxyPath;         /* Name of the proxy lock file */
29711   char *dbPath;                /* Name of the open file */
29712   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29713   void *oldLockingContext;     /* Original lockingcontext to restore on close */
29714   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29715 };
29716
29717 /* 
29718 ** The proxy lock file path for the database at dbPath is written into lPath, 
29719 ** which must point to valid, writable memory large enough for a maxLen length
29720 ** file path. 
29721 */
29722 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29723   int len;
29724   int dbLen;
29725   int i;
29726
29727 #ifdef LOCKPROXYDIR
29728   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29729 #else
29730 # ifdef _CS_DARWIN_USER_TEMP_DIR
29731   {
29732     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29733       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29734                lPath, errno, getpid()));
29735       return SQLITE_IOERR_LOCK;
29736     }
29737     len = strlcat(lPath, "sqliteplocks", maxLen);    
29738   }
29739 # else
29740   len = strlcpy(lPath, "/tmp/", maxLen);
29741 # endif
29742 #endif
29743
29744   if( lPath[len-1]!='/' ){
29745     len = strlcat(lPath, "/", maxLen);
29746   }
29747   
29748   /* transform the db path to a unique cache name */
29749   dbLen = (int)strlen(dbPath);
29750   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29751     char c = dbPath[i];
29752     lPath[i+len] = (c=='/')?'_':c;
29753   }
29754   lPath[i+len]='\0';
29755   strlcat(lPath, ":auto:", maxLen);
29756   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29757   return SQLITE_OK;
29758 }
29759
29760 /* 
29761  ** Creates the lock file and any missing directories in lockPath
29762  */
29763 static int proxyCreateLockPath(const char *lockPath){
29764   int i, len;
29765   char buf[MAXPATHLEN];
29766   int start = 0;
29767   
29768   assert(lockPath!=NULL);
29769   /* try to create all the intermediate directories */
29770   len = (int)strlen(lockPath);
29771   buf[0] = lockPath[0];
29772   for( i=1; i<len; i++ ){
29773     if( lockPath[i] == '/' && (i - start > 0) ){
29774       /* only mkdir if leaf dir != "." or "/" or ".." */
29775       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
29776          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29777         buf[i]='\0';
29778         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29779           int err=errno;
29780           if( err!=EEXIST ) {
29781             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29782                      "'%s' proxy lock path=%s pid=%d\n",
29783                      buf, strerror(err), lockPath, getpid()));
29784             return err;
29785           }
29786         }
29787       }
29788       start=i+1;
29789     }
29790     buf[i] = lockPath[i];
29791   }
29792   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29793   return 0;
29794 }
29795
29796 /*
29797 ** Create a new VFS file descriptor (stored in memory obtained from
29798 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29799 **
29800 ** The caller is responsible not only for closing the file descriptor
29801 ** but also for freeing the memory associated with the file descriptor.
29802 */
29803 static int proxyCreateUnixFile(
29804     const char *path,        /* path for the new unixFile */
29805     unixFile **ppFile,       /* unixFile created and returned by ref */
29806     int islockfile           /* if non zero missing dirs will be created */
29807 ) {
29808   int fd = -1;
29809   int dirfd = -1;
29810   unixFile *pNew;
29811   int rc = SQLITE_OK;
29812   int openFlags = O_RDWR | O_CREAT;
29813   sqlite3_vfs dummyVfs;
29814   int terrno = 0;
29815   UnixUnusedFd *pUnused = NULL;
29816
29817   /* 1. first try to open/create the file
29818   ** 2. if that fails, and this is a lock file (not-conch), try creating
29819   ** the parent directories and then try again.
29820   ** 3. if that fails, try to open the file read-only
29821   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29822   */
29823   pUnused = findReusableFd(path, openFlags);
29824   if( pUnused ){
29825     fd = pUnused->fd;
29826   }else{
29827     pUnused = sqlite3_malloc(sizeof(*pUnused));
29828     if( !pUnused ){
29829       return SQLITE_NOMEM;
29830     }
29831   }
29832   if( fd<0 ){
29833     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29834     terrno = errno;
29835     if( fd<0 && errno==ENOENT && islockfile ){
29836       if( proxyCreateLockPath(path) == SQLITE_OK ){
29837         fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29838       }
29839     }
29840   }
29841   if( fd<0 ){
29842     openFlags = O_RDONLY;
29843     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29844     terrno = errno;
29845   }
29846   if( fd<0 ){
29847     if( islockfile ){
29848       return SQLITE_BUSY;
29849     }
29850     switch (terrno) {
29851       case EACCES:
29852         return SQLITE_PERM;
29853       case EIO: 
29854         return SQLITE_IOERR_LOCK; /* even though it is the conch */
29855       default:
29856         return SQLITE_CANTOPEN_BKPT;
29857     }
29858   }
29859   
29860   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29861   if( pNew==NULL ){
29862     rc = SQLITE_NOMEM;
29863     goto end_create_proxy;
29864   }
29865   memset(pNew, 0, sizeof(unixFile));
29866   pNew->openFlags = openFlags;
29867   memset(&dummyVfs, 0, sizeof(dummyVfs));
29868   dummyVfs.pAppData = (void*)&autolockIoFinder;
29869   dummyVfs.zName = "dummy";
29870   pUnused->fd = fd;
29871   pUnused->flags = openFlags;
29872   pNew->pUnused = pUnused;
29873   
29874   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
29875   if( rc==SQLITE_OK ){
29876     *ppFile = pNew;
29877     return SQLITE_OK;
29878   }
29879 end_create_proxy:    
29880   robust_close(pNew, fd, __LINE__);
29881   sqlite3_free(pNew);
29882   sqlite3_free(pUnused);
29883   return rc;
29884 }
29885
29886 #ifdef SQLITE_TEST
29887 /* simulate multiple hosts by creating unique hostid file paths */
29888 SQLITE_API int sqlite3_hostid_num = 0;
29889 #endif
29890
29891 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29892
29893 /* Not always defined in the headers as it ought to be */
29894 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29895
29896 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
29897 ** bytes of writable memory.
29898 */
29899 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29900   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29901   memset(pHostID, 0, PROXY_HOSTIDLEN);
29902 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29903                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29904   {
29905     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29906     if( gethostuuid(pHostID, &timeout) ){
29907       int err = errno;
29908       if( pError ){
29909         *pError = err;
29910       }
29911       return SQLITE_IOERR;
29912     }
29913   }
29914 #endif
29915 #ifdef SQLITE_TEST
29916   /* simulate multiple hosts by creating unique hostid file paths */
29917   if( sqlite3_hostid_num != 0){
29918     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29919   }
29920 #endif
29921   
29922   return SQLITE_OK;
29923 }
29924
29925 /* The conch file contains the header, host id and lock file path
29926  */
29927 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29928 #define PROXY_HEADERLEN    1   /* conch file header length */
29929 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29930 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29931
29932 /* 
29933 ** Takes an open conch file, copies the contents to a new path and then moves 
29934 ** it back.  The newly created file's file descriptor is assigned to the
29935 ** conch file structure and finally the original conch file descriptor is 
29936 ** closed.  Returns zero if successful.
29937 */
29938 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29939   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29940   unixFile *conchFile = pCtx->conchFile;
29941   char tPath[MAXPATHLEN];
29942   char buf[PROXY_MAXCONCHLEN];
29943   char *cPath = pCtx->conchFilePath;
29944   size_t readLen = 0;
29945   size_t pathLen = 0;
29946   char errmsg[64] = "";
29947   int fd = -1;
29948   int rc = -1;
29949   UNUSED_PARAMETER(myHostID);
29950
29951   /* create a new path by replace the trailing '-conch' with '-break' */
29952   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29953   if( pathLen>MAXPATHLEN || pathLen<6 || 
29954      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29955     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29956     goto end_breaklock;
29957   }
29958   /* read the conch content */
29959   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29960   if( readLen<PROXY_PATHINDEX ){
29961     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29962     goto end_breaklock;
29963   }
29964   /* write it out to the temporary break file */
29965   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
29966                    SQLITE_DEFAULT_FILE_PERMISSIONS);
29967   if( fd<0 ){
29968     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29969     goto end_breaklock;
29970   }
29971   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29972     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29973     goto end_breaklock;
29974   }
29975   if( rename(tPath, cPath) ){
29976     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29977     goto end_breaklock;
29978   }
29979   rc = 0;
29980   fprintf(stderr, "broke stale lock on %s\n", cPath);
29981   robust_close(pFile, conchFile->h, __LINE__);
29982   conchFile->h = fd;
29983   conchFile->openFlags = O_RDWR | O_CREAT;
29984
29985 end_breaklock:
29986   if( rc ){
29987     if( fd>=0 ){
29988       unlink(tPath);
29989       robust_close(pFile, fd, __LINE__);
29990     }
29991     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29992   }
29993   return rc;
29994 }
29995
29996 /* Take the requested lock on the conch file and break a stale lock if the 
29997 ** host id matches.
29998 */
29999 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30000   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30001   unixFile *conchFile = pCtx->conchFile;
30002   int rc = SQLITE_OK;
30003   int nTries = 0;
30004   struct timespec conchModTime;
30005   
30006   do {
30007     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30008     nTries ++;
30009     if( rc==SQLITE_BUSY ){
30010       /* If the lock failed (busy):
30011        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
30012        * 2nd try: fail if the mod time changed or host id is different, wait 
30013        *           10 sec and try again
30014        * 3rd try: break the lock unless the mod time has changed.
30015        */
30016       struct stat buf;
30017       if( osFstat(conchFile->h, &buf) ){
30018         pFile->lastErrno = errno;
30019         return SQLITE_IOERR_LOCK;
30020       }
30021       
30022       if( nTries==1 ){
30023         conchModTime = buf.st_mtimespec;
30024         usleep(500000); /* wait 0.5 sec and try the lock again*/
30025         continue;  
30026       }
30027
30028       assert( nTries>1 );
30029       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
30030          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30031         return SQLITE_BUSY;
30032       }
30033       
30034       if( nTries==2 ){  
30035         char tBuf[PROXY_MAXCONCHLEN];
30036         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30037         if( len<0 ){
30038           pFile->lastErrno = errno;
30039           return SQLITE_IOERR_LOCK;
30040         }
30041         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30042           /* don't break the lock if the host id doesn't match */
30043           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30044             return SQLITE_BUSY;
30045           }
30046         }else{
30047           /* don't break the lock on short read or a version mismatch */
30048           return SQLITE_BUSY;
30049         }
30050         usleep(10000000); /* wait 10 sec and try the lock again */
30051         continue; 
30052       }
30053       
30054       assert( nTries==3 );
30055       if( 0==proxyBreakConchLock(pFile, myHostID) ){
30056         rc = SQLITE_OK;
30057         if( lockType==EXCLUSIVE_LOCK ){
30058           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
30059         }
30060         if( !rc ){
30061           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30062         }
30063       }
30064     }
30065   } while( rc==SQLITE_BUSY && nTries<3 );
30066   
30067   return rc;
30068 }
30069
30070 /* Takes the conch by taking a shared lock and read the contents conch, if 
30071 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
30072 ** lockPath means that the lockPath in the conch file will be used if the 
30073 ** host IDs match, or a new lock path will be generated automatically 
30074 ** and written to the conch file.
30075 */
30076 static int proxyTakeConch(unixFile *pFile){
30077   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30078   
30079   if( pCtx->conchHeld!=0 ){
30080     return SQLITE_OK;
30081   }else{
30082     unixFile *conchFile = pCtx->conchFile;
30083     uuid_t myHostID;
30084     int pError = 0;
30085     char readBuf[PROXY_MAXCONCHLEN];
30086     char lockPath[MAXPATHLEN];
30087     char *tempLockPath = NULL;
30088     int rc = SQLITE_OK;
30089     int createConch = 0;
30090     int hostIdMatch = 0;
30091     int readLen = 0;
30092     int tryOldLockPath = 0;
30093     int forceNewLockPath = 0;
30094     
30095     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30096              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30097
30098     rc = proxyGetHostID(myHostID, &pError);
30099     if( (rc&0xff)==SQLITE_IOERR ){
30100       pFile->lastErrno = pError;
30101       goto end_takeconch;
30102     }
30103     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30104     if( rc!=SQLITE_OK ){
30105       goto end_takeconch;
30106     }
30107     /* read the existing conch file */
30108     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30109     if( readLen<0 ){
30110       /* I/O error: lastErrno set by seekAndRead */
30111       pFile->lastErrno = conchFile->lastErrno;
30112       rc = SQLITE_IOERR_READ;
30113       goto end_takeconch;
30114     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
30115              readBuf[0]!=(char)PROXY_CONCHVERSION ){
30116       /* a short read or version format mismatch means we need to create a new 
30117       ** conch file. 
30118       */
30119       createConch = 1;
30120     }
30121     /* if the host id matches and the lock path already exists in the conch
30122     ** we'll try to use the path there, if we can't open that path, we'll 
30123     ** retry with a new auto-generated path 
30124     */
30125     do { /* in case we need to try again for an :auto: named lock file */
30126
30127       if( !createConch && !forceNewLockPath ){
30128         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
30129                                   PROXY_HOSTIDLEN);
30130         /* if the conch has data compare the contents */
30131         if( !pCtx->lockProxyPath ){
30132           /* for auto-named local lock file, just check the host ID and we'll
30133            ** use the local lock file path that's already in there
30134            */
30135           if( hostIdMatch ){
30136             size_t pathLen = (readLen - PROXY_PATHINDEX);
30137             
30138             if( pathLen>=MAXPATHLEN ){
30139               pathLen=MAXPATHLEN-1;
30140             }
30141             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30142             lockPath[pathLen] = 0;
30143             tempLockPath = lockPath;
30144             tryOldLockPath = 1;
30145             /* create a copy of the lock path if the conch is taken */
30146             goto end_takeconch;
30147           }
30148         }else if( hostIdMatch
30149                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30150                            readLen-PROXY_PATHINDEX)
30151         ){
30152           /* conch host and lock path match */
30153           goto end_takeconch; 
30154         }
30155       }
30156       
30157       /* if the conch isn't writable and doesn't match, we can't take it */
30158       if( (conchFile->openFlags&O_RDWR) == 0 ){
30159         rc = SQLITE_BUSY;
30160         goto end_takeconch;
30161       }
30162       
30163       /* either the conch didn't match or we need to create a new one */
30164       if( !pCtx->lockProxyPath ){
30165         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30166         tempLockPath = lockPath;
30167         /* create a copy of the lock path _only_ if the conch is taken */
30168       }
30169       
30170       /* update conch with host and path (this will fail if other process
30171       ** has a shared lock already), if the host id matches, use the big
30172       ** stick.
30173       */
30174       futimes(conchFile->h, NULL);
30175       if( hostIdMatch && !createConch ){
30176         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30177           /* We are trying for an exclusive lock but another thread in this
30178            ** same process is still holding a shared lock. */
30179           rc = SQLITE_BUSY;
30180         } else {          
30181           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30182         }
30183       }else{
30184         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30185       }
30186       if( rc==SQLITE_OK ){
30187         char writeBuffer[PROXY_MAXCONCHLEN];
30188         int writeSize = 0;
30189         
30190         writeBuffer[0] = (char)PROXY_CONCHVERSION;
30191         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30192         if( pCtx->lockProxyPath!=NULL ){
30193           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30194         }else{
30195           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30196         }
30197         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30198         robust_ftruncate(conchFile->h, writeSize);
30199         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30200         fsync(conchFile->h);
30201         /* If we created a new conch file (not just updated the contents of a 
30202          ** valid conch file), try to match the permissions of the database 
30203          */
30204         if( rc==SQLITE_OK && createConch ){
30205           struct stat buf;
30206           int err = osFstat(pFile->h, &buf);
30207           if( err==0 ){
30208             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30209                                         S_IROTH|S_IWOTH);
30210             /* try to match the database file R/W permissions, ignore failure */
30211 #ifndef SQLITE_PROXY_DEBUG
30212             osFchmod(conchFile->h, cmode);
30213 #else
30214             do{
30215               rc = osFchmod(conchFile->h, cmode);
30216             }while( rc==(-1) && errno==EINTR );
30217             if( rc!=0 ){
30218               int code = errno;
30219               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30220                       cmode, code, strerror(code));
30221             } else {
30222               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30223             }
30224           }else{
30225             int code = errno;
30226             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
30227                     err, code, strerror(code));
30228 #endif
30229           }
30230         }
30231       }
30232       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30233       
30234     end_takeconch:
30235       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30236       if( rc==SQLITE_OK && pFile->openFlags ){
30237         if( pFile->h>=0 ){
30238           robust_close(pFile, pFile->h, __LINE__);
30239         }
30240         pFile->h = -1;
30241         int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30242                       SQLITE_DEFAULT_FILE_PERMISSIONS);
30243         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30244         if( fd>=0 ){
30245           pFile->h = fd;
30246         }else{
30247           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30248            during locking */
30249         }
30250       }
30251       if( rc==SQLITE_OK && !pCtx->lockProxy ){
30252         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30253         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30254         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30255           /* we couldn't create the proxy lock file with the old lock file path
30256            ** so try again via auto-naming 
30257            */
30258           forceNewLockPath = 1;
30259           tryOldLockPath = 0;
30260           continue; /* go back to the do {} while start point, try again */
30261         }
30262       }
30263       if( rc==SQLITE_OK ){
30264         /* Need to make a copy of path if we extracted the value
30265          ** from the conch file or the path was allocated on the stack
30266          */
30267         if( tempLockPath ){
30268           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30269           if( !pCtx->lockProxyPath ){
30270             rc = SQLITE_NOMEM;
30271           }
30272         }
30273       }
30274       if( rc==SQLITE_OK ){
30275         pCtx->conchHeld = 1;
30276         
30277         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30278           afpLockingContext *afpCtx;
30279           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30280           afpCtx->dbPath = pCtx->lockProxyPath;
30281         }
30282       } else {
30283         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30284       }
30285       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30286                rc==SQLITE_OK?"ok":"failed"));
30287       return rc;
30288     } while (1); /* in case we need to retry the :auto: lock file - 
30289                  ** we should never get here except via the 'continue' call. */
30290   }
30291 }
30292
30293 /*
30294 ** If pFile holds a lock on a conch file, then release that lock.
30295 */
30296 static int proxyReleaseConch(unixFile *pFile){
30297   int rc = SQLITE_OK;         /* Subroutine return code */
30298   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30299   unixFile *conchFile;        /* Name of the conch file */
30300
30301   pCtx = (proxyLockingContext *)pFile->lockingContext;
30302   conchFile = pCtx->conchFile;
30303   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30304            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
30305            getpid()));
30306   if( pCtx->conchHeld>0 ){
30307     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30308   }
30309   pCtx->conchHeld = 0;
30310   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30311            (rc==SQLITE_OK ? "ok" : "failed")));
30312   return rc;
30313 }
30314
30315 /*
30316 ** Given the name of a database file, compute the name of its conch file.
30317 ** Store the conch filename in memory obtained from sqlite3_malloc().
30318 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30319 ** or SQLITE_NOMEM if unable to obtain memory.
30320 **
30321 ** The caller is responsible for ensuring that the allocated memory
30322 ** space is eventually freed.
30323 **
30324 ** *pConchPath is set to NULL if a memory allocation error occurs.
30325 */
30326 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30327   int i;                        /* Loop counter */
30328   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30329   char *conchPath;              /* buffer in which to construct conch name */
30330
30331   /* Allocate space for the conch filename and initialize the name to
30332   ** the name of the original database file. */  
30333   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30334   if( conchPath==0 ){
30335     return SQLITE_NOMEM;
30336   }
30337   memcpy(conchPath, dbPath, len+1);
30338   
30339   /* now insert a "." before the last / character */
30340   for( i=(len-1); i>=0; i-- ){
30341     if( conchPath[i]=='/' ){
30342       i++;
30343       break;
30344     }
30345   }
30346   conchPath[i]='.';
30347   while ( i<len ){
30348     conchPath[i+1]=dbPath[i];
30349     i++;
30350   }
30351
30352   /* append the "-conch" suffix to the file */
30353   memcpy(&conchPath[i+1], "-conch", 7);
30354   assert( (int)strlen(conchPath) == len+7 );
30355
30356   return SQLITE_OK;
30357 }
30358
30359
30360 /* Takes a fully configured proxy locking-style unix file and switches
30361 ** the local lock file path 
30362 */
30363 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30364   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30365   char *oldPath = pCtx->lockProxyPath;
30366   int rc = SQLITE_OK;
30367
30368   if( pFile->eFileLock!=NO_LOCK ){
30369     return SQLITE_BUSY;
30370   }  
30371
30372   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30373   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30374     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30375     return SQLITE_OK;
30376   }else{
30377     unixFile *lockProxy = pCtx->lockProxy;
30378     pCtx->lockProxy=NULL;
30379     pCtx->conchHeld = 0;
30380     if( lockProxy!=NULL ){
30381       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30382       if( rc ) return rc;
30383       sqlite3_free(lockProxy);
30384     }
30385     sqlite3_free(oldPath);
30386     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30387   }
30388   
30389   return rc;
30390 }
30391
30392 /*
30393 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30394 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30395 **
30396 ** This routine find the filename associated with pFile and writes it
30397 ** int dbPath.
30398 */
30399 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30400 #if defined(__APPLE__)
30401   if( pFile->pMethod == &afpIoMethods ){
30402     /* afp style keeps a reference to the db path in the filePath field 
30403     ** of the struct */
30404     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30405     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30406   } else
30407 #endif
30408   if( pFile->pMethod == &dotlockIoMethods ){
30409     /* dot lock style uses the locking context to store the dot lock
30410     ** file path */
30411     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30412     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30413   }else{
30414     /* all other styles use the locking context to store the db file path */
30415     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30416     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30417   }
30418   return SQLITE_OK;
30419 }
30420
30421 /*
30422 ** Takes an already filled in unix file and alters it so all file locking 
30423 ** will be performed on the local proxy lock file.  The following fields
30424 ** are preserved in the locking context so that they can be restored and 
30425 ** the unix structure properly cleaned up at close time:
30426 **  ->lockingContext
30427 **  ->pMethod
30428 */
30429 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30430   proxyLockingContext *pCtx;
30431   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30432   char *lockPath=NULL;
30433   int rc = SQLITE_OK;
30434   
30435   if( pFile->eFileLock!=NO_LOCK ){
30436     return SQLITE_BUSY;
30437   }
30438   proxyGetDbPathForUnixFile(pFile, dbPath);
30439   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30440     lockPath=NULL;
30441   }else{
30442     lockPath=(char *)path;
30443   }
30444   
30445   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30446            (lockPath ? lockPath : ":auto:"), getpid()));
30447
30448   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30449   if( pCtx==0 ){
30450     return SQLITE_NOMEM;
30451   }
30452   memset(pCtx, 0, sizeof(*pCtx));
30453
30454   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30455   if( rc==SQLITE_OK ){
30456     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30457     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30458       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30459       ** (c) the file system is read-only, then enable no-locking access.
30460       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30461       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30462       */
30463       struct statfs fsInfo;
30464       struct stat conchInfo;
30465       int goLockless = 0;
30466
30467       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30468         int err = errno;
30469         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30470           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30471         }
30472       }
30473       if( goLockless ){
30474         pCtx->conchHeld = -1; /* read only FS/ lockless */
30475         rc = SQLITE_OK;
30476       }
30477     }
30478   }  
30479   if( rc==SQLITE_OK && lockPath ){
30480     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30481   }
30482
30483   if( rc==SQLITE_OK ){
30484     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30485     if( pCtx->dbPath==NULL ){
30486       rc = SQLITE_NOMEM;
30487     }
30488   }
30489   if( rc==SQLITE_OK ){
30490     /* all memory is allocated, proxys are created and assigned, 
30491     ** switch the locking context and pMethod then return.
30492     */
30493     pCtx->oldLockingContext = pFile->lockingContext;
30494     pFile->lockingContext = pCtx;
30495     pCtx->pOldMethod = pFile->pMethod;
30496     pFile->pMethod = &proxyIoMethods;
30497   }else{
30498     if( pCtx->conchFile ){ 
30499       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30500       sqlite3_free(pCtx->conchFile);
30501     }
30502     sqlite3DbFree(0, pCtx->lockProxyPath);
30503     sqlite3_free(pCtx->conchFilePath); 
30504     sqlite3_free(pCtx);
30505   }
30506   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30507            (rc==SQLITE_OK ? "ok" : "failed")));
30508   return rc;
30509 }
30510
30511
30512 /*
30513 ** This routine handles sqlite3_file_control() calls that are specific
30514 ** to proxy locking.
30515 */
30516 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30517   switch( op ){
30518     case SQLITE_GET_LOCKPROXYFILE: {
30519       unixFile *pFile = (unixFile*)id;
30520       if( pFile->pMethod == &proxyIoMethods ){
30521         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30522         proxyTakeConch(pFile);
30523         if( pCtx->lockProxyPath ){
30524           *(const char **)pArg = pCtx->lockProxyPath;
30525         }else{
30526           *(const char **)pArg = ":auto: (not held)";
30527         }
30528       } else {
30529         *(const char **)pArg = NULL;
30530       }
30531       return SQLITE_OK;
30532     }
30533     case SQLITE_SET_LOCKPROXYFILE: {
30534       unixFile *pFile = (unixFile*)id;
30535       int rc = SQLITE_OK;
30536       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30537       if( pArg==NULL || (const char *)pArg==0 ){
30538         if( isProxyStyle ){
30539           /* turn off proxy locking - not supported */
30540           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30541         }else{
30542           /* turn off proxy locking - already off - NOOP */
30543           rc = SQLITE_OK;
30544         }
30545       }else{
30546         const char *proxyPath = (const char *)pArg;
30547         if( isProxyStyle ){
30548           proxyLockingContext *pCtx = 
30549             (proxyLockingContext*)pFile->lockingContext;
30550           if( !strcmp(pArg, ":auto:") 
30551            || (pCtx->lockProxyPath &&
30552                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30553           ){
30554             rc = SQLITE_OK;
30555           }else{
30556             rc = switchLockProxyPath(pFile, proxyPath);
30557           }
30558         }else{
30559           /* turn on proxy file locking */
30560           rc = proxyTransformUnixFile(pFile, proxyPath);
30561         }
30562       }
30563       return rc;
30564     }
30565     default: {
30566       assert( 0 );  /* The call assures that only valid opcodes are sent */
30567     }
30568   }
30569   /*NOTREACHED*/
30570   return SQLITE_ERROR;
30571 }
30572
30573 /*
30574 ** Within this division (the proxying locking implementation) the procedures
30575 ** above this point are all utilities.  The lock-related methods of the
30576 ** proxy-locking sqlite3_io_method object follow.
30577 */
30578
30579
30580 /*
30581 ** This routine checks if there is a RESERVED lock held on the specified
30582 ** file by this or any other process. If such a lock is held, set *pResOut
30583 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30584 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30585 */
30586 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30587   unixFile *pFile = (unixFile*)id;
30588   int rc = proxyTakeConch(pFile);
30589   if( rc==SQLITE_OK ){
30590     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30591     if( pCtx->conchHeld>0 ){
30592       unixFile *proxy = pCtx->lockProxy;
30593       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30594     }else{ /* conchHeld < 0 is lockless */
30595       pResOut=0;
30596     }
30597   }
30598   return rc;
30599 }
30600
30601 /*
30602 ** Lock the file with the lock specified by parameter eFileLock - one
30603 ** of the following:
30604 **
30605 **     (1) SHARED_LOCK
30606 **     (2) RESERVED_LOCK
30607 **     (3) PENDING_LOCK
30608 **     (4) EXCLUSIVE_LOCK
30609 **
30610 ** Sometimes when requesting one lock state, additional lock states
30611 ** are inserted in between.  The locking might fail on one of the later
30612 ** transitions leaving the lock state different from what it started but
30613 ** still short of its goal.  The following chart shows the allowed
30614 ** transitions and the inserted intermediate states:
30615 **
30616 **    UNLOCKED -> SHARED
30617 **    SHARED -> RESERVED
30618 **    SHARED -> (PENDING) -> EXCLUSIVE
30619 **    RESERVED -> (PENDING) -> EXCLUSIVE
30620 **    PENDING -> EXCLUSIVE
30621 **
30622 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30623 ** routine to lower a locking level.
30624 */
30625 static int proxyLock(sqlite3_file *id, int eFileLock) {
30626   unixFile *pFile = (unixFile*)id;
30627   int rc = proxyTakeConch(pFile);
30628   if( rc==SQLITE_OK ){
30629     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30630     if( pCtx->conchHeld>0 ){
30631       unixFile *proxy = pCtx->lockProxy;
30632       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30633       pFile->eFileLock = proxy->eFileLock;
30634     }else{
30635       /* conchHeld < 0 is lockless */
30636     }
30637   }
30638   return rc;
30639 }
30640
30641
30642 /*
30643 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30644 ** must be either NO_LOCK or SHARED_LOCK.
30645 **
30646 ** If the locking level of the file descriptor is already at or below
30647 ** the requested locking level, this routine is a no-op.
30648 */
30649 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30650   unixFile *pFile = (unixFile*)id;
30651   int rc = proxyTakeConch(pFile);
30652   if( rc==SQLITE_OK ){
30653     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30654     if( pCtx->conchHeld>0 ){
30655       unixFile *proxy = pCtx->lockProxy;
30656       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30657       pFile->eFileLock = proxy->eFileLock;
30658     }else{
30659       /* conchHeld < 0 is lockless */
30660     }
30661   }
30662   return rc;
30663 }
30664
30665 /*
30666 ** Close a file that uses proxy locks.
30667 */
30668 static int proxyClose(sqlite3_file *id) {
30669   if( id ){
30670     unixFile *pFile = (unixFile*)id;
30671     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30672     unixFile *lockProxy = pCtx->lockProxy;
30673     unixFile *conchFile = pCtx->conchFile;
30674     int rc = SQLITE_OK;
30675     
30676     if( lockProxy ){
30677       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30678       if( rc ) return rc;
30679       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30680       if( rc ) return rc;
30681       sqlite3_free(lockProxy);
30682       pCtx->lockProxy = 0;
30683     }
30684     if( conchFile ){
30685       if( pCtx->conchHeld ){
30686         rc = proxyReleaseConch(pFile);
30687         if( rc ) return rc;
30688       }
30689       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30690       if( rc ) return rc;
30691       sqlite3_free(conchFile);
30692     }
30693     sqlite3DbFree(0, pCtx->lockProxyPath);
30694     sqlite3_free(pCtx->conchFilePath);
30695     sqlite3DbFree(0, pCtx->dbPath);
30696     /* restore the original locking context and pMethod then close it */
30697     pFile->lockingContext = pCtx->oldLockingContext;
30698     pFile->pMethod = pCtx->pOldMethod;
30699     sqlite3_free(pCtx);
30700     return pFile->pMethod->xClose(id);
30701   }
30702   return SQLITE_OK;
30703 }
30704
30705
30706
30707 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30708 /*
30709 ** The proxy locking style is intended for use with AFP filesystems.
30710 ** And since AFP is only supported on MacOSX, the proxy locking is also
30711 ** restricted to MacOSX.
30712 ** 
30713 **
30714 ******************* End of the proxy lock implementation **********************
30715 ******************************************************************************/
30716
30717 /*
30718 ** Initialize the operating system interface.
30719 **
30720 ** This routine registers all VFS implementations for unix-like operating
30721 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
30722 ** should be the only routines in this file that are visible from other
30723 ** files.
30724 **
30725 ** This routine is called once during SQLite initialization and by a
30726 ** single thread.  The memory allocation and mutex subsystems have not
30727 ** necessarily been initialized when this routine is called, and so they
30728 ** should not be used.
30729 */
30730 SQLITE_API int sqlite3_os_init(void){ 
30731   /* 
30732   ** The following macro defines an initializer for an sqlite3_vfs object.
30733   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30734   ** to the "finder" function.  (pAppData is a pointer to a pointer because
30735   ** silly C90 rules prohibit a void* from being cast to a function pointer
30736   ** and so we have to go through the intermediate pointer to avoid problems
30737   ** when compiling with -pedantic-errors on GCC.)
30738   **
30739   ** The FINDER parameter to this macro is the name of the pointer to the
30740   ** finder-function.  The finder-function returns a pointer to the
30741   ** sqlite_io_methods object that implements the desired locking
30742   ** behaviors.  See the division above that contains the IOMETHODS
30743   ** macro for addition information on finder-functions.
30744   **
30745   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30746   ** object.  But the "autolockIoFinder" available on MacOSX does a little
30747   ** more than that; it looks at the filesystem type that hosts the 
30748   ** database file and tries to choose an locking method appropriate for
30749   ** that filesystem time.
30750   */
30751   #define UNIXVFS(VFSNAME, FINDER) {                        \
30752     3,                    /* iVersion */                    \
30753     sizeof(unixFile),     /* szOsFile */                    \
30754     MAX_PATHNAME,         /* mxPathname */                  \
30755     0,                    /* pNext */                       \
30756     VFSNAME,              /* zName */                       \
30757     (void*)&FINDER,       /* pAppData */                    \
30758     unixOpen,             /* xOpen */                       \
30759     unixDelete,           /* xDelete */                     \
30760     unixAccess,           /* xAccess */                     \
30761     unixFullPathname,     /* xFullPathname */               \
30762     unixDlOpen,           /* xDlOpen */                     \
30763     unixDlError,          /* xDlError */                    \
30764     unixDlSym,            /* xDlSym */                      \
30765     unixDlClose,          /* xDlClose */                    \
30766     unixRandomness,       /* xRandomness */                 \
30767     unixSleep,            /* xSleep */                      \
30768     unixCurrentTime,      /* xCurrentTime */                \
30769     unixGetLastError,     /* xGetLastError */               \
30770     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30771     unixSetSystemCall,    /* xSetSystemCall */              \
30772     unixGetSystemCall,    /* xGetSystemCall */              \
30773     unixNextSystemCall,   /* xNextSystemCall */             \
30774   }
30775
30776   /*
30777   ** All default VFSes for unix are contained in the following array.
30778   **
30779   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30780   ** by the SQLite core when the VFS is registered.  So the following
30781   ** array cannot be const.
30782   */
30783   static sqlite3_vfs aVfs[] = {
30784 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30785     UNIXVFS("unix",          autolockIoFinder ),
30786 #else
30787     UNIXVFS("unix",          posixIoFinder ),
30788 #endif
30789     UNIXVFS("unix-none",     nolockIoFinder ),
30790     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30791     UNIXVFS("unix-excl",     posixIoFinder ),
30792 #if OS_VXWORKS
30793     UNIXVFS("unix-namedsem", semIoFinder ),
30794 #endif
30795 #if SQLITE_ENABLE_LOCKING_STYLE
30796     UNIXVFS("unix-posix",    posixIoFinder ),
30797 #if !OS_VXWORKS
30798     UNIXVFS("unix-flock",    flockIoFinder ),
30799 #endif
30800 #endif
30801 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30802     UNIXVFS("unix-afp",      afpIoFinder ),
30803     UNIXVFS("unix-nfs",      nfsIoFinder ),
30804     UNIXVFS("unix-proxy",    proxyIoFinder ),
30805 #endif
30806   };
30807   unsigned int i;          /* Loop counter */
30808
30809   /* Double-check that the aSyscall[] array has been constructed
30810   ** correctly.  See ticket [bb3a86e890c8e96ab] */
30811   assert( ArraySize(aSyscall)==16 );
30812
30813   /* Register all VFSes defined in the aVfs[] array */
30814   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30815     sqlite3_vfs_register(&aVfs[i], i==0);
30816   }
30817   return SQLITE_OK; 
30818 }
30819
30820 /*
30821 ** Shutdown the operating system interface.
30822 **
30823 ** Some operating systems might need to do some cleanup in this routine,
30824 ** to release dynamically allocated objects.  But not on unix.
30825 ** This routine is a no-op for unix.
30826 */
30827 SQLITE_API int sqlite3_os_end(void){ 
30828   return SQLITE_OK; 
30829 }
30830  
30831 #endif /* SQLITE_OS_UNIX */
30832
30833 /************** End of os_unix.c *********************************************/
30834 /************** Begin file os_win.c ******************************************/
30835 /*
30836 ** 2004 May 22
30837 **
30838 ** The author disclaims copyright to this source code.  In place of
30839 ** a legal notice, here is a blessing:
30840 **
30841 **    May you do good and not evil.
30842 **    May you find forgiveness for yourself and forgive others.
30843 **    May you share freely, never taking more than you give.
30844 **
30845 ******************************************************************************
30846 **
30847 ** This file contains code that is specific to windows.
30848 */
30849 #if SQLITE_OS_WIN               /* This file is used for windows only */
30850
30851
30852 /*
30853 ** A Note About Memory Allocation:
30854 **
30855 ** This driver uses malloc()/free() directly rather than going through
30856 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
30857 ** are designed for use on embedded systems where memory is scarce and
30858 ** malloc failures happen frequently.  Win32 does not typically run on
30859 ** embedded systems, and when it does the developers normally have bigger
30860 ** problems to worry about than running out of memory.  So there is not
30861 ** a compelling need to use the wrappers.
30862 **
30863 ** But there is a good reason to not use the wrappers.  If we use the
30864 ** wrappers then we will get simulated malloc() failures within this
30865 ** driver.  And that causes all kinds of problems for our tests.  We
30866 ** could enhance SQLite to deal with simulated malloc failures within
30867 ** the OS driver, but the code to deal with those failure would not
30868 ** be exercised on Linux (which does not need to malloc() in the driver)
30869 ** and so we would have difficulty writing coverage tests for that
30870 ** code.  Better to leave the code out, we think.
30871 **
30872 ** The point of this discussion is as follows:  When creating a new
30873 ** OS layer for an embedded system, if you use this file as an example,
30874 ** avoid the use of malloc()/free().  Those routines work ok on windows
30875 ** desktops but not so well in embedded systems.
30876 */
30877
30878 #include <winbase.h>
30879
30880 #ifdef __CYGWIN__
30881 # include <sys/cygwin.h>
30882 #endif
30883
30884 /*
30885 ** Macros used to determine whether or not to use threads.
30886 */
30887 #if defined(THREADSAFE) && THREADSAFE
30888 # define SQLITE_W32_THREADS 1
30889 #endif
30890
30891 /*
30892 ** Include code that is common to all os_*.c files
30893 */
30894 /************** Include os_common.h in the middle of os_win.c ****************/
30895 /************** Begin file os_common.h ***************************************/
30896 /*
30897 ** 2004 May 22
30898 **
30899 ** The author disclaims copyright to this source code.  In place of
30900 ** a legal notice, here is a blessing:
30901 **
30902 **    May you do good and not evil.
30903 **    May you find forgiveness for yourself and forgive others.
30904 **    May you share freely, never taking more than you give.
30905 **
30906 ******************************************************************************
30907 **
30908 ** This file contains macros and a little bit of code that is common to
30909 ** all of the platform-specific files (os_*.c) and is #included into those
30910 ** files.
30911 **
30912 ** This file should be #included by the os_*.c files only.  It is not a
30913 ** general purpose header file.
30914 */
30915 #ifndef _OS_COMMON_H_
30916 #define _OS_COMMON_H_
30917
30918 /*
30919 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30920 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30921 ** switch.  The following code should catch this problem at compile-time.
30922 */
30923 #ifdef MEMORY_DEBUG
30924 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30925 #endif
30926
30927 #ifdef SQLITE_DEBUG
30928 SQLITE_PRIVATE int sqlite3OSTrace = 0;
30929 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30930 #else
30931 #define OSTRACE(X)
30932 #endif
30933
30934 /*
30935 ** Macros for performance tracing.  Normally turned off.  Only works
30936 ** on i486 hardware.
30937 */
30938 #ifdef SQLITE_PERFORMANCE_TRACE
30939
30940 /* 
30941 ** hwtime.h contains inline assembler code for implementing 
30942 ** high-performance timing routines.
30943 */
30944 /************** Include hwtime.h in the middle of os_common.h ****************/
30945 /************** Begin file hwtime.h ******************************************/
30946 /*
30947 ** 2008 May 27
30948 **
30949 ** The author disclaims copyright to this source code.  In place of
30950 ** a legal notice, here is a blessing:
30951 **
30952 **    May you do good and not evil.
30953 **    May you find forgiveness for yourself and forgive others.
30954 **    May you share freely, never taking more than you give.
30955 **
30956 ******************************************************************************
30957 **
30958 ** This file contains inline asm code for retrieving "high-performance"
30959 ** counters for x86 class CPUs.
30960 */
30961 #ifndef _HWTIME_H_
30962 #define _HWTIME_H_
30963
30964 /*
30965 ** The following routine only works on pentium-class (or newer) processors.
30966 ** It uses the RDTSC opcode to read the cycle count value out of the
30967 ** processor and returns that value.  This can be used for high-res
30968 ** profiling.
30969 */
30970 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30971       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30972
30973   #if defined(__GNUC__)
30974
30975   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30976      unsigned int lo, hi;
30977      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30978      return (sqlite_uint64)hi << 32 | lo;
30979   }
30980
30981   #elif defined(_MSC_VER)
30982
30983   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30984      __asm {
30985         rdtsc
30986         ret       ; return value at EDX:EAX
30987      }
30988   }
30989
30990   #endif
30991
30992 #elif (defined(__GNUC__) && defined(__x86_64__))
30993
30994   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30995       unsigned long val;
30996       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30997       return val;
30998   }
30999  
31000 #elif (defined(__GNUC__) && defined(__ppc__))
31001
31002   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31003       unsigned long long retval;
31004       unsigned long junk;
31005       __asm__ __volatile__ ("\n\
31006           1:      mftbu   %1\n\
31007                   mftb    %L0\n\
31008                   mftbu   %0\n\
31009                   cmpw    %0,%1\n\
31010                   bne     1b"
31011                   : "=r" (retval), "=r" (junk));
31012       return retval;
31013   }
31014
31015 #else
31016
31017   #error Need implementation of sqlite3Hwtime() for your platform.
31018
31019   /*
31020   ** To compile without implementing sqlite3Hwtime() for your platform,
31021   ** you can remove the above #error and use the following
31022   ** stub function.  You will lose timing support for many
31023   ** of the debugging and testing utilities, but it should at
31024   ** least compile and run.
31025   */
31026 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31027
31028 #endif
31029
31030 #endif /* !defined(_HWTIME_H_) */
31031
31032 /************** End of hwtime.h **********************************************/
31033 /************** Continuing where we left off in os_common.h ******************/
31034
31035 static sqlite_uint64 g_start;
31036 static sqlite_uint64 g_elapsed;
31037 #define TIMER_START       g_start=sqlite3Hwtime()
31038 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31039 #define TIMER_ELAPSED     g_elapsed
31040 #else
31041 #define TIMER_START
31042 #define TIMER_END
31043 #define TIMER_ELAPSED     ((sqlite_uint64)0)
31044 #endif
31045
31046 /*
31047 ** If we compile with the SQLITE_TEST macro set, then the following block
31048 ** of code will give us the ability to simulate a disk I/O error.  This
31049 ** is used for testing the I/O recovery logic.
31050 */
31051 #ifdef SQLITE_TEST
31052 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31053 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31054 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31055 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31056 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31057 SQLITE_API int sqlite3_diskfull_pending = 0;
31058 SQLITE_API int sqlite3_diskfull = 0;
31059 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31060 #define SimulateIOError(CODE)  \
31061   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31062        || sqlite3_io_error_pending-- == 1 )  \
31063               { local_ioerr(); CODE; }
31064 static void local_ioerr(){
31065   IOTRACE(("IOERR\n"));
31066   sqlite3_io_error_hit++;
31067   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31068 }
31069 #define SimulateDiskfullError(CODE) \
31070    if( sqlite3_diskfull_pending ){ \
31071      if( sqlite3_diskfull_pending == 1 ){ \
31072        local_ioerr(); \
31073        sqlite3_diskfull = 1; \
31074        sqlite3_io_error_hit = 1; \
31075        CODE; \
31076      }else{ \
31077        sqlite3_diskfull_pending--; \
31078      } \
31079    }
31080 #else
31081 #define SimulateIOErrorBenign(X)
31082 #define SimulateIOError(A)
31083 #define SimulateDiskfullError(A)
31084 #endif
31085
31086 /*
31087 ** When testing, keep a count of the number of open files.
31088 */
31089 #ifdef SQLITE_TEST
31090 SQLITE_API int sqlite3_open_file_count = 0;
31091 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
31092 #else
31093 #define OpenCounter(X)
31094 #endif
31095
31096 #endif /* !defined(_OS_COMMON_H_) */
31097
31098 /************** End of os_common.h *******************************************/
31099 /************** Continuing where we left off in os_win.c *********************/
31100
31101 /*
31102 ** Some microsoft compilers lack this definition.
31103 */
31104 #ifndef INVALID_FILE_ATTRIBUTES
31105 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
31106 #endif
31107
31108 /*
31109 ** Determine if we are dealing with WindowsCE - which has a much
31110 ** reduced API.
31111 */
31112 #if SQLITE_OS_WINCE
31113 # define AreFileApisANSI() 1
31114 # define FormatMessageW(a,b,c,d,e,f,g) 0
31115 #endif
31116
31117 /* Forward references */
31118 typedef struct winShm winShm;           /* A connection to shared-memory */
31119 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31120
31121 /*
31122 ** WinCE lacks native support for file locking so we have to fake it
31123 ** with some code of our own.
31124 */
31125 #if SQLITE_OS_WINCE
31126 typedef struct winceLock {
31127   int nReaders;       /* Number of reader locks obtained */
31128   BOOL bPending;      /* Indicates a pending lock has been obtained */
31129   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31130   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31131 } winceLock;
31132 #endif
31133
31134 /*
31135 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31136 ** portability layer.
31137 */
31138 typedef struct winFile winFile;
31139 struct winFile {
31140   const sqlite3_io_methods *pMethod; /*** Must be first ***/
31141   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31142   HANDLE h;               /* Handle for accessing the file */
31143   unsigned char locktype; /* Type of lock currently held on this file */
31144   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31145   DWORD lastErrno;        /* The Windows errno from the last I/O error */
31146   DWORD sectorSize;       /* Sector size of the device file is on */
31147   winShm *pShm;           /* Instance of shared memory on this file */
31148   const char *zPath;      /* Full pathname of this file */
31149   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31150 #if SQLITE_OS_WINCE
31151   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
31152   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
31153   HANDLE hShared;         /* Shared memory segment used for locking */
31154   winceLock local;        /* Locks obtained by this instance of winFile */
31155   winceLock *shared;      /* Global shared lock memory for the file  */
31156 #endif
31157 };
31158
31159 /*
31160 ** Forward prototypes.
31161 */
31162 static int getSectorSize(
31163     sqlite3_vfs *pVfs,
31164     const char *zRelative     /* UTF-8 file name */
31165 );
31166
31167 /*
31168 ** The following variable is (normally) set once and never changes
31169 ** thereafter.  It records whether the operating system is Win95
31170 ** or WinNT.
31171 **
31172 ** 0:   Operating system unknown.
31173 ** 1:   Operating system is Win95.
31174 ** 2:   Operating system is WinNT.
31175 **
31176 ** In order to facilitate testing on a WinNT system, the test fixture
31177 ** can manually set this value to 1 to emulate Win98 behavior.
31178 */
31179 #ifdef SQLITE_TEST
31180 SQLITE_API int sqlite3_os_type = 0;
31181 #else
31182 static int sqlite3_os_type = 0;
31183 #endif
31184
31185 /*
31186 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31187 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31188 **
31189 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31190 ** the LockFileEx() API.  But we can still statically link against that
31191 ** API as long as we don't call it when running Win95/98/ME.  A call to
31192 ** this routine is used to determine if the host is Win95/98/ME or
31193 ** WinNT/2K/XP so that we will know whether or not we can safely call
31194 ** the LockFileEx() API.
31195 */
31196 #if SQLITE_OS_WINCE
31197 # define isNT()  (1)
31198 #else
31199   static int isNT(void){
31200     if( sqlite3_os_type==0 ){
31201       OSVERSIONINFO sInfo;
31202       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31203       GetVersionEx(&sInfo);
31204       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31205     }
31206     return sqlite3_os_type==2;
31207   }
31208 #endif /* SQLITE_OS_WINCE */
31209
31210 /*
31211 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
31212 **
31213 ** Space to hold the returned string is obtained from malloc.
31214 */
31215 static WCHAR *utf8ToUnicode(const char *zFilename){
31216   int nChar;
31217   WCHAR *zWideFilename;
31218
31219   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31220   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31221   if( zWideFilename==0 ){
31222     return 0;
31223   }
31224   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31225   if( nChar==0 ){
31226     free(zWideFilename);
31227     zWideFilename = 0;
31228   }
31229   return zWideFilename;
31230 }
31231
31232 /*
31233 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
31234 ** obtained from malloc().
31235 */
31236 static char *unicodeToUtf8(const WCHAR *zWideFilename){
31237   int nByte;
31238   char *zFilename;
31239
31240   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31241   zFilename = malloc( nByte );
31242   if( zFilename==0 ){
31243     return 0;
31244   }
31245   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31246                               0, 0);
31247   if( nByte == 0 ){
31248     free(zFilename);
31249     zFilename = 0;
31250   }
31251   return zFilename;
31252 }
31253
31254 /*
31255 ** Convert an ansi string to microsoft unicode, based on the
31256 ** current codepage settings for file apis.
31257 ** 
31258 ** Space to hold the returned string is obtained
31259 ** from malloc.
31260 */
31261 static WCHAR *mbcsToUnicode(const char *zFilename){
31262   int nByte;
31263   WCHAR *zMbcsFilename;
31264   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31265
31266   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31267   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31268   if( zMbcsFilename==0 ){
31269     return 0;
31270   }
31271   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31272   if( nByte==0 ){
31273     free(zMbcsFilename);
31274     zMbcsFilename = 0;
31275   }
31276   return zMbcsFilename;
31277 }
31278
31279 /*
31280 ** Convert microsoft unicode to multibyte character string, based on the
31281 ** user's Ansi codepage.
31282 **
31283 ** Space to hold the returned string is obtained from
31284 ** malloc().
31285 */
31286 static char *unicodeToMbcs(const WCHAR *zWideFilename){
31287   int nByte;
31288   char *zFilename;
31289   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31290
31291   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31292   zFilename = malloc( nByte );
31293   if( zFilename==0 ){
31294     return 0;
31295   }
31296   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31297                               0, 0);
31298   if( nByte == 0 ){
31299     free(zFilename);
31300     zFilename = 0;
31301   }
31302   return zFilename;
31303 }
31304
31305 /*
31306 ** Convert multibyte character string to UTF-8.  Space to hold the
31307 ** returned string is obtained from malloc().
31308 */
31309 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31310   char *zFilenameUtf8;
31311   WCHAR *zTmpWide;
31312
31313   zTmpWide = mbcsToUnicode(zFilename);
31314   if( zTmpWide==0 ){
31315     return 0;
31316   }
31317   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31318   free(zTmpWide);
31319   return zFilenameUtf8;
31320 }
31321
31322 /*
31323 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31324 ** returned string is obtained from malloc().
31325 */
31326 static char *utf8ToMbcs(const char *zFilename){
31327   char *zFilenameMbcs;
31328   WCHAR *zTmpWide;
31329
31330   zTmpWide = utf8ToUnicode(zFilename);
31331   if( zTmpWide==0 ){
31332     return 0;
31333   }
31334   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31335   free(zTmpWide);
31336   return zFilenameMbcs;
31337 }
31338
31339 #if SQLITE_OS_WINCE
31340 /*************************************************************************
31341 ** This section contains code for WinCE only.
31342 */
31343 /*
31344 ** WindowsCE does not have a localtime() function.  So create a
31345 ** substitute.
31346 */
31347 struct tm *__cdecl localtime(const time_t *t)
31348 {
31349   static struct tm y;
31350   FILETIME uTm, lTm;
31351   SYSTEMTIME pTm;
31352   sqlite3_int64 t64;
31353   t64 = *t;
31354   t64 = (t64 + 11644473600)*10000000;
31355   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31356   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31357   FileTimeToLocalFileTime(&uTm,&lTm);
31358   FileTimeToSystemTime(&lTm,&pTm);
31359   y.tm_year = pTm.wYear - 1900;
31360   y.tm_mon = pTm.wMonth - 1;
31361   y.tm_wday = pTm.wDayOfWeek;
31362   y.tm_mday = pTm.wDay;
31363   y.tm_hour = pTm.wHour;
31364   y.tm_min = pTm.wMinute;
31365   y.tm_sec = pTm.wSecond;
31366   return &y;
31367 }
31368
31369 /* This will never be called, but defined to make the code compile */
31370 #define GetTempPathA(a,b)
31371
31372 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
31373 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
31374 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
31375
31376 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31377
31378 /*
31379 ** Acquire a lock on the handle h
31380 */
31381 static void winceMutexAcquire(HANDLE h){
31382    DWORD dwErr;
31383    do {
31384      dwErr = WaitForSingleObject(h, INFINITE);
31385    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31386 }
31387 /*
31388 ** Release a lock acquired by winceMutexAcquire()
31389 */
31390 #define winceMutexRelease(h) ReleaseMutex(h)
31391
31392 /*
31393 ** Create the mutex and shared memory used for locking in the file
31394 ** descriptor pFile
31395 */
31396 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31397   WCHAR *zTok;
31398   WCHAR *zName = utf8ToUnicode(zFilename);
31399   BOOL bInit = TRUE;
31400
31401   /* Initialize the local lockdata */
31402   ZeroMemory(&pFile->local, sizeof(pFile->local));
31403
31404   /* Replace the backslashes from the filename and lowercase it
31405   ** to derive a mutex name. */
31406   zTok = CharLowerW(zName);
31407   for (;*zTok;zTok++){
31408     if (*zTok == '\\') *zTok = '_';
31409   }
31410
31411   /* Create/open the named mutex */
31412   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31413   if (!pFile->hMutex){
31414     pFile->lastErrno = GetLastError();
31415     free(zName);
31416     return FALSE;
31417   }
31418
31419   /* Acquire the mutex before continuing */
31420   winceMutexAcquire(pFile->hMutex);
31421   
31422   /* Since the names of named mutexes, semaphores, file mappings etc are 
31423   ** case-sensitive, take advantage of that by uppercasing the mutex name
31424   ** and using that as the shared filemapping name.
31425   */
31426   CharUpperW(zName);
31427   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31428                                        PAGE_READWRITE, 0, sizeof(winceLock),
31429                                        zName);  
31430
31431   /* Set a flag that indicates we're the first to create the memory so it 
31432   ** must be zero-initialized */
31433   if (GetLastError() == ERROR_ALREADY_EXISTS){
31434     bInit = FALSE;
31435   }
31436
31437   free(zName);
31438
31439   /* If we succeeded in making the shared memory handle, map it. */
31440   if (pFile->hShared){
31441     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
31442              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31443     /* If mapping failed, close the shared memory handle and erase it */
31444     if (!pFile->shared){
31445       pFile->lastErrno = GetLastError();
31446       CloseHandle(pFile->hShared);
31447       pFile->hShared = NULL;
31448     }
31449   }
31450
31451   /* If shared memory could not be created, then close the mutex and fail */
31452   if (pFile->hShared == NULL){
31453     winceMutexRelease(pFile->hMutex);
31454     CloseHandle(pFile->hMutex);
31455     pFile->hMutex = NULL;
31456     return FALSE;
31457   }
31458   
31459   /* Initialize the shared memory if we're supposed to */
31460   if (bInit) {
31461     ZeroMemory(pFile->shared, sizeof(winceLock));
31462   }
31463
31464   winceMutexRelease(pFile->hMutex);
31465   return TRUE;
31466 }
31467
31468 /*
31469 ** Destroy the part of winFile that deals with wince locks
31470 */
31471 static void winceDestroyLock(winFile *pFile){
31472   if (pFile->hMutex){
31473     /* Acquire the mutex */
31474     winceMutexAcquire(pFile->hMutex);
31475
31476     /* The following blocks should probably assert in debug mode, but they
31477        are to cleanup in case any locks remained open */
31478     if (pFile->local.nReaders){
31479       pFile->shared->nReaders --;
31480     }
31481     if (pFile->local.bReserved){
31482       pFile->shared->bReserved = FALSE;
31483     }
31484     if (pFile->local.bPending){
31485       pFile->shared->bPending = FALSE;
31486     }
31487     if (pFile->local.bExclusive){
31488       pFile->shared->bExclusive = FALSE;
31489     }
31490
31491     /* De-reference and close our copy of the shared memory handle */
31492     UnmapViewOfFile(pFile->shared);
31493     CloseHandle(pFile->hShared);
31494
31495     /* Done with the mutex */
31496     winceMutexRelease(pFile->hMutex);    
31497     CloseHandle(pFile->hMutex);
31498     pFile->hMutex = NULL;
31499   }
31500 }
31501
31502 /* 
31503 ** An implementation of the LockFile() API of windows for wince
31504 */
31505 static BOOL winceLockFile(
31506   HANDLE *phFile,
31507   DWORD dwFileOffsetLow,
31508   DWORD dwFileOffsetHigh,
31509   DWORD nNumberOfBytesToLockLow,
31510   DWORD nNumberOfBytesToLockHigh
31511 ){
31512   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31513   BOOL bReturn = FALSE;
31514
31515   UNUSED_PARAMETER(dwFileOffsetHigh);
31516   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31517
31518   if (!pFile->hMutex) return TRUE;
31519   winceMutexAcquire(pFile->hMutex);
31520
31521   /* Wanting an exclusive lock? */
31522   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31523        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31524     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31525        pFile->shared->bExclusive = TRUE;
31526        pFile->local.bExclusive = TRUE;
31527        bReturn = TRUE;
31528     }
31529   }
31530
31531   /* Want a read-only lock? */
31532   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31533            nNumberOfBytesToLockLow == 1){
31534     if (pFile->shared->bExclusive == 0){
31535       pFile->local.nReaders ++;
31536       if (pFile->local.nReaders == 1){
31537         pFile->shared->nReaders ++;
31538       }
31539       bReturn = TRUE;
31540     }
31541   }
31542
31543   /* Want a pending lock? */
31544   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31545     /* If no pending lock has been acquired, then acquire it */
31546     if (pFile->shared->bPending == 0) {
31547       pFile->shared->bPending = TRUE;
31548       pFile->local.bPending = TRUE;
31549       bReturn = TRUE;
31550     }
31551   }
31552
31553   /* Want a reserved lock? */
31554   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31555     if (pFile->shared->bReserved == 0) {
31556       pFile->shared->bReserved = TRUE;
31557       pFile->local.bReserved = TRUE;
31558       bReturn = TRUE;
31559     }
31560   }
31561
31562   winceMutexRelease(pFile->hMutex);
31563   return bReturn;
31564 }
31565
31566 /*
31567 ** An implementation of the UnlockFile API of windows for wince
31568 */
31569 static BOOL winceUnlockFile(
31570   HANDLE *phFile,
31571   DWORD dwFileOffsetLow,
31572   DWORD dwFileOffsetHigh,
31573   DWORD nNumberOfBytesToUnlockLow,
31574   DWORD nNumberOfBytesToUnlockHigh
31575 ){
31576   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31577   BOOL bReturn = FALSE;
31578
31579   UNUSED_PARAMETER(dwFileOffsetHigh);
31580   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31581
31582   if (!pFile->hMutex) return TRUE;
31583   winceMutexAcquire(pFile->hMutex);
31584
31585   /* Releasing a reader lock or an exclusive lock */
31586   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31587     /* Did we have an exclusive lock? */
31588     if (pFile->local.bExclusive){
31589       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31590       pFile->local.bExclusive = FALSE;
31591       pFile->shared->bExclusive = FALSE;
31592       bReturn = TRUE;
31593     }
31594
31595     /* Did we just have a reader lock? */
31596     else if (pFile->local.nReaders){
31597       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31598       pFile->local.nReaders --;
31599       if (pFile->local.nReaders == 0)
31600       {
31601         pFile->shared->nReaders --;
31602       }
31603       bReturn = TRUE;
31604     }
31605   }
31606
31607   /* Releasing a pending lock */
31608   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31609     if (pFile->local.bPending){
31610       pFile->local.bPending = FALSE;
31611       pFile->shared->bPending = FALSE;
31612       bReturn = TRUE;
31613     }
31614   }
31615   /* Releasing a reserved lock */
31616   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31617     if (pFile->local.bReserved) {
31618       pFile->local.bReserved = FALSE;
31619       pFile->shared->bReserved = FALSE;
31620       bReturn = TRUE;
31621     }
31622   }
31623
31624   winceMutexRelease(pFile->hMutex);
31625   return bReturn;
31626 }
31627
31628 /*
31629 ** An implementation of the LockFileEx() API of windows for wince
31630 */
31631 static BOOL winceLockFileEx(
31632   HANDLE *phFile,
31633   DWORD dwFlags,
31634   DWORD dwReserved,
31635   DWORD nNumberOfBytesToLockLow,
31636   DWORD nNumberOfBytesToLockHigh,
31637   LPOVERLAPPED lpOverlapped
31638 ){
31639   UNUSED_PARAMETER(dwReserved);
31640   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31641
31642   /* If the caller wants a shared read lock, forward this call
31643   ** to winceLockFile */
31644   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
31645       dwFlags == 1 &&
31646       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31647     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
31648   }
31649   return FALSE;
31650 }
31651 /*
31652 ** End of the special code for wince
31653 *****************************************************************************/
31654 #endif /* SQLITE_OS_WINCE */
31655
31656 /*****************************************************************************
31657 ** The next group of routines implement the I/O methods specified
31658 ** by the sqlite3_io_methods object.
31659 ******************************************************************************/
31660
31661 /*
31662 ** Some microsoft compilers lack this definition.
31663 */
31664 #ifndef INVALID_SET_FILE_POINTER
31665 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
31666 #endif
31667
31668 /*
31669 ** Move the current position of the file handle passed as the first 
31670 ** argument to offset iOffset within the file. If successful, return 0. 
31671 ** Otherwise, set pFile->lastErrno and return non-zero.
31672 */
31673 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31674   LONG upperBits;                 /* Most sig. 32 bits of new offset */
31675   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
31676   DWORD dwRet;                    /* Value returned by SetFilePointer() */
31677
31678   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31679   lowerBits = (LONG)(iOffset & 0xffffffff);
31680
31681   /* API oddity: If successful, SetFilePointer() returns a dword 
31682   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31683   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
31684   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
31685   ** whether an error has actually occured, it is also necessary to call 
31686   ** GetLastError().
31687   */
31688   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31689   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
31690     pFile->lastErrno = GetLastError();
31691     return 1;
31692   }
31693
31694   return 0;
31695 }
31696
31697 /*
31698 ** Close a file.
31699 **
31700 ** It is reported that an attempt to close a handle might sometimes
31701 ** fail.  This is a very unreasonable result, but windows is notorious
31702 ** for being unreasonable so I do not doubt that it might happen.  If
31703 ** the close fails, we pause for 100 milliseconds and try again.  As
31704 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31705 ** giving up and returning an error.
31706 */
31707 #define MX_CLOSE_ATTEMPT 3
31708 static int winClose(sqlite3_file *id){
31709   int rc, cnt = 0;
31710   winFile *pFile = (winFile*)id;
31711
31712   assert( id!=0 );
31713   assert( pFile->pShm==0 );
31714   OSTRACE(("CLOSE %d\n", pFile->h));
31715   do{
31716     rc = CloseHandle(pFile->h);
31717     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31718   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
31719 #if SQLITE_OS_WINCE
31720 #define WINCE_DELETION_ATTEMPTS 3
31721   winceDestroyLock(pFile);
31722   if( pFile->zDeleteOnClose ){
31723     int cnt = 0;
31724     while(
31725            DeleteFileW(pFile->zDeleteOnClose)==0
31726         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
31727         && cnt++ < WINCE_DELETION_ATTEMPTS
31728     ){
31729        Sleep(100);  /* Wait a little before trying again */
31730     }
31731     free(pFile->zDeleteOnClose);
31732   }
31733 #endif
31734   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31735   OpenCounter(-1);
31736   return rc ? SQLITE_OK : SQLITE_IOERR;
31737 }
31738
31739 /*
31740 ** Read data from a file into a buffer.  Return SQLITE_OK if all
31741 ** bytes were read successfully and SQLITE_IOERR if anything goes
31742 ** wrong.
31743 */
31744 static int winRead(
31745   sqlite3_file *id,          /* File to read from */
31746   void *pBuf,                /* Write content into this buffer */
31747   int amt,                   /* Number of bytes to read */
31748   sqlite3_int64 offset       /* Begin reading at this offset */
31749 ){
31750   winFile *pFile = (winFile*)id;  /* file handle */
31751   DWORD nRead;                    /* Number of bytes actually read from file */
31752
31753   assert( id!=0 );
31754   SimulateIOError(return SQLITE_IOERR_READ);
31755   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31756
31757   if( seekWinFile(pFile, offset) ){
31758     return SQLITE_FULL;
31759   }
31760   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31761     pFile->lastErrno = GetLastError();
31762     return SQLITE_IOERR_READ;
31763   }
31764   if( nRead<(DWORD)amt ){
31765     /* Unread parts of the buffer must be zero-filled */
31766     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31767     return SQLITE_IOERR_SHORT_READ;
31768   }
31769
31770   return SQLITE_OK;
31771 }
31772
31773 /*
31774 ** Write data from a buffer into a file.  Return SQLITE_OK on success
31775 ** or some other error code on failure.
31776 */
31777 static int winWrite(
31778   sqlite3_file *id,               /* File to write into */
31779   const void *pBuf,               /* The bytes to be written */
31780   int amt,                        /* Number of bytes to write */
31781   sqlite3_int64 offset            /* Offset into the file to begin writing at */
31782 ){
31783   int rc;                         /* True if error has occured, else false */
31784   winFile *pFile = (winFile*)id;  /* File handle */
31785
31786   assert( amt>0 );
31787   assert( pFile );
31788   SimulateIOError(return SQLITE_IOERR_WRITE);
31789   SimulateDiskfullError(return SQLITE_FULL);
31790
31791   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31792
31793   rc = seekWinFile(pFile, offset);
31794   if( rc==0 ){
31795     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
31796     int nRem = amt;               /* Number of bytes yet to be written */
31797     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
31798
31799     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
31800       aRem += nWrite;
31801       nRem -= nWrite;
31802     }
31803     if( nRem>0 ){
31804       pFile->lastErrno = GetLastError();
31805       rc = 1;
31806     }
31807   }
31808
31809   if( rc ){
31810     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
31811       return SQLITE_FULL;
31812     }
31813     return SQLITE_IOERR_WRITE;
31814   }
31815   return SQLITE_OK;
31816 }
31817
31818 /*
31819 ** Truncate an open file to a specified size
31820 */
31821 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
31822   winFile *pFile = (winFile*)id;  /* File handle object */
31823   int rc = SQLITE_OK;             /* Return code for this function */
31824
31825   assert( pFile );
31826
31827   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
31828   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
31829
31830   /* If the user has configured a chunk-size for this file, truncate the
31831   ** file so that it consists of an integer number of chunks (i.e. the
31832   ** actual file size after the operation may be larger than the requested
31833   ** size).
31834   */
31835   if( pFile->szChunk ){
31836     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
31837   }
31838
31839   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
31840   if( seekWinFile(pFile, nByte) ){
31841     rc = SQLITE_IOERR_TRUNCATE;
31842   }else if( 0==SetEndOfFile(pFile->h) ){
31843     pFile->lastErrno = GetLastError();
31844     rc = SQLITE_IOERR_TRUNCATE;
31845   }
31846
31847   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
31848   return rc;
31849 }
31850
31851 #ifdef SQLITE_TEST
31852 /*
31853 ** Count the number of fullsyncs and normal syncs.  This is used to test
31854 ** that syncs and fullsyncs are occuring at the right times.
31855 */
31856 SQLITE_API int sqlite3_sync_count = 0;
31857 SQLITE_API int sqlite3_fullsync_count = 0;
31858 #endif
31859
31860 /*
31861 ** Make sure all writes to a particular file are committed to disk.
31862 */
31863 static int winSync(sqlite3_file *id, int flags){
31864 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
31865   winFile *pFile = (winFile*)id;
31866 #else
31867   UNUSED_PARAMETER(id);
31868 #endif
31869
31870   assert( pFile );
31871   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
31872   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
31873       || (flags&0x0F)==SQLITE_SYNC_FULL
31874   );
31875
31876   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
31877
31878 #ifndef SQLITE_TEST
31879   UNUSED_PARAMETER(flags);
31880 #else
31881   if( flags & SQLITE_SYNC_FULL ){
31882     sqlite3_fullsync_count++;
31883   }
31884   sqlite3_sync_count++;
31885 #endif
31886
31887   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
31888   ** line is to test that doing so does not cause any problems.
31889   */
31890   SimulateDiskfullError( return SQLITE_FULL );
31891   SimulateIOError( return SQLITE_IOERR; );
31892
31893   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
31894   ** no-op
31895   */
31896 #ifdef SQLITE_NO_SYNC
31897   return SQLITE_OK;
31898 #else
31899   if( FlushFileBuffers(pFile->h) ){
31900     return SQLITE_OK;
31901   }else{
31902     pFile->lastErrno = GetLastError();
31903     return SQLITE_IOERR;
31904   }
31905 #endif
31906 }
31907
31908 /*
31909 ** Determine the current size of a file in bytes
31910 */
31911 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
31912   DWORD upperBits;
31913   DWORD lowerBits;
31914   winFile *pFile = (winFile*)id;
31915   DWORD error;
31916
31917   assert( id!=0 );
31918   SimulateIOError(return SQLITE_IOERR_FSTAT);
31919   lowerBits = GetFileSize(pFile->h, &upperBits);
31920   if(   (lowerBits == INVALID_FILE_SIZE)
31921      && ((error = GetLastError()) != NO_ERROR) )
31922   {
31923     pFile->lastErrno = error;
31924     return SQLITE_IOERR_FSTAT;
31925   }
31926   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
31927   return SQLITE_OK;
31928 }
31929
31930 /*
31931 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
31932 */
31933 #ifndef LOCKFILE_FAIL_IMMEDIATELY
31934 # define LOCKFILE_FAIL_IMMEDIATELY 1
31935 #endif
31936
31937 /*
31938 ** Acquire a reader lock.
31939 ** Different API routines are called depending on whether or not this
31940 ** is Win95 or WinNT.
31941 */
31942 static int getReadLock(winFile *pFile){
31943   int res;
31944   if( isNT() ){
31945     OVERLAPPED ovlp;
31946     ovlp.Offset = SHARED_FIRST;
31947     ovlp.OffsetHigh = 0;
31948     ovlp.hEvent = 0;
31949     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
31950                      0, SHARED_SIZE, 0, &ovlp);
31951 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31952 */
31953 #if SQLITE_OS_WINCE==0
31954   }else{
31955     int lk;
31956     sqlite3_randomness(sizeof(lk), &lk);
31957     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
31958     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
31959 #endif
31960   }
31961   if( res == 0 ){
31962     pFile->lastErrno = GetLastError();
31963   }
31964   return res;
31965 }
31966
31967 /*
31968 ** Undo a readlock
31969 */
31970 static int unlockReadLock(winFile *pFile){
31971   int res;
31972   if( isNT() ){
31973     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
31974 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31975 */
31976 #if SQLITE_OS_WINCE==0
31977   }else{
31978     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
31979 #endif
31980   }
31981   if( res == 0 ){
31982     pFile->lastErrno = GetLastError();
31983   }
31984   return res;
31985 }
31986
31987 /*
31988 ** Lock the file with the lock specified by parameter locktype - one
31989 ** of the following:
31990 **
31991 **     (1) SHARED_LOCK
31992 **     (2) RESERVED_LOCK
31993 **     (3) PENDING_LOCK
31994 **     (4) EXCLUSIVE_LOCK
31995 **
31996 ** Sometimes when requesting one lock state, additional lock states
31997 ** are inserted in between.  The locking might fail on one of the later
31998 ** transitions leaving the lock state different from what it started but
31999 ** still short of its goal.  The following chart shows the allowed
32000 ** transitions and the inserted intermediate states:
32001 **
32002 **    UNLOCKED -> SHARED
32003 **    SHARED -> RESERVED
32004 **    SHARED -> (PENDING) -> EXCLUSIVE
32005 **    RESERVED -> (PENDING) -> EXCLUSIVE
32006 **    PENDING -> EXCLUSIVE
32007 **
32008 ** This routine will only increase a lock.  The winUnlock() routine
32009 ** erases all locks at once and returns us immediately to locking level 0.
32010 ** It is not possible to lower the locking level one step at a time.  You
32011 ** must go straight to locking level 0.
32012 */
32013 static int winLock(sqlite3_file *id, int locktype){
32014   int rc = SQLITE_OK;    /* Return code from subroutines */
32015   int res = 1;           /* Result of a windows lock call */
32016   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32017   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32018   winFile *pFile = (winFile*)id;
32019   DWORD error = NO_ERROR;
32020
32021   assert( id!=0 );
32022   OSTRACE(("LOCK %d %d was %d(%d)\n",
32023            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32024
32025   /* If there is already a lock of this type or more restrictive on the
32026   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32027   ** sqlite3OsEnterMutex() hasn't been called yet.
32028   */
32029   if( pFile->locktype>=locktype ){
32030     return SQLITE_OK;
32031   }
32032
32033   /* Make sure the locking sequence is correct
32034   */
32035   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32036   assert( locktype!=PENDING_LOCK );
32037   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32038
32039   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32040   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32041   ** the PENDING_LOCK byte is temporary.
32042   */
32043   newLocktype = pFile->locktype;
32044   if(   (pFile->locktype==NO_LOCK)
32045      || (   (locktype==EXCLUSIVE_LOCK)
32046          && (pFile->locktype==RESERVED_LOCK))
32047   ){
32048     int cnt = 3;
32049     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32050       /* Try 3 times to get the pending lock.  The pending lock might be
32051       ** held by another reader process who will release it momentarily.
32052       */
32053       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32054       Sleep(1);
32055     }
32056     gotPendingLock = res;
32057     if( !res ){
32058       error = GetLastError();
32059     }
32060   }
32061
32062   /* Acquire a shared lock
32063   */
32064   if( locktype==SHARED_LOCK && res ){
32065     assert( pFile->locktype==NO_LOCK );
32066     res = getReadLock(pFile);
32067     if( res ){
32068       newLocktype = SHARED_LOCK;
32069     }else{
32070       error = GetLastError();
32071     }
32072   }
32073
32074   /* Acquire a RESERVED lock
32075   */
32076   if( locktype==RESERVED_LOCK && res ){
32077     assert( pFile->locktype==SHARED_LOCK );
32078     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32079     if( res ){
32080       newLocktype = RESERVED_LOCK;
32081     }else{
32082       error = GetLastError();
32083     }
32084   }
32085
32086   /* Acquire a PENDING lock
32087   */
32088   if( locktype==EXCLUSIVE_LOCK && res ){
32089     newLocktype = PENDING_LOCK;
32090     gotPendingLock = 0;
32091   }
32092
32093   /* Acquire an EXCLUSIVE lock
32094   */
32095   if( locktype==EXCLUSIVE_LOCK && res ){
32096     assert( pFile->locktype>=SHARED_LOCK );
32097     res = unlockReadLock(pFile);
32098     OSTRACE(("unreadlock = %d\n", res));
32099     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32100     if( res ){
32101       newLocktype = EXCLUSIVE_LOCK;
32102     }else{
32103       error = GetLastError();
32104       OSTRACE(("error-code = %d\n", error));
32105       getReadLock(pFile);
32106     }
32107   }
32108
32109   /* If we are holding a PENDING lock that ought to be released, then
32110   ** release it now.
32111   */
32112   if( gotPendingLock && locktype==SHARED_LOCK ){
32113     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32114   }
32115
32116   /* Update the state of the lock has held in the file descriptor then
32117   ** return the appropriate result code.
32118   */
32119   if( res ){
32120     rc = SQLITE_OK;
32121   }else{
32122     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32123            locktype, newLocktype));
32124     pFile->lastErrno = error;
32125     rc = SQLITE_BUSY;
32126   }
32127   pFile->locktype = (u8)newLocktype;
32128   return rc;
32129 }
32130
32131 /*
32132 ** This routine checks if there is a RESERVED lock held on the specified
32133 ** file by this or any other process. If such a lock is held, return
32134 ** non-zero, otherwise zero.
32135 */
32136 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32137   int rc;
32138   winFile *pFile = (winFile*)id;
32139
32140   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32141
32142   assert( id!=0 );
32143   if( pFile->locktype>=RESERVED_LOCK ){
32144     rc = 1;
32145     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32146   }else{
32147     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32148     if( rc ){
32149       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32150     }
32151     rc = !rc;
32152     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32153   }
32154   *pResOut = rc;
32155   return SQLITE_OK;
32156 }
32157
32158 /*
32159 ** Lower the locking level on file descriptor id to locktype.  locktype
32160 ** must be either NO_LOCK or SHARED_LOCK.
32161 **
32162 ** If the locking level of the file descriptor is already at or below
32163 ** the requested locking level, this routine is a no-op.
32164 **
32165 ** It is not possible for this routine to fail if the second argument
32166 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32167 ** might return SQLITE_IOERR;
32168 */
32169 static int winUnlock(sqlite3_file *id, int locktype){
32170   int type;
32171   winFile *pFile = (winFile*)id;
32172   int rc = SQLITE_OK;
32173   assert( pFile!=0 );
32174   assert( locktype<=SHARED_LOCK );
32175   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32176           pFile->locktype, pFile->sharedLockByte));
32177   type = pFile->locktype;
32178   if( type>=EXCLUSIVE_LOCK ){
32179     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32180     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32181       /* This should never happen.  We should always be able to
32182       ** reacquire the read lock */
32183       rc = SQLITE_IOERR_UNLOCK;
32184     }
32185   }
32186   if( type>=RESERVED_LOCK ){
32187     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32188   }
32189   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32190     unlockReadLock(pFile);
32191   }
32192   if( type>=PENDING_LOCK ){
32193     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32194   }
32195   pFile->locktype = (u8)locktype;
32196   return rc;
32197 }
32198
32199 /*
32200 ** Control and query of the open file handle.
32201 */
32202 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32203   switch( op ){
32204     case SQLITE_FCNTL_LOCKSTATE: {
32205       *(int*)pArg = ((winFile*)id)->locktype;
32206       return SQLITE_OK;
32207     }
32208     case SQLITE_LAST_ERRNO: {
32209       *(int*)pArg = (int)((winFile*)id)->lastErrno;
32210       return SQLITE_OK;
32211     }
32212     case SQLITE_FCNTL_CHUNK_SIZE: {
32213       ((winFile*)id)->szChunk = *(int *)pArg;
32214       return SQLITE_OK;
32215     }
32216     case SQLITE_FCNTL_SIZE_HINT: {
32217       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32218       SimulateIOErrorBenign(1);
32219       winTruncate(id, sz);
32220       SimulateIOErrorBenign(0);
32221       return SQLITE_OK;
32222     }
32223     case SQLITE_FCNTL_SYNC_OMITTED: {
32224       return SQLITE_OK;
32225     }
32226   }
32227   return SQLITE_NOTFOUND;
32228 }
32229
32230 /*
32231 ** Return the sector size in bytes of the underlying block device for
32232 ** the specified file. This is almost always 512 bytes, but may be
32233 ** larger for some devices.
32234 **
32235 ** SQLite code assumes this function cannot fail. It also assumes that
32236 ** if two files are created in the same file-system directory (i.e.
32237 ** a database and its journal file) that the sector size will be the
32238 ** same for both.
32239 */
32240 static int winSectorSize(sqlite3_file *id){
32241   assert( id!=0 );
32242   return (int)(((winFile*)id)->sectorSize);
32243 }
32244
32245 /*
32246 ** Return a vector of device characteristics.
32247 */
32248 static int winDeviceCharacteristics(sqlite3_file *id){
32249   UNUSED_PARAMETER(id);
32250   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32251 }
32252
32253 #ifndef SQLITE_OMIT_WAL
32254
32255 /* 
32256 ** Windows will only let you create file view mappings
32257 ** on allocation size granularity boundaries.
32258 ** During sqlite3_os_init() we do a GetSystemInfo()
32259 ** to get the granularity size.
32260 */
32261 SYSTEM_INFO winSysInfo;
32262
32263 /*
32264 ** Helper functions to obtain and relinquish the global mutex. The
32265 ** global mutex is used to protect the winLockInfo objects used by 
32266 ** this file, all of which may be shared by multiple threads.
32267 **
32268 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32269 ** is held when required. This function is only used as part of assert() 
32270 ** statements. e.g.
32271 **
32272 **   winShmEnterMutex()
32273 **     assert( winShmMutexHeld() );
32274 **   winShmLeaveMutex()
32275 */
32276 static void winShmEnterMutex(void){
32277   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32278 }
32279 static void winShmLeaveMutex(void){
32280   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32281 }
32282 #ifdef SQLITE_DEBUG
32283 static int winShmMutexHeld(void) {
32284   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32285 }
32286 #endif
32287
32288 /*
32289 ** Object used to represent a single file opened and mmapped to provide
32290 ** shared memory.  When multiple threads all reference the same
32291 ** log-summary, each thread has its own winFile object, but they all
32292 ** point to a single instance of this object.  In other words, each
32293 ** log-summary is opened only once per process.
32294 **
32295 ** winShmMutexHeld() must be true when creating or destroying
32296 ** this object or while reading or writing the following fields:
32297 **
32298 **      nRef
32299 **      pNext 
32300 **
32301 ** The following fields are read-only after the object is created:
32302 ** 
32303 **      fid
32304 **      zFilename
32305 **
32306 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32307 ** winShmMutexHeld() is true when reading or writing any other field
32308 ** in this structure.
32309 **
32310 */
32311 struct winShmNode {
32312   sqlite3_mutex *mutex;      /* Mutex to access this object */
32313   char *zFilename;           /* Name of the file */
32314   winFile hFile;             /* File handle from winOpen */
32315
32316   int szRegion;              /* Size of shared-memory regions */
32317   int nRegion;               /* Size of array apRegion */
32318   struct ShmRegion {
32319     HANDLE hMap;             /* File handle from CreateFileMapping */
32320     void *pMap;
32321   } *aRegion;
32322   DWORD lastErrno;           /* The Windows errno from the last I/O error */
32323
32324   int nRef;                  /* Number of winShm objects pointing to this */
32325   winShm *pFirst;            /* All winShm objects pointing to this */
32326   winShmNode *pNext;         /* Next in list of all winShmNode objects */
32327 #ifdef SQLITE_DEBUG
32328   u8 nextShmId;              /* Next available winShm.id value */
32329 #endif
32330 };
32331
32332 /*
32333 ** A global array of all winShmNode objects.
32334 **
32335 ** The winShmMutexHeld() must be true while reading or writing this list.
32336 */
32337 static winShmNode *winShmNodeList = 0;
32338
32339 /*
32340 ** Structure used internally by this VFS to record the state of an
32341 ** open shared memory connection.
32342 **
32343 ** The following fields are initialized when this object is created and
32344 ** are read-only thereafter:
32345 **
32346 **    winShm.pShmNode
32347 **    winShm.id
32348 **
32349 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32350 ** while accessing any read/write fields.
32351 */
32352 struct winShm {
32353   winShmNode *pShmNode;      /* The underlying winShmNode object */
32354   winShm *pNext;             /* Next winShm with the same winShmNode */
32355   u8 hasMutex;               /* True if holding the winShmNode mutex */
32356   u16 sharedMask;            /* Mask of shared locks held */
32357   u16 exclMask;              /* Mask of exclusive locks held */
32358 #ifdef SQLITE_DEBUG
32359   u8 id;                     /* Id of this connection with its winShmNode */
32360 #endif
32361 };
32362
32363 /*
32364 ** Constants used for locking
32365 */
32366 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
32367 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
32368
32369 /*
32370 ** Apply advisory locks for all n bytes beginning at ofst.
32371 */
32372 #define _SHM_UNLCK  1
32373 #define _SHM_RDLCK  2
32374 #define _SHM_WRLCK  3
32375 static int winShmSystemLock(
32376   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
32377   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32378   int ofst,             /* Offset to first byte to be locked/unlocked */
32379   int nByte             /* Number of bytes to lock or unlock */
32380 ){
32381   OVERLAPPED ovlp;
32382   DWORD dwFlags;
32383   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
32384
32385   /* Access to the winShmNode object is serialized by the caller */
32386   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32387
32388   /* Initialize the locking parameters */
32389   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32390   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32391
32392   memset(&ovlp, 0, sizeof(OVERLAPPED));
32393   ovlp.Offset = ofst;
32394
32395   /* Release/Acquire the system-level lock */
32396   if( lockType==_SHM_UNLCK ){
32397     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32398   }else{
32399     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32400   }
32401   
32402   if( rc!= 0 ){
32403     rc = SQLITE_OK;
32404   }else{
32405     pFile->lastErrno =  GetLastError();
32406     rc = SQLITE_BUSY;
32407   }
32408
32409   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
32410            pFile->hFile.h,
32411            rc==SQLITE_OK ? "ok" : "failed",
32412            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32413            pFile->lastErrno));
32414
32415   return rc;
32416 }
32417
32418 /* Forward references to VFS methods */
32419 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32420 static int winDelete(sqlite3_vfs *,const char*,int);
32421
32422 /*
32423 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32424 **
32425 ** This is not a VFS shared-memory method; it is a utility function called
32426 ** by VFS shared-memory methods.
32427 */
32428 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32429   winShmNode **pp;
32430   winShmNode *p;
32431   BOOL bRc;
32432   assert( winShmMutexHeld() );
32433   pp = &winShmNodeList;
32434   while( (p = *pp)!=0 ){
32435     if( p->nRef==0 ){
32436       int i;
32437       if( p->mutex ) sqlite3_mutex_free(p->mutex);
32438       for(i=0; i<p->nRegion; i++){
32439         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32440         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32441                  (int)GetCurrentProcessId(), i,
32442                  bRc ? "ok" : "failed"));
32443         bRc = CloseHandle(p->aRegion[i].hMap);
32444         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32445                  (int)GetCurrentProcessId(), i,
32446                  bRc ? "ok" : "failed"));
32447       }
32448       if( p->hFile.h != INVALID_HANDLE_VALUE ){
32449         SimulateIOErrorBenign(1);
32450         winClose((sqlite3_file *)&p->hFile);
32451         SimulateIOErrorBenign(0);
32452       }
32453       if( deleteFlag ){
32454         SimulateIOErrorBenign(1);
32455         winDelete(pVfs, p->zFilename, 0);
32456         SimulateIOErrorBenign(0);
32457       }
32458       *pp = p->pNext;
32459       sqlite3_free(p->aRegion);
32460       sqlite3_free(p);
32461     }else{
32462       pp = &p->pNext;
32463     }
32464   }
32465 }
32466
32467 /*
32468 ** Open the shared-memory area associated with database file pDbFd.
32469 **
32470 ** When opening a new shared-memory file, if no other instances of that
32471 ** file are currently open, in this process or in other processes, then
32472 ** the file must be truncated to zero length or have its header cleared.
32473 */
32474 static int winOpenSharedMemory(winFile *pDbFd){
32475   struct winShm *p;                  /* The connection to be opened */
32476   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
32477   int rc;                            /* Result code */
32478   struct winShmNode *pNew;           /* Newly allocated winShmNode */
32479   int nName;                         /* Size of zName in bytes */
32480
32481   assert( pDbFd->pShm==0 );    /* Not previously opened */
32482
32483   /* Allocate space for the new sqlite3_shm object.  Also speculatively
32484   ** allocate space for a new winShmNode and filename.
32485   */
32486   p = sqlite3_malloc( sizeof(*p) );
32487   if( p==0 ) return SQLITE_NOMEM;
32488   memset(p, 0, sizeof(*p));
32489   nName = sqlite3Strlen30(pDbFd->zPath);
32490   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32491   if( pNew==0 ){
32492     sqlite3_free(p);
32493     return SQLITE_NOMEM;
32494   }
32495   memset(pNew, 0, sizeof(*pNew));
32496   pNew->zFilename = (char*)&pNew[1];
32497   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32498
32499   /* Look to see if there is an existing winShmNode that can be used.
32500   ** If no matching winShmNode currently exists, create a new one.
32501   */
32502   winShmEnterMutex();
32503   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32504     /* TBD need to come up with better match here.  Perhaps
32505     ** use FILE_ID_BOTH_DIR_INFO Structure.
32506     */
32507     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32508   }
32509   if( pShmNode ){
32510     sqlite3_free(pNew);
32511   }else{
32512     pShmNode = pNew;
32513     pNew = 0;
32514     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32515     pShmNode->pNext = winShmNodeList;
32516     winShmNodeList = pShmNode;
32517
32518     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32519     if( pShmNode->mutex==0 ){
32520       rc = SQLITE_NOMEM;
32521       goto shm_open_err;
32522     }
32523
32524     rc = winOpen(pDbFd->pVfs,
32525                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
32526                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
32527                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32528                  0);
32529     if( SQLITE_OK!=rc ){
32530       rc = SQLITE_CANTOPEN_BKPT;
32531       goto shm_open_err;
32532     }
32533
32534     /* Check to see if another process is holding the dead-man switch.
32535     ** If not, truncate the file to zero length. 
32536     */
32537     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32538       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32539       if( rc!=SQLITE_OK ){
32540         rc = SQLITE_IOERR_SHMOPEN;
32541       }
32542     }
32543     if( rc==SQLITE_OK ){
32544       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32545       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32546     }
32547     if( rc ) goto shm_open_err;
32548   }
32549
32550   /* Make the new connection a child of the winShmNode */
32551   p->pShmNode = pShmNode;
32552 #ifdef SQLITE_DEBUG
32553   p->id = pShmNode->nextShmId++;
32554 #endif
32555   pShmNode->nRef++;
32556   pDbFd->pShm = p;
32557   winShmLeaveMutex();
32558
32559   /* The reference count on pShmNode has already been incremented under
32560   ** the cover of the winShmEnterMutex() mutex and the pointer from the
32561   ** new (struct winShm) object to the pShmNode has been set. All that is
32562   ** left to do is to link the new object into the linked list starting
32563   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
32564   ** mutex.
32565   */
32566   sqlite3_mutex_enter(pShmNode->mutex);
32567   p->pNext = pShmNode->pFirst;
32568   pShmNode->pFirst = p;
32569   sqlite3_mutex_leave(pShmNode->mutex);
32570   return SQLITE_OK;
32571
32572   /* Jump here on any error */
32573 shm_open_err:
32574   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32575   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
32576   sqlite3_free(p);
32577   sqlite3_free(pNew);
32578   winShmLeaveMutex();
32579   return rc;
32580 }
32581
32582 /*
32583 ** Close a connection to shared-memory.  Delete the underlying 
32584 ** storage if deleteFlag is true.
32585 */
32586 static int winShmUnmap(
32587   sqlite3_file *fd,          /* Database holding shared memory */
32588   int deleteFlag             /* Delete after closing if true */
32589 ){
32590   winFile *pDbFd;       /* Database holding shared-memory */
32591   winShm *p;            /* The connection to be closed */
32592   winShmNode *pShmNode; /* The underlying shared-memory file */
32593   winShm **pp;          /* For looping over sibling connections */
32594
32595   pDbFd = (winFile*)fd;
32596   p = pDbFd->pShm;
32597   if( p==0 ) return SQLITE_OK;
32598   pShmNode = p->pShmNode;
32599
32600   /* Remove connection p from the set of connections associated
32601   ** with pShmNode */
32602   sqlite3_mutex_enter(pShmNode->mutex);
32603   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32604   *pp = p->pNext;
32605
32606   /* Free the connection p */
32607   sqlite3_free(p);
32608   pDbFd->pShm = 0;
32609   sqlite3_mutex_leave(pShmNode->mutex);
32610
32611   /* If pShmNode->nRef has reached 0, then close the underlying
32612   ** shared-memory file, too */
32613   winShmEnterMutex();
32614   assert( pShmNode->nRef>0 );
32615   pShmNode->nRef--;
32616   if( pShmNode->nRef==0 ){
32617     winShmPurge(pDbFd->pVfs, deleteFlag);
32618   }
32619   winShmLeaveMutex();
32620
32621   return SQLITE_OK;
32622 }
32623
32624 /*
32625 ** Change the lock state for a shared-memory segment.
32626 */
32627 static int winShmLock(
32628   sqlite3_file *fd,          /* Database file holding the shared memory */
32629   int ofst,                  /* First lock to acquire or release */
32630   int n,                     /* Number of locks to acquire or release */
32631   int flags                  /* What to do with the lock */
32632 ){
32633   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
32634   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
32635   winShm *pX;                           /* For looping over all siblings */
32636   winShmNode *pShmNode = p->pShmNode;
32637   int rc = SQLITE_OK;                   /* Result code */
32638   u16 mask;                             /* Mask of locks to take or release */
32639
32640   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32641   assert( n>=1 );
32642   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32643        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32644        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32645        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32646   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32647
32648   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32649   assert( n>1 || mask==(1<<ofst) );
32650   sqlite3_mutex_enter(pShmNode->mutex);
32651   if( flags & SQLITE_SHM_UNLOCK ){
32652     u16 allMask = 0; /* Mask of locks held by siblings */
32653
32654     /* See if any siblings hold this same lock */
32655     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32656       if( pX==p ) continue;
32657       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32658       allMask |= pX->sharedMask;
32659     }
32660
32661     /* Unlock the system-level locks */
32662     if( (mask & allMask)==0 ){
32663       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32664     }else{
32665       rc = SQLITE_OK;
32666     }
32667
32668     /* Undo the local locks */
32669     if( rc==SQLITE_OK ){
32670       p->exclMask &= ~mask;
32671       p->sharedMask &= ~mask;
32672     } 
32673   }else if( flags & SQLITE_SHM_SHARED ){
32674     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
32675
32676     /* Find out which shared locks are already held by sibling connections.
32677     ** If any sibling already holds an exclusive lock, go ahead and return
32678     ** SQLITE_BUSY.
32679     */
32680     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32681       if( (pX->exclMask & mask)!=0 ){
32682         rc = SQLITE_BUSY;
32683         break;
32684       }
32685       allShared |= pX->sharedMask;
32686     }
32687
32688     /* Get shared locks at the system level, if necessary */
32689     if( rc==SQLITE_OK ){
32690       if( (allShared & mask)==0 ){
32691         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
32692       }else{
32693         rc = SQLITE_OK;
32694       }
32695     }
32696
32697     /* Get the local shared locks */
32698     if( rc==SQLITE_OK ){
32699       p->sharedMask |= mask;
32700     }
32701   }else{
32702     /* Make sure no sibling connections hold locks that will block this
32703     ** lock.  If any do, return SQLITE_BUSY right away.
32704     */
32705     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32706       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
32707         rc = SQLITE_BUSY;
32708         break;
32709       }
32710     }
32711   
32712     /* Get the exclusive locks at the system level.  Then if successful
32713     ** also mark the local connection as being locked.
32714     */
32715     if( rc==SQLITE_OK ){
32716       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
32717       if( rc==SQLITE_OK ){
32718         assert( (p->sharedMask & mask)==0 );
32719         p->exclMask |= mask;
32720       }
32721     }
32722   }
32723   sqlite3_mutex_leave(pShmNode->mutex);
32724   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
32725            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
32726            rc ? "failed" : "ok"));
32727   return rc;
32728 }
32729
32730 /*
32731 ** Implement a memory barrier or memory fence on shared memory.  
32732 **
32733 ** All loads and stores begun before the barrier must complete before
32734 ** any load or store begun after the barrier.
32735 */
32736 static void winShmBarrier(
32737   sqlite3_file *fd          /* Database holding the shared memory */
32738 ){
32739   UNUSED_PARAMETER(fd);
32740   /* MemoryBarrier(); // does not work -- do not know why not */
32741   winShmEnterMutex();
32742   winShmLeaveMutex();
32743 }
32744
32745 /*
32746 ** This function is called to obtain a pointer to region iRegion of the 
32747 ** shared-memory associated with the database file fd. Shared-memory regions 
32748 ** are numbered starting from zero. Each shared-memory region is szRegion 
32749 ** bytes in size.
32750 **
32751 ** If an error occurs, an error code is returned and *pp is set to NULL.
32752 **
32753 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
32754 ** region has not been allocated (by any client, including one running in a
32755 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
32756 ** isWrite is non-zero and the requested shared-memory region has not yet 
32757 ** been allocated, it is allocated by this function.
32758 **
32759 ** If the shared-memory region has already been allocated or is allocated by
32760 ** this call as described above, then it is mapped into this processes 
32761 ** address space (if it is not already), *pp is set to point to the mapped 
32762 ** memory and SQLITE_OK returned.
32763 */
32764 static int winShmMap(
32765   sqlite3_file *fd,               /* Handle open on database file */
32766   int iRegion,                    /* Region to retrieve */
32767   int szRegion,                   /* Size of regions */
32768   int isWrite,                    /* True to extend file if necessary */
32769   void volatile **pp              /* OUT: Mapped memory */
32770 ){
32771   winFile *pDbFd = (winFile*)fd;
32772   winShm *p = pDbFd->pShm;
32773   winShmNode *pShmNode;
32774   int rc = SQLITE_OK;
32775
32776   if( !p ){
32777     rc = winOpenSharedMemory(pDbFd);
32778     if( rc!=SQLITE_OK ) return rc;
32779     p = pDbFd->pShm;
32780   }
32781   pShmNode = p->pShmNode;
32782
32783   sqlite3_mutex_enter(pShmNode->mutex);
32784   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
32785
32786   if( pShmNode->nRegion<=iRegion ){
32787     struct ShmRegion *apNew;           /* New aRegion[] array */
32788     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
32789     sqlite3_int64 sz;                  /* Current size of wal-index file */
32790
32791     pShmNode->szRegion = szRegion;
32792
32793     /* The requested region is not mapped into this processes address space.
32794     ** Check to see if it has been allocated (i.e. if the wal-index file is
32795     ** large enough to contain the requested region).
32796     */
32797     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
32798     if( rc!=SQLITE_OK ){
32799       rc = SQLITE_IOERR_SHMSIZE;
32800       goto shmpage_out;
32801     }
32802
32803     if( sz<nByte ){
32804       /* The requested memory region does not exist. If isWrite is set to
32805       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
32806       **
32807       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
32808       ** the requested memory region.
32809       */
32810       if( !isWrite ) goto shmpage_out;
32811       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
32812       if( rc!=SQLITE_OK ){
32813         rc = SQLITE_IOERR_SHMSIZE;
32814         goto shmpage_out;
32815       }
32816     }
32817
32818     /* Map the requested memory region into this processes address space. */
32819     apNew = (struct ShmRegion *)sqlite3_realloc(
32820         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
32821     );
32822     if( !apNew ){
32823       rc = SQLITE_IOERR_NOMEM;
32824       goto shmpage_out;
32825     }
32826     pShmNode->aRegion = apNew;
32827
32828     while( pShmNode->nRegion<=iRegion ){
32829       HANDLE hMap;                /* file-mapping handle */
32830       void *pMap = 0;             /* Mapped memory region */
32831      
32832       hMap = CreateFileMapping(pShmNode->hFile.h, 
32833           NULL, PAGE_READWRITE, 0, nByte, NULL
32834       );
32835       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
32836                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
32837                hMap ? "ok" : "failed"));
32838       if( hMap ){
32839         int iOffset = pShmNode->nRegion*szRegion;
32840         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32841         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
32842             0, iOffset - iOffsetShift, szRegion + iOffsetShift
32843         );
32844         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
32845                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
32846                  pMap ? "ok" : "failed"));
32847       }
32848       if( !pMap ){
32849         pShmNode->lastErrno = GetLastError();
32850         rc = SQLITE_IOERR;
32851         if( hMap ) CloseHandle(hMap);
32852         goto shmpage_out;
32853       }
32854
32855       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
32856       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
32857       pShmNode->nRegion++;
32858     }
32859   }
32860
32861 shmpage_out:
32862   if( pShmNode->nRegion>iRegion ){
32863     int iOffset = iRegion*szRegion;
32864     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32865     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
32866     *pp = (void *)&p[iOffsetShift];
32867   }else{
32868     *pp = 0;
32869   }
32870   sqlite3_mutex_leave(pShmNode->mutex);
32871   return rc;
32872 }
32873
32874 #else
32875 # define winShmMap     0
32876 # define winShmLock    0
32877 # define winShmBarrier 0
32878 # define winShmUnmap   0
32879 #endif /* #ifndef SQLITE_OMIT_WAL */
32880
32881 /*
32882 ** Here ends the implementation of all sqlite3_file methods.
32883 **
32884 ********************** End sqlite3_file Methods *******************************
32885 ******************************************************************************/
32886
32887 /*
32888 ** This vector defines all the methods that can operate on an
32889 ** sqlite3_file for win32.
32890 */
32891 static const sqlite3_io_methods winIoMethod = {
32892   2,                              /* iVersion */
32893   winClose,                       /* xClose */
32894   winRead,                        /* xRead */
32895   winWrite,                       /* xWrite */
32896   winTruncate,                    /* xTruncate */
32897   winSync,                        /* xSync */
32898   winFileSize,                    /* xFileSize */
32899   winLock,                        /* xLock */
32900   winUnlock,                      /* xUnlock */
32901   winCheckReservedLock,           /* xCheckReservedLock */
32902   winFileControl,                 /* xFileControl */
32903   winSectorSize,                  /* xSectorSize */
32904   winDeviceCharacteristics,       /* xDeviceCharacteristics */
32905   winShmMap,                      /* xShmMap */
32906   winShmLock,                     /* xShmLock */
32907   winShmBarrier,                  /* xShmBarrier */
32908   winShmUnmap                     /* xShmUnmap */
32909 };
32910
32911 /****************************************************************************
32912 **************************** sqlite3_vfs methods ****************************
32913 **
32914 ** This division contains the implementation of methods on the
32915 ** sqlite3_vfs object.
32916 */
32917
32918 /*
32919 ** Convert a UTF-8 filename into whatever form the underlying
32920 ** operating system wants filenames in.  Space to hold the result
32921 ** is obtained from malloc and must be freed by the calling
32922 ** function.
32923 */
32924 static void *convertUtf8Filename(const char *zFilename){
32925   void *zConverted = 0;
32926   if( isNT() ){
32927     zConverted = utf8ToUnicode(zFilename);
32928 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32929 */
32930 #if SQLITE_OS_WINCE==0
32931   }else{
32932     zConverted = utf8ToMbcs(zFilename);
32933 #endif
32934   }
32935   /* caller will handle out of memory */
32936   return zConverted;
32937 }
32938
32939 /*
32940 ** Create a temporary file name in zBuf.  zBuf must be big enough to
32941 ** hold at pVfs->mxPathname characters.
32942 */
32943 static int getTempname(int nBuf, char *zBuf){
32944   static char zChars[] =
32945     "abcdefghijklmnopqrstuvwxyz"
32946     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32947     "0123456789";
32948   size_t i, j;
32949   char zTempPath[MAX_PATH+1];
32950
32951   /* It's odd to simulate an io-error here, but really this is just
32952   ** using the io-error infrastructure to test that SQLite handles this
32953   ** function failing. 
32954   */
32955   SimulateIOError( return SQLITE_IOERR );
32956
32957   if( sqlite3_temp_directory ){
32958     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
32959   }else if( isNT() ){
32960     char *zMulti;
32961     WCHAR zWidePath[MAX_PATH];
32962     GetTempPathW(MAX_PATH-30, zWidePath);
32963     zMulti = unicodeToUtf8(zWidePath);
32964     if( zMulti ){
32965       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
32966       free(zMulti);
32967     }else{
32968       return SQLITE_NOMEM;
32969     }
32970 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32971 ** Since the ASCII version of these Windows API do not exist for WINCE,
32972 ** it's important to not reference them for WINCE builds.
32973 */
32974 #if SQLITE_OS_WINCE==0
32975   }else{
32976     char *zUtf8;
32977     char zMbcsPath[MAX_PATH];
32978     GetTempPathA(MAX_PATH-30, zMbcsPath);
32979     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
32980     if( zUtf8 ){
32981       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
32982       free(zUtf8);
32983     }else{
32984       return SQLITE_NOMEM;
32985     }
32986 #endif
32987   }
32988
32989   /* Check that the output buffer is large enough for the temporary file 
32990   ** name. If it is not, return SQLITE_ERROR.
32991   */
32992   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
32993     return SQLITE_ERROR;
32994   }
32995
32996   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
32997   zTempPath[i] = 0;
32998
32999   sqlite3_snprintf(nBuf-17, zBuf,
33000                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33001   j = sqlite3Strlen30(zBuf);
33002   sqlite3_randomness(15, &zBuf[j]);
33003   for(i=0; i<15; i++, j++){
33004     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33005   }
33006   zBuf[j] = 0;
33007
33008   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33009   return SQLITE_OK; 
33010 }
33011
33012 /*
33013 ** The return value of getLastErrorMsg
33014 ** is zero if the error message fits in the buffer, or non-zero
33015 ** otherwise (if the message was truncated).
33016 */
33017 static int getLastErrorMsg(int nBuf, char *zBuf){
33018   /* FormatMessage returns 0 on failure.  Otherwise it
33019   ** returns the number of TCHARs written to the output
33020   ** buffer, excluding the terminating null char.
33021   */
33022   DWORD error = GetLastError();
33023   DWORD dwLen = 0;
33024   char *zOut = 0;
33025
33026   if( isNT() ){
33027     WCHAR *zTempWide = NULL;
33028     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33029                            NULL,
33030                            error,
33031                            0,
33032                            (LPWSTR) &zTempWide,
33033                            0,
33034                            0);
33035     if( dwLen > 0 ){
33036       /* allocate a buffer and convert to UTF8 */
33037       zOut = unicodeToUtf8(zTempWide);
33038       /* free the system buffer allocated by FormatMessage */
33039       LocalFree(zTempWide);
33040     }
33041 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33042 ** Since the ASCII version of these Windows API do not exist for WINCE,
33043 ** it's important to not reference them for WINCE builds.
33044 */
33045 #if SQLITE_OS_WINCE==0
33046   }else{
33047     char *zTemp = NULL;
33048     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33049                            NULL,
33050                            error,
33051                            0,
33052                            (LPSTR) &zTemp,
33053                            0,
33054                            0);
33055     if( dwLen > 0 ){
33056       /* allocate a buffer and convert to UTF8 */
33057       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33058       /* free the system buffer allocated by FormatMessage */
33059       LocalFree(zTemp);
33060     }
33061 #endif
33062   }
33063   if( 0 == dwLen ){
33064     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
33065   }else{
33066     /* copy a maximum of nBuf chars to output buffer */
33067     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33068     /* free the UTF8 buffer */
33069     free(zOut);
33070   }
33071   return 0;
33072 }
33073
33074 /*
33075 ** Open a file.
33076 */
33077 static int winOpen(
33078   sqlite3_vfs *pVfs,        /* Not used */
33079   const char *zName,        /* Name of the file (UTF-8) */
33080   sqlite3_file *id,         /* Write the SQLite file handle here */
33081   int flags,                /* Open mode flags */
33082   int *pOutFlags            /* Status return flags */
33083 ){
33084   HANDLE h;
33085   DWORD dwDesiredAccess;
33086   DWORD dwShareMode;
33087   DWORD dwCreationDisposition;
33088   DWORD dwFlagsAndAttributes = 0;
33089 #if SQLITE_OS_WINCE
33090   int isTemp = 0;
33091 #endif
33092   winFile *pFile = (winFile*)id;
33093   void *zConverted;              /* Filename in OS encoding */
33094   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33095
33096   /* If argument zPath is a NULL pointer, this function is required to open
33097   ** a temporary file. Use this buffer to store the file name in.
33098   */
33099   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
33100
33101   int rc = SQLITE_OK;            /* Function Return Code */
33102 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33103   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33104 #endif
33105
33106   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33107   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33108   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33109 #ifndef NDEBUG
33110   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33111 #endif
33112   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33113
33114 #ifndef NDEBUG
33115   int isOpenJournal = (isCreate && (
33116         eType==SQLITE_OPEN_MASTER_JOURNAL 
33117      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33118      || eType==SQLITE_OPEN_WAL
33119   ));
33120 #endif
33121
33122   /* Check the following statements are true: 
33123   **
33124   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33125   **   (b) if CREATE is set, then READWRITE must also be set, and
33126   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33127   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33128   */
33129   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33130   assert(isCreate==0 || isReadWrite);
33131   assert(isExclusive==0 || isCreate);
33132   assert(isDelete==0 || isCreate);
33133
33134   /* The main DB, main journal, WAL file and master journal are never 
33135   ** automatically deleted. Nor are they ever temporary files.  */
33136   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33137   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33138   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33139   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33140
33141   /* Assert that the upper layer has set one of the "file-type" flags. */
33142   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33143        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33144        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33145        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33146   );
33147
33148   assert( id!=0 );
33149   UNUSED_PARAMETER(pVfs);
33150
33151   pFile->h = INVALID_HANDLE_VALUE;
33152
33153   /* If the second argument to this function is NULL, generate a 
33154   ** temporary file name to use 
33155   */
33156   if( !zUtf8Name ){
33157     assert(isDelete && !isOpenJournal);
33158     rc = getTempname(MAX_PATH+1, zTmpname);
33159     if( rc!=SQLITE_OK ){
33160       return rc;
33161     }
33162     zUtf8Name = zTmpname;
33163   }
33164
33165   /* Convert the filename to the system encoding. */
33166   zConverted = convertUtf8Filename(zUtf8Name);
33167   if( zConverted==0 ){
33168     return SQLITE_NOMEM;
33169   }
33170
33171   if( isReadWrite ){
33172     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33173   }else{
33174     dwDesiredAccess = GENERIC_READ;
33175   }
33176
33177   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33178   ** created. SQLite doesn't use it to indicate "exclusive access" 
33179   ** as it is usually understood.
33180   */
33181   if( isExclusive ){
33182     /* Creates a new file, only if it does not already exist. */
33183     /* If the file exists, it fails. */
33184     dwCreationDisposition = CREATE_NEW;
33185   }else if( isCreate ){
33186     /* Open existing file, or create if it doesn't exist */
33187     dwCreationDisposition = OPEN_ALWAYS;
33188   }else{
33189     /* Opens a file, only if it exists. */
33190     dwCreationDisposition = OPEN_EXISTING;
33191   }
33192
33193   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33194
33195   if( isDelete ){
33196 #if SQLITE_OS_WINCE
33197     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33198     isTemp = 1;
33199 #else
33200     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33201                                | FILE_ATTRIBUTE_HIDDEN
33202                                | FILE_FLAG_DELETE_ON_CLOSE;
33203 #endif
33204   }else{
33205     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33206   }
33207   /* Reports from the internet are that performance is always
33208   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33209 #if SQLITE_OS_WINCE
33210   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33211 #endif
33212
33213   if( isNT() ){
33214     h = CreateFileW((WCHAR*)zConverted,
33215        dwDesiredAccess,
33216        dwShareMode,
33217        NULL,
33218        dwCreationDisposition,
33219        dwFlagsAndAttributes,
33220        NULL
33221     );
33222 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33223 ** Since the ASCII version of these Windows API do not exist for WINCE,
33224 ** it's important to not reference them for WINCE builds.
33225 */
33226 #if SQLITE_OS_WINCE==0
33227   }else{
33228     h = CreateFileA((char*)zConverted,
33229        dwDesiredAccess,
33230        dwShareMode,
33231        NULL,
33232        dwCreationDisposition,
33233        dwFlagsAndAttributes,
33234        NULL
33235     );
33236 #endif
33237   }
33238
33239   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33240            h, zName, dwDesiredAccess, 
33241            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33242
33243   if( h==INVALID_HANDLE_VALUE ){
33244     pFile->lastErrno = GetLastError();
33245     free(zConverted);
33246     if( isReadWrite ){
33247       return winOpen(pVfs, zName, id, 
33248              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33249     }else{
33250       return SQLITE_CANTOPEN_BKPT;
33251     }
33252   }
33253
33254   if( pOutFlags ){
33255     if( isReadWrite ){
33256       *pOutFlags = SQLITE_OPEN_READWRITE;
33257     }else{
33258       *pOutFlags = SQLITE_OPEN_READONLY;
33259     }
33260   }
33261
33262   memset(pFile, 0, sizeof(*pFile));
33263   pFile->pMethod = &winIoMethod;
33264   pFile->h = h;
33265   pFile->lastErrno = NO_ERROR;
33266   pFile->pVfs = pVfs;
33267   pFile->pShm = 0;
33268   pFile->zPath = zName;
33269   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33270
33271 #if SQLITE_OS_WINCE
33272   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33273        && !winceCreateLock(zName, pFile)
33274   ){
33275     CloseHandle(h);
33276     free(zConverted);
33277     return SQLITE_CANTOPEN_BKPT;
33278   }
33279   if( isTemp ){
33280     pFile->zDeleteOnClose = zConverted;
33281   }else
33282 #endif
33283   {
33284     free(zConverted);
33285   }
33286
33287   OpenCounter(+1);
33288   return rc;
33289 }
33290
33291 /*
33292 ** Delete the named file.
33293 **
33294 ** Note that windows does not allow a file to be deleted if some other
33295 ** process has it open.  Sometimes a virus scanner or indexing program
33296 ** will open a journal file shortly after it is created in order to do
33297 ** whatever it does.  While this other process is holding the
33298 ** file open, we will be unable to delete it.  To work around this
33299 ** problem, we delay 100 milliseconds and try to delete again.  Up
33300 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33301 ** up and returning an error.
33302 */
33303 #define MX_DELETION_ATTEMPTS 5
33304 static int winDelete(
33305   sqlite3_vfs *pVfs,          /* Not used on win32 */
33306   const char *zFilename,      /* Name of file to delete */
33307   int syncDir                 /* Not used on win32 */
33308 ){
33309   int cnt = 0;
33310   DWORD rc;
33311   DWORD error = 0;
33312   void *zConverted;
33313   UNUSED_PARAMETER(pVfs);
33314   UNUSED_PARAMETER(syncDir);
33315
33316   SimulateIOError(return SQLITE_IOERR_DELETE);
33317   zConverted = convertUtf8Filename(zFilename);
33318   if( zConverted==0 ){
33319     return SQLITE_NOMEM;
33320   }
33321   if( isNT() ){
33322     do{
33323       DeleteFileW(zConverted);
33324     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33325                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33326            && (++cnt < MX_DELETION_ATTEMPTS)
33327            && (Sleep(100), 1) );
33328 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33329 ** Since the ASCII version of these Windows API do not exist for WINCE,
33330 ** it's important to not reference them for WINCE builds.
33331 */
33332 #if SQLITE_OS_WINCE==0
33333   }else{
33334     do{
33335       DeleteFileA(zConverted);
33336     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33337                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33338            && (++cnt < MX_DELETION_ATTEMPTS)
33339            && (Sleep(100), 1) );
33340 #endif
33341   }
33342   free(zConverted);
33343   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33344        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33345          "ok" : "failed" ));
33346  
33347   return (   (rc == INVALID_FILE_ATTRIBUTES) 
33348           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
33349 }
33350
33351 /*
33352 ** Check the existance and status of a file.
33353 */
33354 static int winAccess(
33355   sqlite3_vfs *pVfs,         /* Not used on win32 */
33356   const char *zFilename,     /* Name of file to check */
33357   int flags,                 /* Type of test to make on this file */
33358   int *pResOut               /* OUT: Result */
33359 ){
33360   DWORD attr;
33361   int rc = 0;
33362   void *zConverted;
33363   UNUSED_PARAMETER(pVfs);
33364
33365   SimulateIOError( return SQLITE_IOERR_ACCESS; );
33366   zConverted = convertUtf8Filename(zFilename);
33367   if( zConverted==0 ){
33368     return SQLITE_NOMEM;
33369   }
33370   if( isNT() ){
33371     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33372     memset(&sAttrData, 0, sizeof(sAttrData));
33373     if( GetFileAttributesExW((WCHAR*)zConverted,
33374                              GetFileExInfoStandard, 
33375                              &sAttrData) ){
33376       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33377       ** as if it does not exist.
33378       */
33379       if(    flags==SQLITE_ACCESS_EXISTS
33380           && sAttrData.nFileSizeHigh==0 
33381           && sAttrData.nFileSizeLow==0 ){
33382         attr = INVALID_FILE_ATTRIBUTES;
33383       }else{
33384         attr = sAttrData.dwFileAttributes;
33385       }
33386     }else{
33387       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33388         free(zConverted);
33389         return SQLITE_IOERR_ACCESS;
33390       }else{
33391         attr = INVALID_FILE_ATTRIBUTES;
33392       }
33393     }
33394 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33395 ** Since the ASCII version of these Windows API do not exist for WINCE,
33396 ** it's important to not reference them for WINCE builds.
33397 */
33398 #if SQLITE_OS_WINCE==0
33399   }else{
33400     attr = GetFileAttributesA((char*)zConverted);
33401 #endif
33402   }
33403   free(zConverted);
33404   switch( flags ){
33405     case SQLITE_ACCESS_READ:
33406     case SQLITE_ACCESS_EXISTS:
33407       rc = attr!=INVALID_FILE_ATTRIBUTES;
33408       break;
33409     case SQLITE_ACCESS_READWRITE:
33410       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33411       break;
33412     default:
33413       assert(!"Invalid flags argument");
33414   }
33415   *pResOut = rc;
33416   return SQLITE_OK;
33417 }
33418
33419
33420 /*
33421 ** Turn a relative pathname into a full pathname.  Write the full
33422 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
33423 ** bytes in size.
33424 */
33425 static int winFullPathname(
33426   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
33427   const char *zRelative,        /* Possibly relative input path */
33428   int nFull,                    /* Size of output buffer in bytes */
33429   char *zFull                   /* Output buffer */
33430 ){
33431   
33432 #if defined(__CYGWIN__)
33433   SimulateIOError( return SQLITE_ERROR );
33434   UNUSED_PARAMETER(nFull);
33435   cygwin_conv_to_full_win32_path(zRelative, zFull);
33436   return SQLITE_OK;
33437 #endif
33438
33439 #if SQLITE_OS_WINCE
33440   SimulateIOError( return SQLITE_ERROR );
33441   UNUSED_PARAMETER(nFull);
33442   /* WinCE has no concept of a relative pathname, or so I am told. */
33443   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33444   return SQLITE_OK;
33445 #endif
33446
33447 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33448   int nByte;
33449   void *zConverted;
33450   char *zOut;
33451
33452   /* It's odd to simulate an io-error here, but really this is just
33453   ** using the io-error infrastructure to test that SQLite handles this
33454   ** function failing. This function could fail if, for example, the
33455   ** current working directory has been unlinked.
33456   */
33457   SimulateIOError( return SQLITE_ERROR );
33458   UNUSED_PARAMETER(nFull);
33459   zConverted = convertUtf8Filename(zRelative);
33460   if( isNT() ){
33461     WCHAR *zTemp;
33462     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33463     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33464     if( zTemp==0 ){
33465       free(zConverted);
33466       return SQLITE_NOMEM;
33467     }
33468     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33469     free(zConverted);
33470     zOut = unicodeToUtf8(zTemp);
33471     free(zTemp);
33472 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33473 ** Since the ASCII version of these Windows API do not exist for WINCE,
33474 ** it's important to not reference them for WINCE builds.
33475 */
33476 #if SQLITE_OS_WINCE==0
33477   }else{
33478     char *zTemp;
33479     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33480     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33481     if( zTemp==0 ){
33482       free(zConverted);
33483       return SQLITE_NOMEM;
33484     }
33485     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33486     free(zConverted);
33487     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33488     free(zTemp);
33489 #endif
33490   }
33491   if( zOut ){
33492     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33493     free(zOut);
33494     return SQLITE_OK;
33495   }else{
33496     return SQLITE_NOMEM;
33497   }
33498 #endif
33499 }
33500
33501 /*
33502 ** Get the sector size of the device used to store
33503 ** file.
33504 */
33505 static int getSectorSize(
33506     sqlite3_vfs *pVfs,
33507     const char *zRelative     /* UTF-8 file name */
33508 ){
33509   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33510   /* GetDiskFreeSpace is not supported under WINCE */
33511 #if SQLITE_OS_WINCE
33512   UNUSED_PARAMETER(pVfs);
33513   UNUSED_PARAMETER(zRelative);
33514 #else
33515   char zFullpath[MAX_PATH+1];
33516   int rc;
33517   DWORD dwRet = 0;
33518   DWORD dwDummy;
33519
33520   /*
33521   ** We need to get the full path name of the file
33522   ** to get the drive letter to look up the sector
33523   ** size.
33524   */
33525   SimulateIOErrorBenign(1);
33526   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33527   SimulateIOErrorBenign(0);
33528   if( rc == SQLITE_OK )
33529   {
33530     void *zConverted = convertUtf8Filename(zFullpath);
33531     if( zConverted ){
33532       if( isNT() ){
33533         /* trim path to just drive reference */
33534         WCHAR *p = zConverted;
33535         for(;*p;p++){
33536           if( *p == '\\' ){
33537             *p = '\0';
33538             break;
33539           }
33540         }
33541         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33542                                   &dwDummy,
33543                                   &bytesPerSector,
33544                                   &dwDummy,
33545                                   &dwDummy);
33546       }else{
33547         /* trim path to just drive reference */
33548         char *p = (char *)zConverted;
33549         for(;*p;p++){
33550           if( *p == '\\' ){
33551             *p = '\0';
33552             break;
33553           }
33554         }
33555         dwRet = GetDiskFreeSpaceA((char*)zConverted,
33556                                   &dwDummy,
33557                                   &bytesPerSector,
33558                                   &dwDummy,
33559                                   &dwDummy);
33560       }
33561       free(zConverted);
33562     }
33563     if( !dwRet ){
33564       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33565     }
33566   }
33567 #endif
33568   return (int) bytesPerSector; 
33569 }
33570
33571 #ifndef SQLITE_OMIT_LOAD_EXTENSION
33572 /*
33573 ** Interfaces for opening a shared library, finding entry points
33574 ** within the shared library, and closing the shared library.
33575 */
33576 /*
33577 ** Interfaces for opening a shared library, finding entry points
33578 ** within the shared library, and closing the shared library.
33579 */
33580 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33581   HANDLE h;
33582   void *zConverted = convertUtf8Filename(zFilename);
33583   UNUSED_PARAMETER(pVfs);
33584   if( zConverted==0 ){
33585     return 0;
33586   }
33587   if( isNT() ){
33588     h = LoadLibraryW((WCHAR*)zConverted);
33589 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33590 ** Since the ASCII version of these Windows API do not exist for WINCE,
33591 ** it's important to not reference them for WINCE builds.
33592 */
33593 #if SQLITE_OS_WINCE==0
33594   }else{
33595     h = LoadLibraryA((char*)zConverted);
33596 #endif
33597   }
33598   free(zConverted);
33599   return (void*)h;
33600 }
33601 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
33602   UNUSED_PARAMETER(pVfs);
33603   getLastErrorMsg(nBuf, zBufOut);
33604 }
33605 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
33606   UNUSED_PARAMETER(pVfs);
33607 #if SQLITE_OS_WINCE
33608   /* The GetProcAddressA() routine is only available on wince. */
33609   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
33610 #else
33611   /* All other windows platforms expect GetProcAddress() to take
33612   ** an Ansi string regardless of the _UNICODE setting */
33613   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
33614 #endif
33615 }
33616 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
33617   UNUSED_PARAMETER(pVfs);
33618   FreeLibrary((HANDLE)pHandle);
33619 }
33620 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
33621   #define winDlOpen  0
33622   #define winDlError 0
33623   #define winDlSym   0
33624   #define winDlClose 0
33625 #endif
33626
33627
33628 /*
33629 ** Write up to nBuf bytes of randomness into zBuf.
33630 */
33631 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33632   int n = 0;
33633   UNUSED_PARAMETER(pVfs);
33634 #if defined(SQLITE_TEST)
33635   n = nBuf;
33636   memset(zBuf, 0, nBuf);
33637 #else
33638   if( sizeof(SYSTEMTIME)<=nBuf-n ){
33639     SYSTEMTIME x;
33640     GetSystemTime(&x);
33641     memcpy(&zBuf[n], &x, sizeof(x));
33642     n += sizeof(x);
33643   }
33644   if( sizeof(DWORD)<=nBuf-n ){
33645     DWORD pid = GetCurrentProcessId();
33646     memcpy(&zBuf[n], &pid, sizeof(pid));
33647     n += sizeof(pid);
33648   }
33649   if( sizeof(DWORD)<=nBuf-n ){
33650     DWORD cnt = GetTickCount();
33651     memcpy(&zBuf[n], &cnt, sizeof(cnt));
33652     n += sizeof(cnt);
33653   }
33654   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
33655     LARGE_INTEGER i;
33656     QueryPerformanceCounter(&i);
33657     memcpy(&zBuf[n], &i, sizeof(i));
33658     n += sizeof(i);
33659   }
33660 #endif
33661   return n;
33662 }
33663
33664
33665 /*
33666 ** Sleep for a little while.  Return the amount of time slept.
33667 */
33668 static int winSleep(sqlite3_vfs *pVfs, int microsec){
33669   Sleep((microsec+999)/1000);
33670   UNUSED_PARAMETER(pVfs);
33671   return ((microsec+999)/1000)*1000;
33672 }
33673
33674 /*
33675 ** The following variable, if set to a non-zero value, is interpreted as
33676 ** the number of seconds since 1970 and is used to set the result of
33677 ** sqlite3OsCurrentTime() during testing.
33678 */
33679 #ifdef SQLITE_TEST
33680 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
33681 #endif
33682
33683 /*
33684 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
33685 ** the current time and date as a Julian Day number times 86_400_000.  In
33686 ** other words, write into *piNow the number of milliseconds since the Julian
33687 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
33688 ** proleptic Gregorian calendar.
33689 **
33690 ** On success, return 0.  Return 1 if the time and date cannot be found.
33691 */
33692 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
33693   /* FILETIME structure is a 64-bit value representing the number of 
33694      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
33695   */
33696   FILETIME ft;
33697   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
33698 #ifdef SQLITE_TEST
33699   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
33700 #endif
33701   /* 2^32 - to avoid use of LL and warnings in gcc */
33702   static const sqlite3_int64 max32BitValue = 
33703       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
33704
33705 #if SQLITE_OS_WINCE
33706   SYSTEMTIME time;
33707   GetSystemTime(&time);
33708   /* if SystemTimeToFileTime() fails, it returns zero. */
33709   if (!SystemTimeToFileTime(&time,&ft)){
33710     return 1;
33711   }
33712 #else
33713   GetSystemTimeAsFileTime( &ft );
33714 #endif
33715
33716   *piNow = winFiletimeEpoch +
33717             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
33718                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
33719
33720 #ifdef SQLITE_TEST
33721   if( sqlite3_current_time ){
33722     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
33723   }
33724 #endif
33725   UNUSED_PARAMETER(pVfs);
33726   return 0;
33727 }
33728
33729 /*
33730 ** Find the current time (in Universal Coordinated Time).  Write the
33731 ** current time and date as a Julian Day number into *prNow and
33732 ** return 0.  Return 1 if the time and date cannot be found.
33733 */
33734 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
33735   int rc;
33736   sqlite3_int64 i;
33737   rc = winCurrentTimeInt64(pVfs, &i);
33738   if( !rc ){
33739     *prNow = i/86400000.0;
33740   }
33741   return rc;
33742 }
33743
33744 /*
33745 ** The idea is that this function works like a combination of
33746 ** GetLastError() and FormatMessage() on windows (or errno and
33747 ** strerror_r() on unix). After an error is returned by an OS
33748 ** function, SQLite calls this function with zBuf pointing to
33749 ** a buffer of nBuf bytes. The OS layer should populate the
33750 ** buffer with a nul-terminated UTF-8 encoded error message
33751 ** describing the last IO error to have occurred within the calling
33752 ** thread.
33753 **
33754 ** If the error message is too large for the supplied buffer,
33755 ** it should be truncated. The return value of xGetLastError
33756 ** is zero if the error message fits in the buffer, or non-zero
33757 ** otherwise (if the message was truncated). If non-zero is returned,
33758 ** then it is not necessary to include the nul-terminator character
33759 ** in the output buffer.
33760 **
33761 ** Not supplying an error message will have no adverse effect
33762 ** on SQLite. It is fine to have an implementation that never
33763 ** returns an error message:
33764 **
33765 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33766 **     assert(zBuf[0]=='\0');
33767 **     return 0;
33768 **   }
33769 **
33770 ** However if an error message is supplied, it will be incorporated
33771 ** by sqlite into the error message available to the user using
33772 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
33773 */
33774 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33775   UNUSED_PARAMETER(pVfs);
33776   return getLastErrorMsg(nBuf, zBuf);
33777 }
33778
33779
33780
33781 /*
33782 ** Initialize and deinitialize the operating system interface.
33783 */
33784 SQLITE_API int sqlite3_os_init(void){
33785   static sqlite3_vfs winVfs = {
33786     3,                   /* iVersion */
33787     sizeof(winFile),     /* szOsFile */
33788     MAX_PATH,            /* mxPathname */
33789     0,                   /* pNext */
33790     "win32",             /* zName */
33791     0,                   /* pAppData */
33792     winOpen,             /* xOpen */
33793     winDelete,           /* xDelete */
33794     winAccess,           /* xAccess */
33795     winFullPathname,     /* xFullPathname */
33796     winDlOpen,           /* xDlOpen */
33797     winDlError,          /* xDlError */
33798     winDlSym,            /* xDlSym */
33799     winDlClose,          /* xDlClose */
33800     winRandomness,       /* xRandomness */
33801     winSleep,            /* xSleep */
33802     winCurrentTime,      /* xCurrentTime */
33803     winGetLastError,     /* xGetLastError */
33804     winCurrentTimeInt64, /* xCurrentTimeInt64 */
33805     0,                   /* xSetSystemCall */
33806     0,                   /* xGetSystemCall */
33807     0,                   /* xNextSystemCall */
33808   };
33809
33810 #ifndef SQLITE_OMIT_WAL
33811   /* get memory map allocation granularity */
33812   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
33813   GetSystemInfo(&winSysInfo);
33814   assert(winSysInfo.dwAllocationGranularity > 0);
33815 #endif
33816
33817   sqlite3_vfs_register(&winVfs, 1);
33818   return SQLITE_OK; 
33819 }
33820 SQLITE_API int sqlite3_os_end(void){ 
33821   return SQLITE_OK;
33822 }
33823
33824 #endif /* SQLITE_OS_WIN */
33825
33826 /************** End of os_win.c **********************************************/
33827 /************** Begin file bitvec.c ******************************************/
33828 /*
33829 ** 2008 February 16
33830 **
33831 ** The author disclaims copyright to this source code.  In place of
33832 ** a legal notice, here is a blessing:
33833 **
33834 **    May you do good and not evil.
33835 **    May you find forgiveness for yourself and forgive others.
33836 **    May you share freely, never taking more than you give.
33837 **
33838 *************************************************************************
33839 ** This file implements an object that represents a fixed-length
33840 ** bitmap.  Bits are numbered starting with 1.
33841 **
33842 ** A bitmap is used to record which pages of a database file have been
33843 ** journalled during a transaction, or which pages have the "dont-write"
33844 ** property.  Usually only a few pages are meet either condition.
33845 ** So the bitmap is usually sparse and has low cardinality.
33846 ** But sometimes (for example when during a DROP of a large table) most
33847 ** or all of the pages in a database can get journalled.  In those cases, 
33848 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
33849 ** to handle both cases well.
33850 **
33851 ** The size of the bitmap is fixed when the object is created.
33852 **
33853 ** All bits are clear when the bitmap is created.  Individual bits
33854 ** may be set or cleared one at a time.
33855 **
33856 ** Test operations are about 100 times more common that set operations.
33857 ** Clear operations are exceedingly rare.  There are usually between
33858 ** 5 and 500 set operations per Bitvec object, though the number of sets can
33859 ** sometimes grow into tens of thousands or larger.  The size of the
33860 ** Bitvec object is the number of pages in the database file at the
33861 ** start of a transaction, and is thus usually less than a few thousand,
33862 ** but can be as large as 2 billion for a really big database.
33863 */
33864
33865 /* Size of the Bitvec structure in bytes. */
33866 #define BITVEC_SZ        512
33867
33868 /* Round the union size down to the nearest pointer boundary, since that's how 
33869 ** it will be aligned within the Bitvec struct. */
33870 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
33871
33872 /* Type of the array "element" for the bitmap representation. 
33873 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
33874 ** Setting this to the "natural word" size of your CPU may improve
33875 ** performance. */
33876 #define BITVEC_TELEM     u8
33877 /* Size, in bits, of the bitmap element. */
33878 #define BITVEC_SZELEM    8
33879 /* Number of elements in a bitmap array. */
33880 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
33881 /* Number of bits in the bitmap array. */
33882 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
33883
33884 /* Number of u32 values in hash table. */
33885 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
33886 /* Maximum number of entries in hash table before 
33887 ** sub-dividing and re-hashing. */
33888 #define BITVEC_MXHASH    (BITVEC_NINT/2)
33889 /* Hashing function for the aHash representation.
33890 ** Empirical testing showed that the *37 multiplier 
33891 ** (an arbitrary prime)in the hash function provided 
33892 ** no fewer collisions than the no-op *1. */
33893 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
33894
33895 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
33896
33897
33898 /*
33899 ** A bitmap is an instance of the following structure.
33900 **
33901 ** This bitmap records the existance of zero or more bits
33902 ** with values between 1 and iSize, inclusive.
33903 **
33904 ** There are three possible representations of the bitmap.
33905 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
33906 ** bitmap.  The least significant bit is bit 1.
33907 **
33908 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
33909 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
33910 **
33911 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
33912 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
33913 ** handles up to iDivisor separate values of i.  apSub[0] holds
33914 ** values between 1 and iDivisor.  apSub[1] holds values between
33915 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
33916 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
33917 ** to hold deal with values between 1 and iDivisor.
33918 */
33919 struct Bitvec {
33920   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
33921   u32 nSet;       /* Number of bits that are set - only valid for aHash
33922                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
33923                   ** this would be 125. */
33924   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
33925                   /* Should >=0 for apSub element. */
33926                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
33927                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
33928   union {
33929     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
33930     u32 aHash[BITVEC_NINT];      /* Hash table representation */
33931     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
33932   } u;
33933 };
33934
33935 /*
33936 ** Create a new bitmap object able to handle bits between 0 and iSize,
33937 ** inclusive.  Return a pointer to the new object.  Return NULL if 
33938 ** malloc fails.
33939 */
33940 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
33941   Bitvec *p;
33942   assert( sizeof(*p)==BITVEC_SZ );
33943   p = sqlite3MallocZero( sizeof(*p) );
33944   if( p ){
33945     p->iSize = iSize;
33946   }
33947   return p;
33948 }
33949
33950 /*
33951 ** Check to see if the i-th bit is set.  Return true or false.
33952 ** If p is NULL (if the bitmap has not been created) or if
33953 ** i is out of range, then return false.
33954 */
33955 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
33956   if( p==0 ) return 0;
33957   if( i>p->iSize || i==0 ) return 0;
33958   i--;
33959   while( p->iDivisor ){
33960     u32 bin = i/p->iDivisor;
33961     i = i%p->iDivisor;
33962     p = p->u.apSub[bin];
33963     if (!p) {
33964       return 0;
33965     }
33966   }
33967   if( p->iSize<=BITVEC_NBIT ){
33968     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
33969   } else{
33970     u32 h = BITVEC_HASH(i++);
33971     while( p->u.aHash[h] ){
33972       if( p->u.aHash[h]==i ) return 1;
33973       h = (h+1) % BITVEC_NINT;
33974     }
33975     return 0;
33976   }
33977 }
33978
33979 /*
33980 ** Set the i-th bit.  Return 0 on success and an error code if
33981 ** anything goes wrong.
33982 **
33983 ** This routine might cause sub-bitmaps to be allocated.  Failing
33984 ** to get the memory needed to hold the sub-bitmap is the only
33985 ** that can go wrong with an insert, assuming p and i are valid.
33986 **
33987 ** The calling function must ensure that p is a valid Bitvec object
33988 ** and that the value for "i" is within range of the Bitvec object.
33989 ** Otherwise the behavior is undefined.
33990 */
33991 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
33992   u32 h;
33993   if( p==0 ) return SQLITE_OK;
33994   assert( i>0 );
33995   assert( i<=p->iSize );
33996   i--;
33997   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
33998     u32 bin = i/p->iDivisor;
33999     i = i%p->iDivisor;
34000     if( p->u.apSub[bin]==0 ){
34001       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34002       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34003     }
34004     p = p->u.apSub[bin];
34005   }
34006   if( p->iSize<=BITVEC_NBIT ){
34007     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34008     return SQLITE_OK;
34009   }
34010   h = BITVEC_HASH(i++);
34011   /* if there wasn't a hash collision, and this doesn't */
34012   /* completely fill the hash, then just add it without */
34013   /* worring about sub-dividing and re-hashing. */
34014   if( !p->u.aHash[h] ){
34015     if (p->nSet<(BITVEC_NINT-1)) {
34016       goto bitvec_set_end;
34017     } else {
34018       goto bitvec_set_rehash;
34019     }
34020   }
34021   /* there was a collision, check to see if it's already */
34022   /* in hash, if not, try to find a spot for it */
34023   do {
34024     if( p->u.aHash[h]==i ) return SQLITE_OK;
34025     h++;
34026     if( h>=BITVEC_NINT ) h = 0;
34027   } while( p->u.aHash[h] );
34028   /* we didn't find it in the hash.  h points to the first */
34029   /* available free spot. check to see if this is going to */
34030   /* make our hash too "full".  */
34031 bitvec_set_rehash:
34032   if( p->nSet>=BITVEC_MXHASH ){
34033     unsigned int j;
34034     int rc;
34035     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34036     if( aiValues==0 ){
34037       return SQLITE_NOMEM;
34038     }else{
34039       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34040       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34041       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34042       rc = sqlite3BitvecSet(p, i);
34043       for(j=0; j<BITVEC_NINT; j++){
34044         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34045       }
34046       sqlite3StackFree(0, aiValues);
34047       return rc;
34048     }
34049   }
34050 bitvec_set_end:
34051   p->nSet++;
34052   p->u.aHash[h] = i;
34053   return SQLITE_OK;
34054 }
34055
34056 /*
34057 ** Clear the i-th bit.
34058 **
34059 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34060 ** that BitvecClear can use to rebuilt its hash table.
34061 */
34062 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34063   if( p==0 ) return;
34064   assert( i>0 );
34065   i--;
34066   while( p->iDivisor ){
34067     u32 bin = i/p->iDivisor;
34068     i = i%p->iDivisor;
34069     p = p->u.apSub[bin];
34070     if (!p) {
34071       return;
34072     }
34073   }
34074   if( p->iSize<=BITVEC_NBIT ){
34075     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34076   }else{
34077     unsigned int j;
34078     u32 *aiValues = pBuf;
34079     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34080     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34081     p->nSet = 0;
34082     for(j=0; j<BITVEC_NINT; j++){
34083       if( aiValues[j] && aiValues[j]!=(i+1) ){
34084         u32 h = BITVEC_HASH(aiValues[j]-1);
34085         p->nSet++;
34086         while( p->u.aHash[h] ){
34087           h++;
34088           if( h>=BITVEC_NINT ) h = 0;
34089         }
34090         p->u.aHash[h] = aiValues[j];
34091       }
34092     }
34093   }
34094 }
34095
34096 /*
34097 ** Destroy a bitmap object.  Reclaim all memory used.
34098 */
34099 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34100   if( p==0 ) return;
34101   if( p->iDivisor ){
34102     unsigned int i;
34103     for(i=0; i<BITVEC_NPTR; i++){
34104       sqlite3BitvecDestroy(p->u.apSub[i]);
34105     }
34106   }
34107   sqlite3_free(p);
34108 }
34109
34110 /*
34111 ** Return the value of the iSize parameter specified when Bitvec *p
34112 ** was created.
34113 */
34114 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34115   return p->iSize;
34116 }
34117
34118 #ifndef SQLITE_OMIT_BUILTIN_TEST
34119 /*
34120 ** Let V[] be an array of unsigned characters sufficient to hold
34121 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34122 ** Then the following macros can be used to set, clear, or test
34123 ** individual bits within V.
34124 */
34125 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34126 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34127 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34128
34129 /*
34130 ** This routine runs an extensive test of the Bitvec code.
34131 **
34132 ** The input is an array of integers that acts as a program
34133 ** to test the Bitvec.  The integers are opcodes followed
34134 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34135 ** opcode follows immediately after the last operand.
34136 **
34137 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34138 ** "halt" opcode and causes the test to end.
34139 **
34140 **    0          Halt and return the number of errors
34141 **    1 N S X    Set N bits beginning with S and incrementing by X
34142 **    2 N S X    Clear N bits beginning with S and incrementing by X
34143 **    3 N        Set N randomly chosen bits
34144 **    4 N        Clear N randomly chosen bits
34145 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
34146 **
34147 ** The opcodes 1 through 4 perform set and clear operations are performed
34148 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34149 ** Opcode 5 works on the linear array only, not on the Bitvec.
34150 ** Opcode 5 is used to deliberately induce a fault in order to
34151 ** confirm that error detection works.
34152 **
34153 ** At the conclusion of the test the linear array is compared
34154 ** against the Bitvec object.  If there are any differences,
34155 ** an error is returned.  If they are the same, zero is returned.
34156 **
34157 ** If a memory allocation error occurs, return -1.
34158 */
34159 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34160   Bitvec *pBitvec = 0;
34161   unsigned char *pV = 0;
34162   int rc = -1;
34163   int i, nx, pc, op;
34164   void *pTmpSpace;
34165
34166   /* Allocate the Bitvec to be tested and a linear array of
34167   ** bits to act as the reference */
34168   pBitvec = sqlite3BitvecCreate( sz );
34169   pV = sqlite3_malloc( (sz+7)/8 + 1 );
34170   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34171   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34172   memset(pV, 0, (sz+7)/8 + 1);
34173
34174   /* NULL pBitvec tests */
34175   sqlite3BitvecSet(0, 1);
34176   sqlite3BitvecClear(0, 1, pTmpSpace);
34177
34178   /* Run the program */
34179   pc = 0;
34180   while( (op = aOp[pc])!=0 ){
34181     switch( op ){
34182       case 1:
34183       case 2:
34184       case 5: {
34185         nx = 4;
34186         i = aOp[pc+2] - 1;
34187         aOp[pc+2] += aOp[pc+3];
34188         break;
34189       }
34190       case 3:
34191       case 4: 
34192       default: {
34193         nx = 2;
34194         sqlite3_randomness(sizeof(i), &i);
34195         break;
34196       }
34197     }
34198     if( (--aOp[pc+1]) > 0 ) nx = 0;
34199     pc += nx;
34200     i = (i & 0x7fffffff)%sz;
34201     if( (op & 1)!=0 ){
34202       SETBIT(pV, (i+1));
34203       if( op!=5 ){
34204         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34205       }
34206     }else{
34207       CLEARBIT(pV, (i+1));
34208       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34209     }
34210   }
34211
34212   /* Test to make sure the linear array exactly matches the
34213   ** Bitvec object.  Start with the assumption that they do
34214   ** match (rc==0).  Change rc to non-zero if a discrepancy
34215   ** is found.
34216   */
34217   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34218           + sqlite3BitvecTest(pBitvec, 0)
34219           + (sqlite3BitvecSize(pBitvec) - sz);
34220   for(i=1; i<=sz; i++){
34221     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34222       rc = i;
34223       break;
34224     }
34225   }
34226
34227   /* Free allocated structure */
34228 bitvec_end:
34229   sqlite3_free(pTmpSpace);
34230   sqlite3_free(pV);
34231   sqlite3BitvecDestroy(pBitvec);
34232   return rc;
34233 }
34234 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34235
34236 /************** End of bitvec.c **********************************************/
34237 /************** Begin file pcache.c ******************************************/
34238 /*
34239 ** 2008 August 05
34240 **
34241 ** The author disclaims copyright to this source code.  In place of
34242 ** a legal notice, here is a blessing:
34243 **
34244 **    May you do good and not evil.
34245 **    May you find forgiveness for yourself and forgive others.
34246 **    May you share freely, never taking more than you give.
34247 **
34248 *************************************************************************
34249 ** This file implements that page cache.
34250 */
34251
34252 /*
34253 ** A complete page cache is an instance of this structure.
34254 */
34255 struct PCache {
34256   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
34257   PgHdr *pSynced;                     /* Last synced page in dirty page list */
34258   int nRef;                           /* Number of referenced pages */
34259   int nMax;                           /* Configured cache size */
34260   int szPage;                         /* Size of every page in this cache */
34261   int szExtra;                        /* Size of extra space for each page */
34262   int bPurgeable;                     /* True if pages are on backing store */
34263   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
34264   void *pStress;                      /* Argument to xStress */
34265   sqlite3_pcache *pCache;             /* Pluggable cache module */
34266   PgHdr *pPage1;                      /* Reference to page 1 */
34267 };
34268
34269 /*
34270 ** Some of the assert() macros in this code are too expensive to run
34271 ** even during normal debugging.  Use them only rarely on long-running
34272 ** tests.  Enable the expensive asserts using the
34273 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34274 */
34275 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34276 # define expensive_assert(X)  assert(X)
34277 #else
34278 # define expensive_assert(X)
34279 #endif
34280
34281 /********************************** Linked List Management ********************/
34282
34283 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34284 /*
34285 ** Check that the pCache->pSynced variable is set correctly. If it
34286 ** is not, either fail an assert or return zero. Otherwise, return
34287 ** non-zero. This is only used in debugging builds, as follows:
34288 **
34289 **   expensive_assert( pcacheCheckSynced(pCache) );
34290 */
34291 static int pcacheCheckSynced(PCache *pCache){
34292   PgHdr *p;
34293   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34294     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34295   }
34296   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34297 }
34298 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34299
34300 /*
34301 ** Remove page pPage from the list of dirty pages.
34302 */
34303 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34304   PCache *p = pPage->pCache;
34305
34306   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34307   assert( pPage->pDirtyPrev || pPage==p->pDirty );
34308
34309   /* Update the PCache1.pSynced variable if necessary. */
34310   if( p->pSynced==pPage ){
34311     PgHdr *pSynced = pPage->pDirtyPrev;
34312     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34313       pSynced = pSynced->pDirtyPrev;
34314     }
34315     p->pSynced = pSynced;
34316   }
34317
34318   if( pPage->pDirtyNext ){
34319     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34320   }else{
34321     assert( pPage==p->pDirtyTail );
34322     p->pDirtyTail = pPage->pDirtyPrev;
34323   }
34324   if( pPage->pDirtyPrev ){
34325     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34326   }else{
34327     assert( pPage==p->pDirty );
34328     p->pDirty = pPage->pDirtyNext;
34329   }
34330   pPage->pDirtyNext = 0;
34331   pPage->pDirtyPrev = 0;
34332
34333   expensive_assert( pcacheCheckSynced(p) );
34334 }
34335
34336 /*
34337 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34338 ** pPage).
34339 */
34340 static void pcacheAddToDirtyList(PgHdr *pPage){
34341   PCache *p = pPage->pCache;
34342
34343   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34344
34345   pPage->pDirtyNext = p->pDirty;
34346   if( pPage->pDirtyNext ){
34347     assert( pPage->pDirtyNext->pDirtyPrev==0 );
34348     pPage->pDirtyNext->pDirtyPrev = pPage;
34349   }
34350   p->pDirty = pPage;
34351   if( !p->pDirtyTail ){
34352     p->pDirtyTail = pPage;
34353   }
34354   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34355     p->pSynced = pPage;
34356   }
34357   expensive_assert( pcacheCheckSynced(p) );
34358 }
34359
34360 /*
34361 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34362 ** being used for an in-memory database, this function is a no-op.
34363 */
34364 static void pcacheUnpin(PgHdr *p){
34365   PCache *pCache = p->pCache;
34366   if( pCache->bPurgeable ){
34367     if( p->pgno==1 ){
34368       pCache->pPage1 = 0;
34369     }
34370     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34371   }
34372 }
34373
34374 /*************************************************** General Interfaces ******
34375 **
34376 ** Initialize and shutdown the page cache subsystem. Neither of these 
34377 ** functions are threadsafe.
34378 */
34379 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34380   if( sqlite3GlobalConfig.pcache.xInit==0 ){
34381     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34382     ** built-in default page cache is used instead of the application defined
34383     ** page cache. */
34384     sqlite3PCacheSetDefault();
34385   }
34386   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34387 }
34388 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34389   if( sqlite3GlobalConfig.pcache.xShutdown ){
34390     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34391     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34392   }
34393 }
34394
34395 /*
34396 ** Return the size in bytes of a PCache object.
34397 */
34398 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34399
34400 /*
34401 ** Create a new PCache object. Storage space to hold the object
34402 ** has already been allocated and is passed in as the p pointer. 
34403 ** The caller discovers how much space needs to be allocated by 
34404 ** calling sqlite3PcacheSize().
34405 */
34406 SQLITE_PRIVATE void sqlite3PcacheOpen(
34407   int szPage,                  /* Size of every page */
34408   int szExtra,                 /* Extra space associated with each page */
34409   int bPurgeable,              /* True if pages are on backing store */
34410   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34411   void *pStress,               /* Argument to xStress */
34412   PCache *p                    /* Preallocated space for the PCache */
34413 ){
34414   memset(p, 0, sizeof(PCache));
34415   p->szPage = szPage;
34416   p->szExtra = szExtra;
34417   p->bPurgeable = bPurgeable;
34418   p->xStress = xStress;
34419   p->pStress = pStress;
34420   p->nMax = 100;
34421 }
34422
34423 /*
34424 ** Change the page size for PCache object. The caller must ensure that there
34425 ** are no outstanding page references when this function is called.
34426 */
34427 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34428   assert( pCache->nRef==0 && pCache->pDirty==0 );
34429   if( pCache->pCache ){
34430     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34431     pCache->pCache = 0;
34432     pCache->pPage1 = 0;
34433   }
34434   pCache->szPage = szPage;
34435 }
34436
34437 /*
34438 ** Try to obtain a page from the cache.
34439 */
34440 SQLITE_PRIVATE int sqlite3PcacheFetch(
34441   PCache *pCache,       /* Obtain the page from this cache */
34442   Pgno pgno,            /* Page number to obtain */
34443   int createFlag,       /* If true, create page if it does not exist already */
34444   PgHdr **ppPage        /* Write the page here */
34445 ){
34446   PgHdr *pPage = 0;
34447   int eCreate;
34448
34449   assert( pCache!=0 );
34450   assert( createFlag==1 || createFlag==0 );
34451   assert( pgno>0 );
34452
34453   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34454   ** allocate it now.
34455   */
34456   if( !pCache->pCache && createFlag ){
34457     sqlite3_pcache *p;
34458     int nByte;
34459     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34460     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34461     if( !p ){
34462       return SQLITE_NOMEM;
34463     }
34464     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34465     pCache->pCache = p;
34466   }
34467
34468   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34469   if( pCache->pCache ){
34470     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34471   }
34472
34473   if( !pPage && eCreate==1 ){
34474     PgHdr *pPg;
34475
34476     /* Find a dirty page to write-out and recycle. First try to find a 
34477     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34478     ** cleared), but if that is not possible settle for any other 
34479     ** unreferenced dirty page.
34480     */
34481     expensive_assert( pcacheCheckSynced(pCache) );
34482     for(pPg=pCache->pSynced; 
34483         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
34484         pPg=pPg->pDirtyPrev
34485     );
34486     pCache->pSynced = pPg;
34487     if( !pPg ){
34488       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34489     }
34490     if( pPg ){
34491       int rc;
34492       rc = pCache->xStress(pCache->pStress, pPg);
34493       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34494         return rc;
34495       }
34496     }
34497
34498     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34499   }
34500
34501   if( pPage ){
34502     if( !pPage->pData ){
34503       memset(pPage, 0, sizeof(PgHdr));
34504       pPage->pData = (void *)&pPage[1];
34505       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34506       memset(pPage->pExtra, 0, pCache->szExtra);
34507       pPage->pCache = pCache;
34508       pPage->pgno = pgno;
34509     }
34510     assert( pPage->pCache==pCache );
34511     assert( pPage->pgno==pgno );
34512     assert( pPage->pData==(void *)&pPage[1] );
34513     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34514
34515     if( 0==pPage->nRef ){
34516       pCache->nRef++;
34517     }
34518     pPage->nRef++;
34519     if( pgno==1 ){
34520       pCache->pPage1 = pPage;
34521     }
34522   }
34523   *ppPage = pPage;
34524   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34525 }
34526
34527 /*
34528 ** Decrement the reference count on a page. If the page is clean and the
34529 ** reference count drops to 0, then it is made elible for recycling.
34530 */
34531 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34532   assert( p->nRef>0 );
34533   p->nRef--;
34534   if( p->nRef==0 ){
34535     PCache *pCache = p->pCache;
34536     pCache->nRef--;
34537     if( (p->flags&PGHDR_DIRTY)==0 ){
34538       pcacheUnpin(p);
34539     }else{
34540       /* Move the page to the head of the dirty list. */
34541       pcacheRemoveFromDirtyList(p);
34542       pcacheAddToDirtyList(p);
34543     }
34544   }
34545 }
34546
34547 /*
34548 ** Increase the reference count of a supplied page by 1.
34549 */
34550 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34551   assert(p->nRef>0);
34552   p->nRef++;
34553 }
34554
34555 /*
34556 ** Drop a page from the cache. There must be exactly one reference to the
34557 ** page. This function deletes that reference, so after it returns the
34558 ** page pointed to by p is invalid.
34559 */
34560 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
34561   PCache *pCache;
34562   assert( p->nRef==1 );
34563   if( p->flags&PGHDR_DIRTY ){
34564     pcacheRemoveFromDirtyList(p);
34565   }
34566   pCache = p->pCache;
34567   pCache->nRef--;
34568   if( p->pgno==1 ){
34569     pCache->pPage1 = 0;
34570   }
34571   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
34572 }
34573
34574 /*
34575 ** Make sure the page is marked as dirty. If it isn't dirty already,
34576 ** make it so.
34577 */
34578 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
34579   p->flags &= ~PGHDR_DONT_WRITE;
34580   assert( p->nRef>0 );
34581   if( 0==(p->flags & PGHDR_DIRTY) ){
34582     p->flags |= PGHDR_DIRTY;
34583     pcacheAddToDirtyList( p);
34584   }
34585 }
34586
34587 /*
34588 ** Make sure the page is marked as clean. If it isn't clean already,
34589 ** make it so.
34590 */
34591 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
34592   if( (p->flags & PGHDR_DIRTY) ){
34593     pcacheRemoveFromDirtyList(p);
34594     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
34595     if( p->nRef==0 ){
34596       pcacheUnpin(p);
34597     }
34598   }
34599 }
34600
34601 /*
34602 ** Make every page in the cache clean.
34603 */
34604 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
34605   PgHdr *p;
34606   while( (p = pCache->pDirty)!=0 ){
34607     sqlite3PcacheMakeClean(p);
34608   }
34609 }
34610
34611 /*
34612 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
34613 */
34614 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
34615   PgHdr *p;
34616   for(p=pCache->pDirty; p; p=p->pDirtyNext){
34617     p->flags &= ~PGHDR_NEED_SYNC;
34618   }
34619   pCache->pSynced = pCache->pDirtyTail;
34620 }
34621
34622 /*
34623 ** Change the page number of page p to newPgno. 
34624 */
34625 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
34626   PCache *pCache = p->pCache;
34627   assert( p->nRef>0 );
34628   assert( newPgno>0 );
34629   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
34630   p->pgno = newPgno;
34631   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
34632     pcacheRemoveFromDirtyList(p);
34633     pcacheAddToDirtyList(p);
34634   }
34635 }
34636
34637 /*
34638 ** Drop every cache entry whose page number is greater than "pgno". The
34639 ** caller must ensure that there are no outstanding references to any pages
34640 ** other than page 1 with a page number greater than pgno.
34641 **
34642 ** If there is a reference to page 1 and the pgno parameter passed to this
34643 ** function is 0, then the data area associated with page 1 is zeroed, but
34644 ** the page object is not dropped.
34645 */
34646 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
34647   if( pCache->pCache ){
34648     PgHdr *p;
34649     PgHdr *pNext;
34650     for(p=pCache->pDirty; p; p=pNext){
34651       pNext = p->pDirtyNext;
34652       /* This routine never gets call with a positive pgno except right
34653       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
34654       ** it must be that pgno==0.
34655       */
34656       assert( p->pgno>0 );
34657       if( ALWAYS(p->pgno>pgno) ){
34658         assert( p->flags&PGHDR_DIRTY );
34659         sqlite3PcacheMakeClean(p);
34660       }
34661     }
34662     if( pgno==0 && pCache->pPage1 ){
34663       memset(pCache->pPage1->pData, 0, pCache->szPage);
34664       pgno = 1;
34665     }
34666     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
34667   }
34668 }
34669
34670 /*
34671 ** Close a cache.
34672 */
34673 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
34674   if( pCache->pCache ){
34675     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34676   }
34677 }
34678
34679 /* 
34680 ** Discard the contents of the cache.
34681 */
34682 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
34683   sqlite3PcacheTruncate(pCache, 0);
34684 }
34685
34686 /*
34687 ** Merge two lists of pages connected by pDirty and in pgno order.
34688 ** Do not both fixing the pDirtyPrev pointers.
34689 */
34690 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
34691   PgHdr result, *pTail;
34692   pTail = &result;
34693   while( pA && pB ){
34694     if( pA->pgno<pB->pgno ){
34695       pTail->pDirty = pA;
34696       pTail = pA;
34697       pA = pA->pDirty;
34698     }else{
34699       pTail->pDirty = pB;
34700       pTail = pB;
34701       pB = pB->pDirty;
34702     }
34703   }
34704   if( pA ){
34705     pTail->pDirty = pA;
34706   }else if( pB ){
34707     pTail->pDirty = pB;
34708   }else{
34709     pTail->pDirty = 0;
34710   }
34711   return result.pDirty;
34712 }
34713
34714 /*
34715 ** Sort the list of pages in accending order by pgno.  Pages are
34716 ** connected by pDirty pointers.  The pDirtyPrev pointers are
34717 ** corrupted by this sort.
34718 **
34719 ** Since there cannot be more than 2^31 distinct pages in a database,
34720 ** there cannot be more than 31 buckets required by the merge sorter.
34721 ** One extra bucket is added to catch overflow in case something
34722 ** ever changes to make the previous sentence incorrect.
34723 */
34724 #define N_SORT_BUCKET  32
34725 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
34726   PgHdr *a[N_SORT_BUCKET], *p;
34727   int i;
34728   memset(a, 0, sizeof(a));
34729   while( pIn ){
34730     p = pIn;
34731     pIn = p->pDirty;
34732     p->pDirty = 0;
34733     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
34734       if( a[i]==0 ){
34735         a[i] = p;
34736         break;
34737       }else{
34738         p = pcacheMergeDirtyList(a[i], p);
34739         a[i] = 0;
34740       }
34741     }
34742     if( NEVER(i==N_SORT_BUCKET-1) ){
34743       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
34744       ** the input list.  But that is impossible.
34745       */
34746       a[i] = pcacheMergeDirtyList(a[i], p);
34747     }
34748   }
34749   p = a[0];
34750   for(i=1; i<N_SORT_BUCKET; i++){
34751     p = pcacheMergeDirtyList(p, a[i]);
34752   }
34753   return p;
34754 }
34755
34756 /*
34757 ** Return a list of all dirty pages in the cache, sorted by page number.
34758 */
34759 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
34760   PgHdr *p;
34761   for(p=pCache->pDirty; p; p=p->pDirtyNext){
34762     p->pDirty = p->pDirtyNext;
34763   }
34764   return pcacheSortDirtyList(pCache->pDirty);
34765 }
34766
34767 /* 
34768 ** Return the total number of referenced pages held by the cache.
34769 */
34770 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
34771   return pCache->nRef;
34772 }
34773
34774 /*
34775 ** Return the number of references to the page supplied as an argument.
34776 */
34777 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
34778   return p->nRef;
34779 }
34780
34781 /* 
34782 ** Return the total number of pages in the cache.
34783 */
34784 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
34785   int nPage = 0;
34786   if( pCache->pCache ){
34787     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
34788   }
34789   return nPage;
34790 }
34791
34792 #ifdef SQLITE_TEST
34793 /*
34794 ** Get the suggested cache-size value.
34795 */
34796 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
34797   return pCache->nMax;
34798 }
34799 #endif
34800
34801 /*
34802 ** Set the suggested cache-size value.
34803 */
34804 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
34805   pCache->nMax = mxPage;
34806   if( pCache->pCache ){
34807     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
34808   }
34809 }
34810
34811 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
34812 /*
34813 ** For all dirty pages currently in the cache, invoke the specified
34814 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
34815 ** defined.
34816 */
34817 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
34818   PgHdr *pDirty;
34819   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
34820     xIter(pDirty);
34821   }
34822 }
34823 #endif
34824
34825 /************** End of pcache.c **********************************************/
34826 /************** Begin file pcache1.c *****************************************/
34827 /*
34828 ** 2008 November 05
34829 **
34830 ** The author disclaims copyright to this source code.  In place of
34831 ** a legal notice, here is a blessing:
34832 **
34833 **    May you do good and not evil.
34834 **    May you find forgiveness for yourself and forgive others.
34835 **    May you share freely, never taking more than you give.
34836 **
34837 *************************************************************************
34838 **
34839 ** This file implements the default page cache implementation (the
34840 ** sqlite3_pcache interface). It also contains part of the implementation
34841 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
34842 ** If the default page cache implementation is overriden, then neither of
34843 ** these two features are available.
34844 */
34845
34846
34847 typedef struct PCache1 PCache1;
34848 typedef struct PgHdr1 PgHdr1;
34849 typedef struct PgFreeslot PgFreeslot;
34850 typedef struct PGroup PGroup;
34851
34852 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
34853 ** of one or more PCaches that are able to recycle each others unpinned
34854 ** pages when they are under memory pressure.  A PGroup is an instance of
34855 ** the following object.
34856 **
34857 ** This page cache implementation works in one of two modes:
34858 **
34859 **   (1)  Every PCache is the sole member of its own PGroup.  There is
34860 **        one PGroup per PCache.
34861 **
34862 **   (2)  There is a single global PGroup that all PCaches are a member
34863 **        of.
34864 **
34865 ** Mode 1 uses more memory (since PCache instances are not able to rob
34866 ** unused pages from other PCaches) but it also operates without a mutex,
34867 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
34868 ** threadsafe, but is able recycle pages more efficient.
34869 **
34870 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
34871 ** PGroup which is the pcache1.grp global variable and its mutex is
34872 ** SQLITE_MUTEX_STATIC_LRU.
34873 */
34874 struct PGroup {
34875   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
34876   int nMaxPage;                  /* Sum of nMax for purgeable caches */
34877   int nMinPage;                  /* Sum of nMin for purgeable caches */
34878   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
34879   int nCurrentPage;              /* Number of purgeable pages allocated */
34880   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
34881 };
34882
34883 /* Each page cache is an instance of the following object.  Every
34884 ** open database file (including each in-memory database and each
34885 ** temporary or transient database) has a single page cache which
34886 ** is an instance of this object.
34887 **
34888 ** Pointers to structures of this type are cast and returned as 
34889 ** opaque sqlite3_pcache* handles.
34890 */
34891 struct PCache1 {
34892   /* Cache configuration parameters. Page size (szPage) and the purgeable
34893   ** flag (bPurgeable) are set when the cache is created. nMax may be 
34894   ** modified at any time by a call to the pcache1CacheSize() method.
34895   ** The PGroup mutex must be held when accessing nMax.
34896   */
34897   PGroup *pGroup;                     /* PGroup this cache belongs to */
34898   int szPage;                         /* Size of allocated pages in bytes */
34899   int bPurgeable;                     /* True if cache is purgeable */
34900   unsigned int nMin;                  /* Minimum number of pages reserved */
34901   unsigned int nMax;                  /* Configured "cache_size" value */
34902   unsigned int n90pct;                /* nMax*9/10 */
34903
34904   /* Hash table of all pages. The following variables may only be accessed
34905   ** when the accessor is holding the PGroup mutex.
34906   */
34907   unsigned int nRecyclable;           /* Number of pages in the LRU list */
34908   unsigned int nPage;                 /* Total number of pages in apHash */
34909   unsigned int nHash;                 /* Number of slots in apHash[] */
34910   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
34911
34912   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
34913 };
34914
34915 /*
34916 ** Each cache entry is represented by an instance of the following 
34917 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
34918 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
34919 ** macro below).
34920 */
34921 struct PgHdr1 {
34922   unsigned int iKey;             /* Key value (page number) */
34923   PgHdr1 *pNext;                 /* Next in hash table chain */
34924   PCache1 *pCache;               /* Cache that currently owns this page */
34925   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
34926   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
34927 };
34928
34929 /*
34930 ** Free slots in the allocator used to divide up the buffer provided using
34931 ** the SQLITE_CONFIG_PAGECACHE mechanism.
34932 */
34933 struct PgFreeslot {
34934   PgFreeslot *pNext;  /* Next free slot */
34935 };
34936
34937 /*
34938 ** Global data used by this cache.
34939 */
34940 static SQLITE_WSD struct PCacheGlobal {
34941   PGroup grp;                    /* The global PGroup for mode (2) */
34942
34943   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
34944   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
34945   ** fixed at sqlite3_initialize() time and do not require mutex protection.
34946   ** The nFreeSlot and pFree values do require mutex protection.
34947   */
34948   int isInit;                    /* True if initialized */
34949   int szSlot;                    /* Size of each free slot */
34950   int nSlot;                     /* The number of pcache slots */
34951   int nReserve;                  /* Try to keep nFreeSlot above this */
34952   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
34953   /* Above requires no mutex.  Use mutex below for variable that follow. */
34954   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
34955   int nFreeSlot;                 /* Number of unused pcache slots */
34956   PgFreeslot *pFree;             /* Free page blocks */
34957   /* The following value requires a mutex to change.  We skip the mutex on
34958   ** reading because (1) most platforms read a 32-bit integer atomically and
34959   ** (2) even if an incorrect value is read, no great harm is done since this
34960   ** is really just an optimization. */
34961   int bUnderPressure;            /* True if low on PAGECACHE memory */
34962 } pcache1_g;
34963
34964 /*
34965 ** All code in this file should access the global structure above via the
34966 ** alias "pcache1". This ensures that the WSD emulation is used when
34967 ** compiling for systems that do not support real WSD.
34968 */
34969 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
34970
34971 /*
34972 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
34973 ** bytes of data are located directly before it in memory (i.e. the total
34974 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
34975 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
34976 ** an argument and returns a pointer to the associated block of szPage
34977 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
34978 ** a pointer to a block of szPage bytes of data and the return value is
34979 ** a pointer to the associated PgHdr1 structure.
34980 **
34981 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
34982 */
34983 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
34984 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
34985
34986 /*
34987 ** Macros to enter and leave the PCache LRU mutex.
34988 */
34989 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
34990 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
34991
34992 /******************************************************************************/
34993 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
34994
34995 /*
34996 ** This function is called during initialization if a static buffer is 
34997 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
34998 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
34999 ** enough to contain 'n' buffers of 'sz' bytes each.
35000 **
35001 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35002 ** to be serialized already.  There is no need for further mutexing.
35003 */
35004 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35005   if( pcache1.isInit ){
35006     PgFreeslot *p;
35007     sz = ROUNDDOWN8(sz);
35008     pcache1.szSlot = sz;
35009     pcache1.nSlot = pcache1.nFreeSlot = n;
35010     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35011     pcache1.pStart = pBuf;
35012     pcache1.pFree = 0;
35013     pcache1.bUnderPressure = 0;
35014     while( n-- ){
35015       p = (PgFreeslot*)pBuf;
35016       p->pNext = pcache1.pFree;
35017       pcache1.pFree = p;
35018       pBuf = (void*)&((char*)pBuf)[sz];
35019     }
35020     pcache1.pEnd = pBuf;
35021   }
35022 }
35023
35024 /*
35025 ** Malloc function used within this file to allocate space from the buffer
35026 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35027 ** such buffer exists or there is no space left in it, this function falls 
35028 ** back to sqlite3Malloc().
35029 **
35030 ** Multiple threads can run this routine at the same time.  Global variables
35031 ** in pcache1 need to be protected via mutex.
35032 */
35033 static void *pcache1Alloc(int nByte){
35034   void *p = 0;
35035   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35036   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35037   if( nByte<=pcache1.szSlot ){
35038     sqlite3_mutex_enter(pcache1.mutex);
35039     p = (PgHdr1 *)pcache1.pFree;
35040     if( p ){
35041       pcache1.pFree = pcache1.pFree->pNext;
35042       pcache1.nFreeSlot--;
35043       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35044       assert( pcache1.nFreeSlot>=0 );
35045       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35046     }
35047     sqlite3_mutex_leave(pcache1.mutex);
35048   }
35049   if( p==0 ){
35050     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35051     ** it from sqlite3Malloc instead.
35052     */
35053     p = sqlite3Malloc(nByte);
35054     if( p ){
35055       int sz = sqlite3MallocSize(p);
35056       sqlite3_mutex_enter(pcache1.mutex);
35057       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35058       sqlite3_mutex_leave(pcache1.mutex);
35059     }
35060     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35061   }
35062   return p;
35063 }
35064
35065 /*
35066 ** Free an allocated buffer obtained from pcache1Alloc().
35067 */
35068 static void pcache1Free(void *p){
35069   if( p==0 ) return;
35070   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35071     PgFreeslot *pSlot;
35072     sqlite3_mutex_enter(pcache1.mutex);
35073     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35074     pSlot = (PgFreeslot*)p;
35075     pSlot->pNext = pcache1.pFree;
35076     pcache1.pFree = pSlot;
35077     pcache1.nFreeSlot++;
35078     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35079     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35080     sqlite3_mutex_leave(pcache1.mutex);
35081   }else{
35082     int iSize;
35083     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35084     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35085     iSize = sqlite3MallocSize(p);
35086     sqlite3_mutex_enter(pcache1.mutex);
35087     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35088     sqlite3_mutex_leave(pcache1.mutex);
35089     sqlite3_free(p);
35090   }
35091 }
35092
35093 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35094 /*
35095 ** Return the size of a pcache allocation
35096 */
35097 static int pcache1MemSize(void *p){
35098   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35099     return pcache1.szSlot;
35100   }else{
35101     int iSize;
35102     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35103     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35104     iSize = sqlite3MallocSize(p);
35105     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35106     return iSize;
35107   }
35108 }
35109 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35110
35111 /*
35112 ** Allocate a new page object initially associated with cache pCache.
35113 */
35114 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35115   int nByte = sizeof(PgHdr1) + pCache->szPage;
35116   void *pPg = pcache1Alloc(nByte);
35117   PgHdr1 *p;
35118   if( pPg ){
35119     p = PAGE_TO_PGHDR1(pCache, pPg);
35120     if( pCache->bPurgeable ){
35121       pCache->pGroup->nCurrentPage++;
35122     }
35123   }else{
35124     p = 0;
35125   }
35126   return p;
35127 }
35128
35129 /*
35130 ** Free a page object allocated by pcache1AllocPage().
35131 **
35132 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
35133 ** that the current implementation happens to never call this routine
35134 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35135 */
35136 static void pcache1FreePage(PgHdr1 *p){
35137   if( ALWAYS(p) ){
35138     PCache1 *pCache = p->pCache;
35139     if( pCache->bPurgeable ){
35140       pCache->pGroup->nCurrentPage--;
35141     }
35142     pcache1Free(PGHDR1_TO_PAGE(p));
35143   }
35144 }
35145
35146 /*
35147 ** Malloc function used by SQLite to obtain space from the buffer configured
35148 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35149 ** exists, this function falls back to sqlite3Malloc().
35150 */
35151 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35152   return pcache1Alloc(sz);
35153 }
35154
35155 /*
35156 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35157 */
35158 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35159   pcache1Free(p);
35160 }
35161
35162
35163 /*
35164 ** Return true if it desirable to avoid allocating a new page cache
35165 ** entry.
35166 **
35167 ** If memory was allocated specifically to the page cache using
35168 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35169 ** it is desirable to avoid allocating a new page cache entry because
35170 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35171 ** for all page cache needs and we should not need to spill the
35172 ** allocation onto the heap.
35173 **
35174 ** Or, the heap is used for all page cache memory put the heap is
35175 ** under memory pressure, then again it is desirable to avoid
35176 ** allocating a new page cache entry in order to avoid stressing
35177 ** the heap even further.
35178 */
35179 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35180   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35181     return pcache1.bUnderPressure;
35182   }else{
35183     return sqlite3HeapNearlyFull();
35184   }
35185 }
35186
35187 /******************************************************************************/
35188 /******** General Implementation Functions ************************************/
35189
35190 /*
35191 ** This function is used to resize the hash table used by the cache passed
35192 ** as the first argument.
35193 **
35194 ** The PCache mutex must be held when this function is called.
35195 */
35196 static int pcache1ResizeHash(PCache1 *p){
35197   PgHdr1 **apNew;
35198   unsigned int nNew;
35199   unsigned int i;
35200
35201   assert( sqlite3_mutex_held(p->pGroup->mutex) );
35202
35203   nNew = p->nHash*2;
35204   if( nNew<256 ){
35205     nNew = 256;
35206   }
35207
35208   pcache1LeaveMutex(p->pGroup);
35209   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35210   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35211   if( p->nHash ){ sqlite3EndBenignMalloc(); }
35212   pcache1EnterMutex(p->pGroup);
35213   if( apNew ){
35214     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35215     for(i=0; i<p->nHash; i++){
35216       PgHdr1 *pPage;
35217       PgHdr1 *pNext = p->apHash[i];
35218       while( (pPage = pNext)!=0 ){
35219         unsigned int h = pPage->iKey % nNew;
35220         pNext = pPage->pNext;
35221         pPage->pNext = apNew[h];
35222         apNew[h] = pPage;
35223       }
35224     }
35225     sqlite3_free(p->apHash);
35226     p->apHash = apNew;
35227     p->nHash = nNew;
35228   }
35229
35230   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35231 }
35232
35233 /*
35234 ** This function is used internally to remove the page pPage from the 
35235 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35236 ** LRU list, then this function is a no-op.
35237 **
35238 ** The PGroup mutex must be held when this function is called.
35239 **
35240 ** If pPage is NULL then this routine is a no-op.
35241 */
35242 static void pcache1PinPage(PgHdr1 *pPage){
35243   PCache1 *pCache;
35244   PGroup *pGroup;
35245
35246   if( pPage==0 ) return;
35247   pCache = pPage->pCache;
35248   pGroup = pCache->pGroup;
35249   assert( sqlite3_mutex_held(pGroup->mutex) );
35250   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35251     if( pPage->pLruPrev ){
35252       pPage->pLruPrev->pLruNext = pPage->pLruNext;
35253     }
35254     if( pPage->pLruNext ){
35255       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35256     }
35257     if( pGroup->pLruHead==pPage ){
35258       pGroup->pLruHead = pPage->pLruNext;
35259     }
35260     if( pGroup->pLruTail==pPage ){
35261       pGroup->pLruTail = pPage->pLruPrev;
35262     }
35263     pPage->pLruNext = 0;
35264     pPage->pLruPrev = 0;
35265     pPage->pCache->nRecyclable--;
35266   }
35267 }
35268
35269
35270 /*
35271 ** Remove the page supplied as an argument from the hash table 
35272 ** (PCache1.apHash structure) that it is currently stored in.
35273 **
35274 ** The PGroup mutex must be held when this function is called.
35275 */
35276 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35277   unsigned int h;
35278   PCache1 *pCache = pPage->pCache;
35279   PgHdr1 **pp;
35280
35281   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35282   h = pPage->iKey % pCache->nHash;
35283   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35284   *pp = (*pp)->pNext;
35285
35286   pCache->nPage--;
35287 }
35288
35289 /*
35290 ** If there are currently more than nMaxPage pages allocated, try
35291 ** to recycle pages to reduce the number allocated to nMaxPage.
35292 */
35293 static void pcache1EnforceMaxPage(PGroup *pGroup){
35294   assert( sqlite3_mutex_held(pGroup->mutex) );
35295   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35296     PgHdr1 *p = pGroup->pLruTail;
35297     assert( p->pCache->pGroup==pGroup );
35298     pcache1PinPage(p);
35299     pcache1RemoveFromHash(p);
35300     pcache1FreePage(p);
35301   }
35302 }
35303
35304 /*
35305 ** Discard all pages from cache pCache with a page number (key value) 
35306 ** greater than or equal to iLimit. Any pinned pages that meet this 
35307 ** criteria are unpinned before they are discarded.
35308 **
35309 ** The PCache mutex must be held when this function is called.
35310 */
35311 static void pcache1TruncateUnsafe(
35312   PCache1 *pCache,             /* The cache to truncate */
35313   unsigned int iLimit          /* Drop pages with this pgno or larger */
35314 ){
35315   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
35316   unsigned int h;
35317   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35318   for(h=0; h<pCache->nHash; h++){
35319     PgHdr1 **pp = &pCache->apHash[h]; 
35320     PgHdr1 *pPage;
35321     while( (pPage = *pp)!=0 ){
35322       if( pPage->iKey>=iLimit ){
35323         pCache->nPage--;
35324         *pp = pPage->pNext;
35325         pcache1PinPage(pPage);
35326         pcache1FreePage(pPage);
35327       }else{
35328         pp = &pPage->pNext;
35329         TESTONLY( nPage++; )
35330       }
35331     }
35332   }
35333   assert( pCache->nPage==nPage );
35334 }
35335
35336 /******************************************************************************/
35337 /******** sqlite3_pcache Methods **********************************************/
35338
35339 /*
35340 ** Implementation of the sqlite3_pcache.xInit method.
35341 */
35342 static int pcache1Init(void *NotUsed){
35343   UNUSED_PARAMETER(NotUsed);
35344   assert( pcache1.isInit==0 );
35345   memset(&pcache1, 0, sizeof(pcache1));
35346   if( sqlite3GlobalConfig.bCoreMutex ){
35347     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35348     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35349   }
35350   pcache1.grp.mxPinned = 10;
35351   pcache1.isInit = 1;
35352   return SQLITE_OK;
35353 }
35354
35355 /*
35356 ** Implementation of the sqlite3_pcache.xShutdown method.
35357 ** Note that the static mutex allocated in xInit does 
35358 ** not need to be freed.
35359 */
35360 static void pcache1Shutdown(void *NotUsed){
35361   UNUSED_PARAMETER(NotUsed);
35362   assert( pcache1.isInit!=0 );
35363   memset(&pcache1, 0, sizeof(pcache1));
35364 }
35365
35366 /*
35367 ** Implementation of the sqlite3_pcache.xCreate method.
35368 **
35369 ** Allocate a new cache.
35370 */
35371 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35372   PCache1 *pCache;      /* The newly created page cache */
35373   PGroup *pGroup;       /* The group the new page cache will belong to */
35374   int sz;               /* Bytes of memory required to allocate the new cache */
35375
35376   /*
35377   ** The seperateCache variable is true if each PCache has its own private
35378   ** PGroup.  In other words, separateCache is true for mode (1) where no
35379   ** mutexing is required.
35380   **
35381   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35382   **
35383   **   *  Always use a unified cache in single-threaded applications
35384   **
35385   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35386   **      use separate caches (mode-1)
35387   */
35388 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35389   const int separateCache = 0;
35390 #else
35391   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35392 #endif
35393
35394   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35395   pCache = (PCache1 *)sqlite3_malloc(sz);
35396   if( pCache ){
35397     memset(pCache, 0, sz);
35398     if( separateCache ){
35399       pGroup = (PGroup*)&pCache[1];
35400       pGroup->mxPinned = 10;
35401     }else{
35402       pGroup = &pcache1_g.grp;
35403     }
35404     pCache->pGroup = pGroup;
35405     pCache->szPage = szPage;
35406     pCache->bPurgeable = (bPurgeable ? 1 : 0);
35407     if( bPurgeable ){
35408       pCache->nMin = 10;
35409       pcache1EnterMutex(pGroup);
35410       pGroup->nMinPage += pCache->nMin;
35411       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35412       pcache1LeaveMutex(pGroup);
35413     }
35414   }
35415   return (sqlite3_pcache *)pCache;
35416 }
35417
35418 /*
35419 ** Implementation of the sqlite3_pcache.xCachesize method. 
35420 **
35421 ** Configure the cache_size limit for a cache.
35422 */
35423 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35424   PCache1 *pCache = (PCache1 *)p;
35425   if( pCache->bPurgeable ){
35426     PGroup *pGroup = pCache->pGroup;
35427     pcache1EnterMutex(pGroup);
35428     pGroup->nMaxPage += (nMax - pCache->nMax);
35429     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35430     pCache->nMax = nMax;
35431     pCache->n90pct = pCache->nMax*9/10;
35432     pcache1EnforceMaxPage(pGroup);
35433     pcache1LeaveMutex(pGroup);
35434   }
35435 }
35436
35437 /*
35438 ** Implementation of the sqlite3_pcache.xPagecount method. 
35439 */
35440 static int pcache1Pagecount(sqlite3_pcache *p){
35441   int n;
35442   PCache1 *pCache = (PCache1*)p;
35443   pcache1EnterMutex(pCache->pGroup);
35444   n = pCache->nPage;
35445   pcache1LeaveMutex(pCache->pGroup);
35446   return n;
35447 }
35448
35449 /*
35450 ** Implementation of the sqlite3_pcache.xFetch method. 
35451 **
35452 ** Fetch a page by key value.
35453 **
35454 ** Whether or not a new page may be allocated by this function depends on
35455 ** the value of the createFlag argument.  0 means do not allocate a new
35456 ** page.  1 means allocate a new page if space is easily available.  2 
35457 ** means to try really hard to allocate a new page.
35458 **
35459 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35460 ** database) there is really no difference between createFlag 1 and 2.  So
35461 ** the calling function (pcache.c) will never have a createFlag of 1 on
35462 ** a non-purgable cache.
35463 **
35464 ** There are three different approaches to obtaining space for a page,
35465 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35466 **
35467 **   1. Regardless of the value of createFlag, the cache is searched for a 
35468 **      copy of the requested page. If one is found, it is returned.
35469 **
35470 **   2. If createFlag==0 and the page is not already in the cache, NULL is
35471 **      returned.
35472 **
35473 **   3. If createFlag is 1, and the page is not already in the cache, then
35474 **      return NULL (do not allocate a new page) if any of the following
35475 **      conditions are true:
35476 **
35477 **       (a) the number of pages pinned by the cache is greater than
35478 **           PCache1.nMax, or
35479 **
35480 **       (b) the number of pages pinned by the cache is greater than
35481 **           the sum of nMax for all purgeable caches, less the sum of 
35482 **           nMin for all other purgeable caches, or
35483 **
35484 **   4. If none of the first three conditions apply and the cache is marked
35485 **      as purgeable, and if one of the following is true:
35486 **
35487 **       (a) The number of pages allocated for the cache is already 
35488 **           PCache1.nMax, or
35489 **
35490 **       (b) The number of pages allocated for all purgeable caches is
35491 **           already equal to or greater than the sum of nMax for all
35492 **           purgeable caches,
35493 **
35494 **       (c) The system is under memory pressure and wants to avoid
35495 **           unnecessary pages cache entry allocations
35496 **
35497 **      then attempt to recycle a page from the LRU list. If it is the right
35498 **      size, return the recycled buffer. Otherwise, free the buffer and
35499 **      proceed to step 5. 
35500 **
35501 **   5. Otherwise, allocate and return a new page buffer.
35502 */
35503 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35504   int nPinned;
35505   PCache1 *pCache = (PCache1 *)p;
35506   PGroup *pGroup;
35507   PgHdr1 *pPage = 0;
35508
35509   assert( pCache->bPurgeable || createFlag!=1 );
35510   assert( pCache->bPurgeable || pCache->nMin==0 );
35511   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35512   assert( pCache->nMin==0 || pCache->bPurgeable );
35513   pcache1EnterMutex(pGroup = pCache->pGroup);
35514
35515   /* Step 1: Search the hash table for an existing entry. */
35516   if( pCache->nHash>0 ){
35517     unsigned int h = iKey % pCache->nHash;
35518     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35519   }
35520
35521   /* Step 2: Abort if no existing page is found and createFlag is 0 */
35522   if( pPage || createFlag==0 ){
35523     pcache1PinPage(pPage);
35524     goto fetch_out;
35525   }
35526
35527   /* The pGroup local variable will normally be initialized by the
35528   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
35529   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35530   ** local variable here.  Delaying the initialization of pGroup is an
35531   ** optimization:  The common case is to exit the module before reaching
35532   ** this point.
35533   */
35534 #ifdef SQLITE_MUTEX_OMIT
35535   pGroup = pCache->pGroup;
35536 #endif
35537
35538
35539   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35540   nPinned = pCache->nPage - pCache->nRecyclable;
35541   assert( nPinned>=0 );
35542   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35543   assert( pCache->n90pct == pCache->nMax*9/10 );
35544   if( createFlag==1 && (
35545         nPinned>=pGroup->mxPinned
35546      || nPinned>=(int)pCache->n90pct
35547      || pcache1UnderMemoryPressure(pCache)
35548   )){
35549     goto fetch_out;
35550   }
35551
35552   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
35553     goto fetch_out;
35554   }
35555
35556   /* Step 4. Try to recycle a page. */
35557   if( pCache->bPurgeable && pGroup->pLruTail && (
35558          (pCache->nPage+1>=pCache->nMax)
35559       || pGroup->nCurrentPage>=pGroup->nMaxPage
35560       || pcache1UnderMemoryPressure(pCache)
35561   )){
35562     PCache1 *pOtherCache;
35563     pPage = pGroup->pLruTail;
35564     pcache1RemoveFromHash(pPage);
35565     pcache1PinPage(pPage);
35566     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
35567       pcache1FreePage(pPage);
35568       pPage = 0;
35569     }else{
35570       pGroup->nCurrentPage -= 
35571                (pOtherCache->bPurgeable - pCache->bPurgeable);
35572     }
35573   }
35574
35575   /* Step 5. If a usable page buffer has still not been found, 
35576   ** attempt to allocate a new one. 
35577   */
35578   if( !pPage ){
35579     if( createFlag==1 ) sqlite3BeginBenignMalloc();
35580     pcache1LeaveMutex(pGroup);
35581     pPage = pcache1AllocPage(pCache);
35582     pcache1EnterMutex(pGroup);
35583     if( createFlag==1 ) sqlite3EndBenignMalloc();
35584   }
35585
35586   if( pPage ){
35587     unsigned int h = iKey % pCache->nHash;
35588     pCache->nPage++;
35589     pPage->iKey = iKey;
35590     pPage->pNext = pCache->apHash[h];
35591     pPage->pCache = pCache;
35592     pPage->pLruPrev = 0;
35593     pPage->pLruNext = 0;
35594     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
35595     pCache->apHash[h] = pPage;
35596   }
35597
35598 fetch_out:
35599   if( pPage && iKey>pCache->iMaxKey ){
35600     pCache->iMaxKey = iKey;
35601   }
35602   pcache1LeaveMutex(pGroup);
35603   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
35604 }
35605
35606
35607 /*
35608 ** Implementation of the sqlite3_pcache.xUnpin method.
35609 **
35610 ** Mark a page as unpinned (eligible for asynchronous recycling).
35611 */
35612 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
35613   PCache1 *pCache = (PCache1 *)p;
35614   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35615   PGroup *pGroup = pCache->pGroup;
35616  
35617   assert( pPage->pCache==pCache );
35618   pcache1EnterMutex(pGroup);
35619
35620   /* It is an error to call this function if the page is already 
35621   ** part of the PGroup LRU list.
35622   */
35623   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
35624   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
35625
35626   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
35627     pcache1RemoveFromHash(pPage);
35628     pcache1FreePage(pPage);
35629   }else{
35630     /* Add the page to the PGroup LRU list. */
35631     if( pGroup->pLruHead ){
35632       pGroup->pLruHead->pLruPrev = pPage;
35633       pPage->pLruNext = pGroup->pLruHead;
35634       pGroup->pLruHead = pPage;
35635     }else{
35636       pGroup->pLruTail = pPage;
35637       pGroup->pLruHead = pPage;
35638     }
35639     pCache->nRecyclable++;
35640   }
35641
35642   pcache1LeaveMutex(pCache->pGroup);
35643 }
35644
35645 /*
35646 ** Implementation of the sqlite3_pcache.xRekey method. 
35647 */
35648 static void pcache1Rekey(
35649   sqlite3_pcache *p,
35650   void *pPg,
35651   unsigned int iOld,
35652   unsigned int iNew
35653 ){
35654   PCache1 *pCache = (PCache1 *)p;
35655   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35656   PgHdr1 **pp;
35657   unsigned int h; 
35658   assert( pPage->iKey==iOld );
35659   assert( pPage->pCache==pCache );
35660
35661   pcache1EnterMutex(pCache->pGroup);
35662
35663   h = iOld%pCache->nHash;
35664   pp = &pCache->apHash[h];
35665   while( (*pp)!=pPage ){
35666     pp = &(*pp)->pNext;
35667   }
35668   *pp = pPage->pNext;
35669
35670   h = iNew%pCache->nHash;
35671   pPage->iKey = iNew;
35672   pPage->pNext = pCache->apHash[h];
35673   pCache->apHash[h] = pPage;
35674   if( iNew>pCache->iMaxKey ){
35675     pCache->iMaxKey = iNew;
35676   }
35677
35678   pcache1LeaveMutex(pCache->pGroup);
35679 }
35680
35681 /*
35682 ** Implementation of the sqlite3_pcache.xTruncate method. 
35683 **
35684 ** Discard all unpinned pages in the cache with a page number equal to
35685 ** or greater than parameter iLimit. Any pinned pages with a page number
35686 ** equal to or greater than iLimit are implicitly unpinned.
35687 */
35688 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
35689   PCache1 *pCache = (PCache1 *)p;
35690   pcache1EnterMutex(pCache->pGroup);
35691   if( iLimit<=pCache->iMaxKey ){
35692     pcache1TruncateUnsafe(pCache, iLimit);
35693     pCache->iMaxKey = iLimit-1;
35694   }
35695   pcache1LeaveMutex(pCache->pGroup);
35696 }
35697
35698 /*
35699 ** Implementation of the sqlite3_pcache.xDestroy method. 
35700 **
35701 ** Destroy a cache allocated using pcache1Create().
35702 */
35703 static void pcache1Destroy(sqlite3_pcache *p){
35704   PCache1 *pCache = (PCache1 *)p;
35705   PGroup *pGroup = pCache->pGroup;
35706   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
35707   pcache1EnterMutex(pGroup);
35708   pcache1TruncateUnsafe(pCache, 0);
35709   pGroup->nMaxPage -= pCache->nMax;
35710   pGroup->nMinPage -= pCache->nMin;
35711   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35712   pcache1EnforceMaxPage(pGroup);
35713   pcache1LeaveMutex(pGroup);
35714   sqlite3_free(pCache->apHash);
35715   sqlite3_free(pCache);
35716 }
35717
35718 /*
35719 ** This function is called during initialization (sqlite3_initialize()) to
35720 ** install the default pluggable cache module, assuming the user has not
35721 ** already provided an alternative.
35722 */
35723 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
35724   static const sqlite3_pcache_methods defaultMethods = {
35725     0,                       /* pArg */
35726     pcache1Init,             /* xInit */
35727     pcache1Shutdown,         /* xShutdown */
35728     pcache1Create,           /* xCreate */
35729     pcache1Cachesize,        /* xCachesize */
35730     pcache1Pagecount,        /* xPagecount */
35731     pcache1Fetch,            /* xFetch */
35732     pcache1Unpin,            /* xUnpin */
35733     pcache1Rekey,            /* xRekey */
35734     pcache1Truncate,         /* xTruncate */
35735     pcache1Destroy           /* xDestroy */
35736   };
35737   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
35738 }
35739
35740 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35741 /*
35742 ** This function is called to free superfluous dynamically allocated memory
35743 ** held by the pager system. Memory in use by any SQLite pager allocated
35744 ** by the current thread may be sqlite3_free()ed.
35745 **
35746 ** nReq is the number of bytes of memory required. Once this much has
35747 ** been released, the function returns. The return value is the total number 
35748 ** of bytes of memory released.
35749 */
35750 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
35751   int nFree = 0;
35752   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35753   assert( sqlite3_mutex_notheld(pcache1.mutex) );
35754   if( pcache1.pStart==0 ){
35755     PgHdr1 *p;
35756     pcache1EnterMutex(&pcache1.grp);
35757     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
35758       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
35759       pcache1PinPage(p);
35760       pcache1RemoveFromHash(p);
35761       pcache1FreePage(p);
35762     }
35763     pcache1LeaveMutex(&pcache1.grp);
35764   }
35765   return nFree;
35766 }
35767 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35768
35769 #ifdef SQLITE_TEST
35770 /*
35771 ** This function is used by test procedures to inspect the internal state
35772 ** of the global cache.
35773 */
35774 SQLITE_PRIVATE void sqlite3PcacheStats(
35775   int *pnCurrent,      /* OUT: Total number of pages cached */
35776   int *pnMax,          /* OUT: Global maximum cache size */
35777   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
35778   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
35779 ){
35780   PgHdr1 *p;
35781   int nRecyclable = 0;
35782   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
35783     nRecyclable++;
35784   }
35785   *pnCurrent = pcache1.grp.nCurrentPage;
35786   *pnMax = pcache1.grp.nMaxPage;
35787   *pnMin = pcache1.grp.nMinPage;
35788   *pnRecyclable = nRecyclable;
35789 }
35790 #endif
35791
35792 /************** End of pcache1.c *********************************************/
35793 /************** Begin file rowset.c ******************************************/
35794 /*
35795 ** 2008 December 3
35796 **
35797 ** The author disclaims copyright to this source code.  In place of
35798 ** a legal notice, here is a blessing:
35799 **
35800 **    May you do good and not evil.
35801 **    May you find forgiveness for yourself and forgive others.
35802 **    May you share freely, never taking more than you give.
35803 **
35804 *************************************************************************
35805 **
35806 ** This module implements an object we call a "RowSet".
35807 **
35808 ** The RowSet object is a collection of rowids.  Rowids
35809 ** are inserted into the RowSet in an arbitrary order.  Inserts
35810 ** can be intermixed with tests to see if a given rowid has been
35811 ** previously inserted into the RowSet.
35812 **
35813 ** After all inserts are finished, it is possible to extract the
35814 ** elements of the RowSet in sorted order.  Once this extraction
35815 ** process has started, no new elements may be inserted.
35816 **
35817 ** Hence, the primitive operations for a RowSet are:
35818 **
35819 **    CREATE
35820 **    INSERT
35821 **    TEST
35822 **    SMALLEST
35823 **    DESTROY
35824 **
35825 ** The CREATE and DESTROY primitives are the constructor and destructor,
35826 ** obviously.  The INSERT primitive adds a new element to the RowSet.
35827 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
35828 ** extracts the least value from the RowSet.
35829 **
35830 ** The INSERT primitive might allocate additional memory.  Memory is
35831 ** allocated in chunks so most INSERTs do no allocation.  There is an 
35832 ** upper bound on the size of allocated memory.  No memory is freed
35833 ** until DESTROY.
35834 **
35835 ** The TEST primitive includes a "batch" number.  The TEST primitive
35836 ** will only see elements that were inserted before the last change
35837 ** in the batch number.  In other words, if an INSERT occurs between
35838 ** two TESTs where the TESTs have the same batch nubmer, then the
35839 ** value added by the INSERT will not be visible to the second TEST.
35840 ** The initial batch number is zero, so if the very first TEST contains
35841 ** a non-zero batch number, it will see all prior INSERTs.
35842 **
35843 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
35844 ** that is attempted.
35845 **
35846 ** The cost of an INSERT is roughly constant.  (Sometime new memory
35847 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
35848 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
35849 ** The cost of a TEST using the same batch number is O(logN).  The cost
35850 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
35851 ** primitives are constant time.  The cost of DESTROY is O(N).
35852 **
35853 ** There is an added cost of O(N) when switching between TEST and
35854 ** SMALLEST primitives.
35855 */
35856
35857
35858 /*
35859 ** Target size for allocation chunks.
35860 */
35861 #define ROWSET_ALLOCATION_SIZE 1024
35862
35863 /*
35864 ** The number of rowset entries per allocation chunk.
35865 */
35866 #define ROWSET_ENTRY_PER_CHUNK  \
35867                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
35868
35869 /*
35870 ** Each entry in a RowSet is an instance of the following object.
35871 */
35872 struct RowSetEntry {            
35873   i64 v;                        /* ROWID value for this entry */
35874   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
35875   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
35876 };
35877
35878 /*
35879 ** RowSetEntry objects are allocated in large chunks (instances of the
35880 ** following structure) to reduce memory allocation overhead.  The
35881 ** chunks are kept on a linked list so that they can be deallocated
35882 ** when the RowSet is destroyed.
35883 */
35884 struct RowSetChunk {
35885   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
35886   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
35887 };
35888
35889 /*
35890 ** A RowSet in an instance of the following structure.
35891 **
35892 ** A typedef of this structure if found in sqliteInt.h.
35893 */
35894 struct RowSet {
35895   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
35896   sqlite3 *db;                   /* The database connection */
35897   struct RowSetEntry *pEntry;    /* List of entries using pRight */
35898   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
35899   struct RowSetEntry *pFresh;    /* Source of new entry objects */
35900   struct RowSetEntry *pTree;     /* Binary tree of entries */
35901   u16 nFresh;                    /* Number of objects on pFresh */
35902   u8 isSorted;                   /* True if pEntry is sorted */
35903   u8 iBatch;                     /* Current insert batch */
35904 };
35905
35906 /*
35907 ** Turn bulk memory into a RowSet object.  N bytes of memory
35908 ** are available at pSpace.  The db pointer is used as a memory context
35909 ** for any subsequent allocations that need to occur.
35910 ** Return a pointer to the new RowSet object.
35911 **
35912 ** It must be the case that N is sufficient to make a Rowset.  If not
35913 ** an assertion fault occurs.
35914 ** 
35915 ** If N is larger than the minimum, use the surplus as an initial
35916 ** allocation of entries available to be filled.
35917 */
35918 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
35919   RowSet *p;
35920   assert( N >= ROUND8(sizeof(*p)) );
35921   p = pSpace;
35922   p->pChunk = 0;
35923   p->db = db;
35924   p->pEntry = 0;
35925   p->pLast = 0;
35926   p->pTree = 0;
35927   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
35928   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
35929   p->isSorted = 1;
35930   p->iBatch = 0;
35931   return p;
35932 }
35933
35934 /*
35935 ** Deallocate all chunks from a RowSet.  This frees all memory that
35936 ** the RowSet has allocated over its lifetime.  This routine is
35937 ** the destructor for the RowSet.
35938 */
35939 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
35940   struct RowSetChunk *pChunk, *pNextChunk;
35941   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
35942     pNextChunk = pChunk->pNextChunk;
35943     sqlite3DbFree(p->db, pChunk);
35944   }
35945   p->pChunk = 0;
35946   p->nFresh = 0;
35947   p->pEntry = 0;
35948   p->pLast = 0;
35949   p->pTree = 0;
35950   p->isSorted = 1;
35951 }
35952
35953 /*
35954 ** Insert a new value into a RowSet.
35955 **
35956 ** The mallocFailed flag of the database connection is set if a
35957 ** memory allocation fails.
35958 */
35959 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
35960   struct RowSetEntry *pEntry;  /* The new entry */
35961   struct RowSetEntry *pLast;   /* The last prior entry */
35962   assert( p!=0 );
35963   if( p->nFresh==0 ){
35964     struct RowSetChunk *pNew;
35965     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
35966     if( pNew==0 ){
35967       return;
35968     }
35969     pNew->pNextChunk = p->pChunk;
35970     p->pChunk = pNew;
35971     p->pFresh = pNew->aEntry;
35972     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
35973   }
35974   pEntry = p->pFresh++;
35975   p->nFresh--;
35976   pEntry->v = rowid;
35977   pEntry->pRight = 0;
35978   pLast = p->pLast;
35979   if( pLast ){
35980     if( p->isSorted && rowid<=pLast->v ){
35981       p->isSorted = 0;
35982     }
35983     pLast->pRight = pEntry;
35984   }else{
35985     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
35986     p->pEntry = pEntry;
35987   }
35988   p->pLast = pEntry;
35989 }
35990
35991 /*
35992 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
35993 **
35994 ** The input lists are connected via pRight pointers and are 
35995 ** assumed to each already be in sorted order.
35996 */
35997 static struct RowSetEntry *rowSetMerge(
35998   struct RowSetEntry *pA,    /* First sorted list to be merged */
35999   struct RowSetEntry *pB     /* Second sorted list to be merged */
36000 ){
36001   struct RowSetEntry head;
36002   struct RowSetEntry *pTail;
36003
36004   pTail = &head;
36005   while( pA && pB ){
36006     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36007     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36008     if( pA->v<pB->v ){
36009       pTail->pRight = pA;
36010       pA = pA->pRight;
36011       pTail = pTail->pRight;
36012     }else if( pB->v<pA->v ){
36013       pTail->pRight = pB;
36014       pB = pB->pRight;
36015       pTail = pTail->pRight;
36016     }else{
36017       pA = pA->pRight;
36018     }
36019   }
36020   if( pA ){
36021     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36022     pTail->pRight = pA;
36023   }else{
36024     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36025     pTail->pRight = pB;
36026   }
36027   return head.pRight;
36028 }
36029
36030 /*
36031 ** Sort all elements on the pEntry list of the RowSet into ascending order.
36032 */ 
36033 static void rowSetSort(RowSet *p){
36034   unsigned int i;
36035   struct RowSetEntry *pEntry;
36036   struct RowSetEntry *aBucket[40];
36037
36038   assert( p->isSorted==0 );
36039   memset(aBucket, 0, sizeof(aBucket));
36040   while( p->pEntry ){
36041     pEntry = p->pEntry;
36042     p->pEntry = pEntry->pRight;
36043     pEntry->pRight = 0;
36044     for(i=0; aBucket[i]; i++){
36045       pEntry = rowSetMerge(aBucket[i], pEntry);
36046       aBucket[i] = 0;
36047     }
36048     aBucket[i] = pEntry;
36049   }
36050   pEntry = 0;
36051   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36052     pEntry = rowSetMerge(pEntry, aBucket[i]);
36053   }
36054   p->pEntry = pEntry;
36055   p->pLast = 0;
36056   p->isSorted = 1;
36057 }
36058
36059
36060 /*
36061 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36062 ** Convert this tree into a linked list connected by the pRight pointers
36063 ** and return pointers to the first and last elements of the new list.
36064 */
36065 static void rowSetTreeToList(
36066   struct RowSetEntry *pIn,         /* Root of the input tree */
36067   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36068   struct RowSetEntry **ppLast      /* Write tail of the output list here */
36069 ){
36070   assert( pIn!=0 );
36071   if( pIn->pLeft ){
36072     struct RowSetEntry *p;
36073     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36074     p->pRight = pIn;
36075   }else{
36076     *ppFirst = pIn;
36077   }
36078   if( pIn->pRight ){
36079     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36080   }else{
36081     *ppLast = pIn;
36082   }
36083   assert( (*ppLast)->pRight==0 );
36084 }
36085
36086
36087 /*
36088 ** Convert a sorted list of elements (connected by pRight) into a binary
36089 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36090 ** node taken from the head of *ppList.  A depth of 2 means a tree with
36091 ** three nodes.  And so forth.
36092 **
36093 ** Use as many entries from the input list as required and update the
36094 ** *ppList to point to the unused elements of the list.  If the input
36095 ** list contains too few elements, then construct an incomplete tree
36096 ** and leave *ppList set to NULL.
36097 **
36098 ** Return a pointer to the root of the constructed binary tree.
36099 */
36100 static struct RowSetEntry *rowSetNDeepTree(
36101   struct RowSetEntry **ppList,
36102   int iDepth
36103 ){
36104   struct RowSetEntry *p;         /* Root of the new tree */
36105   struct RowSetEntry *pLeft;     /* Left subtree */
36106   if( *ppList==0 ){
36107     return 0;
36108   }
36109   if( iDepth==1 ){
36110     p = *ppList;
36111     *ppList = p->pRight;
36112     p->pLeft = p->pRight = 0;
36113     return p;
36114   }
36115   pLeft = rowSetNDeepTree(ppList, iDepth-1);
36116   p = *ppList;
36117   if( p==0 ){
36118     return pLeft;
36119   }
36120   p->pLeft = pLeft;
36121   *ppList = p->pRight;
36122   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36123   return p;
36124 }
36125
36126 /*
36127 ** Convert a sorted list of elements into a binary tree. Make the tree
36128 ** as deep as it needs to be in order to contain the entire list.
36129 */
36130 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36131   int iDepth;           /* Depth of the tree so far */
36132   struct RowSetEntry *p;       /* Current tree root */
36133   struct RowSetEntry *pLeft;   /* Left subtree */
36134
36135   assert( pList!=0 );
36136   p = pList;
36137   pList = p->pRight;
36138   p->pLeft = p->pRight = 0;
36139   for(iDepth=1; pList; iDepth++){
36140     pLeft = p;
36141     p = pList;
36142     pList = p->pRight;
36143     p->pLeft = pLeft;
36144     p->pRight = rowSetNDeepTree(&pList, iDepth);
36145   }
36146   return p;
36147 }
36148
36149 /*
36150 ** Convert the list in p->pEntry into a sorted list if it is not
36151 ** sorted already.  If there is a binary tree on p->pTree, then
36152 ** convert it into a list too and merge it into the p->pEntry list.
36153 */
36154 static void rowSetToList(RowSet *p){
36155   if( !p->isSorted ){
36156     rowSetSort(p);
36157   }
36158   if( p->pTree ){
36159     struct RowSetEntry *pHead, *pTail;
36160     rowSetTreeToList(p->pTree, &pHead, &pTail);
36161     p->pTree = 0;
36162     p->pEntry = rowSetMerge(p->pEntry, pHead);
36163   }
36164 }
36165
36166 /*
36167 ** Extract the smallest element from the RowSet.
36168 ** Write the element into *pRowid.  Return 1 on success.  Return
36169 ** 0 if the RowSet is already empty.
36170 **
36171 ** After this routine has been called, the sqlite3RowSetInsert()
36172 ** routine may not be called again.  
36173 */
36174 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36175   rowSetToList(p);
36176   if( p->pEntry ){
36177     *pRowid = p->pEntry->v;
36178     p->pEntry = p->pEntry->pRight;
36179     if( p->pEntry==0 ){
36180       sqlite3RowSetClear(p);
36181     }
36182     return 1;
36183   }else{
36184     return 0;
36185   }
36186 }
36187
36188 /*
36189 ** Check to see if element iRowid was inserted into the the rowset as
36190 ** part of any insert batch prior to iBatch.  Return 1 or 0.
36191 */
36192 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36193   struct RowSetEntry *p;
36194   if( iBatch!=pRowSet->iBatch ){
36195     if( pRowSet->pEntry ){
36196       rowSetToList(pRowSet);
36197       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36198       pRowSet->pEntry = 0;
36199       pRowSet->pLast = 0;
36200     }
36201     pRowSet->iBatch = iBatch;
36202   }
36203   p = pRowSet->pTree;
36204   while( p ){
36205     if( p->v<iRowid ){
36206       p = p->pRight;
36207     }else if( p->v>iRowid ){
36208       p = p->pLeft;
36209     }else{
36210       return 1;
36211     }
36212   }
36213   return 0;
36214 }
36215
36216 /************** End of rowset.c **********************************************/
36217 /************** Begin file pager.c *******************************************/
36218 /*
36219 ** 2001 September 15
36220 **
36221 ** The author disclaims copyright to this source code.  In place of
36222 ** a legal notice, here is a blessing:
36223 **
36224 **    May you do good and not evil.
36225 **    May you find forgiveness for yourself and forgive others.
36226 **    May you share freely, never taking more than you give.
36227 **
36228 *************************************************************************
36229 ** This is the implementation of the page cache subsystem or "pager".
36230 ** 
36231 ** The pager is used to access a database disk file.  It implements
36232 ** atomic commit and rollback through the use of a journal file that
36233 ** is separate from the database file.  The pager also implements file
36234 ** locking to prevent two processes from writing the same database
36235 ** file simultaneously, or one process from reading the database while
36236 ** another is writing.
36237 */
36238 #ifndef SQLITE_OMIT_DISKIO
36239 /************** Include wal.h in the middle of pager.c ***********************/
36240 /************** Begin file wal.h *********************************************/
36241 /*
36242 ** 2010 February 1
36243 **
36244 ** The author disclaims copyright to this source code.  In place of
36245 ** a legal notice, here is a blessing:
36246 **
36247 **    May you do good and not evil.
36248 **    May you find forgiveness for yourself and forgive others.
36249 **    May you share freely, never taking more than you give.
36250 **
36251 *************************************************************************
36252 ** This header file defines the interface to the write-ahead logging 
36253 ** system. Refer to the comments below and the header comment attached to 
36254 ** the implementation of each function in log.c for further details.
36255 */
36256
36257 #ifndef _WAL_H_
36258 #define _WAL_H_
36259
36260
36261 #ifdef SQLITE_OMIT_WAL
36262 # define sqlite3WalOpen(x,y,z)                   0
36263 # define sqlite3WalClose(w,x,y,z)                0
36264 # define sqlite3WalBeginReadTransaction(y,z)     0
36265 # define sqlite3WalEndReadTransaction(z)
36266 # define sqlite3WalRead(v,w,x,y,z)               0
36267 # define sqlite3WalDbsize(y)                     0
36268 # define sqlite3WalBeginWriteTransaction(y)      0
36269 # define sqlite3WalEndWriteTransaction(x)        0
36270 # define sqlite3WalUndo(x,y,z)                   0
36271 # define sqlite3WalSavepoint(y,z)
36272 # define sqlite3WalSavepointUndo(y,z)            0
36273 # define sqlite3WalFrames(u,v,w,x,y,z)           0
36274 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36275 # define sqlite3WalCallback(z)                   0
36276 # define sqlite3WalExclusiveMode(y,z)            0
36277 # define sqlite3WalHeapMemory(z)                 0
36278 #else
36279
36280 #define WAL_SAVEPOINT_NDATA 4
36281
36282 /* Connection to a write-ahead log (WAL) file. 
36283 ** There is one object of this type for each pager. 
36284 */
36285 typedef struct Wal Wal;
36286
36287 /* Open and close a connection to a write-ahead log. */
36288 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
36289 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36290
36291 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
36292 ** snapshot is like a read-transaction.  It is the state of the database
36293 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
36294 ** preserves the current state even if the other threads or processes
36295 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
36296 ** transaction and releases the lock.
36297 */
36298 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36299 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36300
36301 /* Read a page from the write-ahead log, if it is present. */
36302 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36303
36304 /* If the WAL is not empty, return the size of the database. */
36305 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36306
36307 /* Obtain or release the WRITER lock. */
36308 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36309 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36310
36311 /* Undo any frames written (but not committed) to the log */
36312 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36313
36314 /* Return an integer that records the current (uncommitted) write
36315 ** position in the WAL */
36316 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36317
36318 /* Move the write position of the WAL back to iFrame.  Called in
36319 ** response to a ROLLBACK TO command. */
36320 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36321
36322 /* Write a frame or frames to the log. */
36323 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36324
36325 /* Copy pages from the log to the database file */ 
36326 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36327   Wal *pWal,                      /* Write-ahead log connection */
36328   int eMode,                      /* One of PASSIVE, FULL and RESTART */
36329   int (*xBusy)(void*),            /* Function to call when busy */
36330   void *pBusyArg,                 /* Context argument for xBusyHandler */
36331   int sync_flags,                 /* Flags to sync db file with (or 0) */
36332   int nBuf,                       /* Size of buffer nBuf */
36333   u8 *zBuf,                       /* Temporary buffer to use */
36334   int *pnLog,                     /* OUT: Number of frames in WAL */
36335   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
36336 );
36337
36338 /* Return the value to pass to a sqlite3_wal_hook callback, the
36339 ** number of frames in the WAL at the point of the last commit since
36340 ** sqlite3WalCallback() was called.  If no commits have occurred since
36341 ** the last call, then return 0.
36342 */
36343 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36344
36345 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36346 ** by the pager layer on the database file.
36347 */
36348 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36349
36350 /* Return true if the argument is non-NULL and the WAL module is using
36351 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36352 ** WAL module is using shared-memory, return false. 
36353 */
36354 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36355
36356 #endif /* ifndef SQLITE_OMIT_WAL */
36357 #endif /* _WAL_H_ */
36358
36359 /************** End of wal.h *************************************************/
36360 /************** Continuing where we left off in pager.c **********************/
36361
36362
36363 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36364 **
36365 ** This comment block describes invariants that hold when using a rollback
36366 ** journal.  These invariants do not apply for journal_mode=WAL,
36367 ** journal_mode=MEMORY, or journal_mode=OFF.
36368 **
36369 ** Within this comment block, a page is deemed to have been synced
36370 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36371 ** Otherwise, the page is not synced until the xSync method of the VFS
36372 ** is called successfully on the file containing the page.
36373 **
36374 ** Definition:  A page of the database file is said to be "overwriteable" if
36375 ** one or more of the following are true about the page:
36376 ** 
36377 **     (a)  The original content of the page as it was at the beginning of
36378 **          the transaction has been written into the rollback journal and
36379 **          synced.
36380 ** 
36381 **     (b)  The page was a freelist leaf page at the start of the transaction.
36382 ** 
36383 **     (c)  The page number is greater than the largest page that existed in
36384 **          the database file at the start of the transaction.
36385 ** 
36386 ** (1) A page of the database file is never overwritten unless one of the
36387 **     following are true:
36388 ** 
36389 **     (a) The page and all other pages on the same sector are overwriteable.
36390 ** 
36391 **     (b) The atomic page write optimization is enabled, and the entire
36392 **         transaction other than the update of the transaction sequence
36393 **         number consists of a single page change.
36394 ** 
36395 ** (2) The content of a page written into the rollback journal exactly matches
36396 **     both the content in the database when the rollback journal was written
36397 **     and the content in the database at the beginning of the current
36398 **     transaction.
36399 ** 
36400 ** (3) Writes to the database file are an integer multiple of the page size
36401 **     in length and are aligned on a page boundary.
36402 ** 
36403 ** (4) Reads from the database file are either aligned on a page boundary and
36404 **     an integer multiple of the page size in length or are taken from the
36405 **     first 100 bytes of the database file.
36406 ** 
36407 ** (5) All writes to the database file are synced prior to the rollback journal
36408 **     being deleted, truncated, or zeroed.
36409 ** 
36410 ** (6) If a master journal file is used, then all writes to the database file
36411 **     are synced prior to the master journal being deleted.
36412 ** 
36413 ** Definition: Two databases (or the same database at two points it time)
36414 ** are said to be "logically equivalent" if they give the same answer to
36415 ** all queries.  Note in particular the the content of freelist leaf
36416 ** pages can be changed arbitarily without effecting the logical equivalence
36417 ** of the database.
36418 ** 
36419 ** (7) At any time, if any subset, including the empty set and the total set,
36420 **     of the unsynced changes to a rollback journal are removed and the 
36421 **     journal is rolled back, the resulting database file will be logical
36422 **     equivalent to the database file at the beginning of the transaction.
36423 ** 
36424 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
36425 **     is called to restore the database file to the same size it was at
36426 **     the beginning of the transaction.  (In some VFSes, the xTruncate
36427 **     method is a no-op, but that does not change the fact the SQLite will
36428 **     invoke it.)
36429 ** 
36430 ** (9) Whenever the database file is modified, at least one bit in the range
36431 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
36432 **     the EXCLUSIVE lock, thus signaling other connections on the same
36433 **     database to flush their caches.
36434 **
36435 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36436 **      than one billion transactions.
36437 **
36438 ** (11) A database file is well-formed at the beginning and at the conclusion
36439 **      of every transaction.
36440 **
36441 ** (12) An EXCLUSIVE lock is held on the database file when writing to
36442 **      the database file.
36443 **
36444 ** (13) A SHARED lock is held on the database file while reading any
36445 **      content out of the database file.
36446 **
36447 ******************************************************************************/
36448
36449 /*
36450 ** Macros for troubleshooting.  Normally turned off
36451 */
36452 #if 0
36453 int sqlite3PagerTrace=1;  /* True to enable tracing */
36454 #define sqlite3DebugPrintf printf
36455 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36456 #else
36457 #define PAGERTRACE(X)
36458 #endif
36459
36460 /*
36461 ** The following two macros are used within the PAGERTRACE() macros above
36462 ** to print out file-descriptors. 
36463 **
36464 ** PAGERID() takes a pointer to a Pager struct as its argument. The
36465 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36466 ** struct as its argument.
36467 */
36468 #define PAGERID(p) ((int)(p->fd))
36469 #define FILEHANDLEID(fd) ((int)fd)
36470
36471 /*
36472 ** The Pager.eState variable stores the current 'state' of a pager. A
36473 ** pager may be in any one of the seven states shown in the following
36474 ** state diagram.
36475 **
36476 **                            OPEN <------+------+
36477 **                              |         |      |
36478 **                              V         |      |
36479 **               +---------> READER-------+      |
36480 **               |              |                |
36481 **               |              V                |
36482 **               |<-------WRITER_LOCKED------> ERROR
36483 **               |              |                ^  
36484 **               |              V                |
36485 **               |<------WRITER_CACHEMOD-------->|
36486 **               |              |                |
36487 **               |              V                |
36488 **               |<-------WRITER_DBMOD---------->|
36489 **               |              |                |
36490 **               |              V                |
36491 **               +<------WRITER_FINISHED-------->+
36492 **
36493 **
36494 ** List of state transitions and the C [function] that performs each:
36495 ** 
36496 **   OPEN              -> READER              [sqlite3PagerSharedLock]
36497 **   READER            -> OPEN                [pager_unlock]
36498 **
36499 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
36500 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
36501 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
36502 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
36503 **   WRITER_***        -> READER              [pager_end_transaction]
36504 **
36505 **   WRITER_***        -> ERROR               [pager_error]
36506 **   ERROR             -> OPEN                [pager_unlock]
36507 ** 
36508 **
36509 **  OPEN:
36510 **
36511 **    The pager starts up in this state. Nothing is guaranteed in this
36512 **    state - the file may or may not be locked and the database size is
36513 **    unknown. The database may not be read or written.
36514 **
36515 **    * No read or write transaction is active.
36516 **    * Any lock, or no lock at all, may be held on the database file.
36517 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36518 **
36519 **  READER:
36520 **
36521 **    In this state all the requirements for reading the database in 
36522 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
36523 **    was) in exclusive-locking mode, a user-level read transaction is 
36524 **    open. The database size is known in this state.
36525 **
36526 **    A connection running with locking_mode=normal enters this state when
36527 **    it opens a read-transaction on the database and returns to state
36528 **    OPEN after the read-transaction is completed. However a connection
36529 **    running in locking_mode=exclusive (including temp databases) remains in
36530 **    this state even after the read-transaction is closed. The only way
36531 **    a locking_mode=exclusive connection can transition from READER to OPEN
36532 **    is via the ERROR state (see below).
36533 ** 
36534 **    * A read transaction may be active (but a write-transaction cannot).
36535 **    * A SHARED or greater lock is held on the database file.
36536 **    * The dbSize variable may be trusted (even if a user-level read 
36537 **      transaction is not active). The dbOrigSize and dbFileSize variables
36538 **      may not be trusted at this point.
36539 **    * If the database is a WAL database, then the WAL connection is open.
36540 **    * Even if a read-transaction is not open, it is guaranteed that 
36541 **      there is no hot-journal in the file-system.
36542 **
36543 **  WRITER_LOCKED:
36544 **
36545 **    The pager moves to this state from READER when a write-transaction
36546 **    is first opened on the database. In WRITER_LOCKED state, all locks 
36547 **    required to start a write-transaction are held, but no actual 
36548 **    modifications to the cache or database have taken place.
36549 **
36550 **    In rollback mode, a RESERVED or (if the transaction was opened with 
36551 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
36552 **    moving to this state, but the journal file is not written to or opened 
36553 **    to in this state. If the transaction is committed or rolled back while 
36554 **    in WRITER_LOCKED state, all that is required is to unlock the database 
36555 **    file.
36556 **
36557 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
36558 **    If the connection is running with locking_mode=exclusive, an attempt
36559 **    is made to obtain an EXCLUSIVE lock on the database file.
36560 **
36561 **    * A write transaction is active.
36562 **    * If the connection is open in rollback-mode, a RESERVED or greater 
36563 **      lock is held on the database file.
36564 **    * If the connection is open in WAL-mode, a WAL write transaction
36565 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
36566 **      called).
36567 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
36568 **    * The contents of the pager cache have not been modified.
36569 **    * The journal file may or may not be open.
36570 **    * Nothing (not even the first header) has been written to the journal.
36571 **
36572 **  WRITER_CACHEMOD:
36573 **
36574 **    A pager moves from WRITER_LOCKED state to this state when a page is
36575 **    first modified by the upper layer. In rollback mode the journal file
36576 **    is opened (if it is not already open) and a header written to the
36577 **    start of it. The database file on disk has not been modified.
36578 **
36579 **    * A write transaction is active.
36580 **    * A RESERVED or greater lock is held on the database file.
36581 **    * The journal file is open and the first header has been written 
36582 **      to it, but the header has not been synced to disk.
36583 **    * The contents of the page cache have been modified.
36584 **
36585 **  WRITER_DBMOD:
36586 **
36587 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
36588 **    when it modifies the contents of the database file. WAL connections
36589 **    never enter this state (since they do not modify the database file,
36590 **    just the log file).
36591 **
36592 **    * A write transaction is active.
36593 **    * An EXCLUSIVE or greater lock is held on the database file.
36594 **    * The journal file is open and the first header has been written 
36595 **      and synced to disk.
36596 **    * The contents of the page cache have been modified (and possibly
36597 **      written to disk).
36598 **
36599 **  WRITER_FINISHED:
36600 **
36601 **    It is not possible for a WAL connection to enter this state.
36602 **
36603 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
36604 **    state after the entire transaction has been successfully written into the
36605 **    database file. In this state the transaction may be committed simply
36606 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
36607 **    not possible to modify the database further. At this point, the upper 
36608 **    layer must either commit or rollback the transaction.
36609 **
36610 **    * A write transaction is active.
36611 **    * An EXCLUSIVE or greater lock is held on the database file.
36612 **    * All writing and syncing of journal and database data has finished.
36613 **      If no error occured, all that remains is to finalize the journal to
36614 **      commit the transaction. If an error did occur, the caller will need
36615 **      to rollback the transaction. 
36616 **
36617 **  ERROR:
36618 **
36619 **    The ERROR state is entered when an IO or disk-full error (including
36620 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
36621 **    difficult to be sure that the in-memory pager state (cache contents, 
36622 **    db size etc.) are consistent with the contents of the file-system.
36623 **
36624 **    Temporary pager files may enter the ERROR state, but in-memory pagers
36625 **    cannot.
36626 **
36627 **    For example, if an IO error occurs while performing a rollback, 
36628 **    the contents of the page-cache may be left in an inconsistent state.
36629 **    At this point it would be dangerous to change back to READER state
36630 **    (as usually happens after a rollback). Any subsequent readers might
36631 **    report database corruption (due to the inconsistent cache), and if
36632 **    they upgrade to writers, they may inadvertently corrupt the database
36633 **    file. To avoid this hazard, the pager switches into the ERROR state
36634 **    instead of READER following such an error.
36635 **
36636 **    Once it has entered the ERROR state, any attempt to use the pager
36637 **    to read or write data returns an error. Eventually, once all 
36638 **    outstanding transactions have been abandoned, the pager is able to
36639 **    transition back to OPEN state, discarding the contents of the 
36640 **    page-cache and any other in-memory state at the same time. Everything
36641 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
36642 **    when a read-transaction is next opened on the pager (transitioning
36643 **    the pager into READER state). At that point the system has recovered 
36644 **    from the error.
36645 **
36646 **    Specifically, the pager jumps into the ERROR state if:
36647 **
36648 **      1. An error occurs while attempting a rollback. This happens in
36649 **         function sqlite3PagerRollback().
36650 **
36651 **      2. An error occurs while attempting to finalize a journal file
36652 **         following a commit in function sqlite3PagerCommitPhaseTwo().
36653 **
36654 **      3. An error occurs while attempting to write to the journal or
36655 **         database file in function pagerStress() in order to free up
36656 **         memory.
36657 **
36658 **    In other cases, the error is returned to the b-tree layer. The b-tree
36659 **    layer then attempts a rollback operation. If the error condition 
36660 **    persists, the pager enters the ERROR state via condition (1) above.
36661 **
36662 **    Condition (3) is necessary because it can be triggered by a read-only
36663 **    statement executed within a transaction. In this case, if the error
36664 **    code were simply returned to the user, the b-tree layer would not
36665 **    automatically attempt a rollback, as it assumes that an error in a
36666 **    read-only statement cannot leave the pager in an internally inconsistent 
36667 **    state.
36668 **
36669 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
36670 **    * There are one or more outstanding references to pages (after the
36671 **      last reference is dropped the pager should move back to OPEN state).
36672 **    * The pager is not an in-memory pager.
36673 **    
36674 **
36675 ** Notes:
36676 **
36677 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
36678 **     connection is open in WAL mode. A WAL connection is always in one
36679 **     of the first four states.
36680 **
36681 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
36682 **     state. There are two exceptions: immediately after exclusive-mode has
36683 **     been turned on (and before any read or write transactions are 
36684 **     executed), and when the pager is leaving the "error state".
36685 **
36686 **   * See also: assert_pager_state().
36687 */
36688 #define PAGER_OPEN                  0
36689 #define PAGER_READER                1
36690 #define PAGER_WRITER_LOCKED         2
36691 #define PAGER_WRITER_CACHEMOD       3
36692 #define PAGER_WRITER_DBMOD          4
36693 #define PAGER_WRITER_FINISHED       5
36694 #define PAGER_ERROR                 6
36695
36696 /*
36697 ** The Pager.eLock variable is almost always set to one of the 
36698 ** following locking-states, according to the lock currently held on
36699 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36700 ** This variable is kept up to date as locks are taken and released by
36701 ** the pagerLockDb() and pagerUnlockDb() wrappers.
36702 **
36703 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36704 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36705 ** the operation was successful. In these circumstances pagerLockDb() and
36706 ** pagerUnlockDb() take a conservative approach - eLock is always updated
36707 ** when unlocking the file, and only updated when locking the file if the
36708 ** VFS call is successful. This way, the Pager.eLock variable may be set
36709 ** to a less exclusive (lower) value than the lock that is actually held
36710 ** at the system level, but it is never set to a more exclusive value.
36711 **
36712 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
36713 ** be a few redundant xLock() calls or a lock may be held for longer than
36714 ** required, but nothing really goes wrong.
36715 **
36716 ** The exception is when the database file is unlocked as the pager moves
36717 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
36718 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
36719 ** transition, by the same pager or any other). If the call to xUnlock()
36720 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
36721 ** can confuse the call to xCheckReservedLock() call made later as part
36722 ** of hot-journal detection.
36723 **
36724 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
36725 ** lock held by this process or any others". So xCheckReservedLock may 
36726 ** return true because the caller itself is holding an EXCLUSIVE lock (but
36727 ** doesn't know it because of a previous error in xUnlock). If this happens
36728 ** a hot-journal may be mistaken for a journal being created by an active
36729 ** transaction in another process, causing SQLite to read from the database
36730 ** without rolling it back.
36731 **
36732 ** To work around this, if a call to xUnlock() fails when unlocking the
36733 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
36734 ** is only changed back to a real locking state after a successful call
36735 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
36736 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
36737 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
36738 ** lock on the database file before attempting to roll it back. See function
36739 ** PagerSharedLock() for more detail.
36740 **
36741 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
36742 ** PAGER_OPEN state.
36743 */
36744 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
36745
36746 /*
36747 ** A macro used for invoking the codec if there is one
36748 */
36749 #ifdef SQLITE_HAS_CODEC
36750 # define CODEC1(P,D,N,X,E) \
36751     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
36752 # define CODEC2(P,D,N,X,E,O) \
36753     if( P->xCodec==0 ){ O=(char*)D; }else \
36754     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
36755 #else
36756 # define CODEC1(P,D,N,X,E)   /* NO-OP */
36757 # define CODEC2(P,D,N,X,E,O) O=(char*)D
36758 #endif
36759
36760 /*
36761 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
36762 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
36763 ** This could conceivably cause corruption following a power failure on
36764 ** such a system. This is currently an undocumented limit.
36765 */
36766 #define MAX_SECTOR_SIZE 0x10000
36767
36768 /*
36769 ** An instance of the following structure is allocated for each active
36770 ** savepoint and statement transaction in the system. All such structures
36771 ** are stored in the Pager.aSavepoint[] array, which is allocated and
36772 ** resized using sqlite3Realloc().
36773 **
36774 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
36775 ** set to 0. If a journal-header is written into the main journal while
36776 ** the savepoint is active, then iHdrOffset is set to the byte offset 
36777 ** immediately following the last journal record written into the main
36778 ** journal before the journal-header. This is required during savepoint
36779 ** rollback (see pagerPlaybackSavepoint()).
36780 */
36781 typedef struct PagerSavepoint PagerSavepoint;
36782 struct PagerSavepoint {
36783   i64 iOffset;                 /* Starting offset in main journal */
36784   i64 iHdrOffset;              /* See above */
36785   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
36786   Pgno nOrig;                  /* Original number of pages in file */
36787   Pgno iSubRec;                /* Index of first record in sub-journal */
36788 #ifndef SQLITE_OMIT_WAL
36789   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
36790 #endif
36791 };
36792
36793 /*
36794 ** A open page cache is an instance of struct Pager. A description of
36795 ** some of the more important member variables follows:
36796 **
36797 ** eState
36798 **
36799 **   The current 'state' of the pager object. See the comment and state
36800 **   diagram above for a description of the pager state.
36801 **
36802 ** eLock
36803 **
36804 **   For a real on-disk database, the current lock held on the database file -
36805 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36806 **
36807 **   For a temporary or in-memory database (neither of which require any
36808 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
36809 **   databases always have Pager.exclusiveMode==1, this tricks the pager
36810 **   logic into thinking that it already has all the locks it will ever
36811 **   need (and no reason to release them).
36812 **
36813 **   In some (obscure) circumstances, this variable may also be set to
36814 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
36815 **   details.
36816 **
36817 ** changeCountDone
36818 **
36819 **   This boolean variable is used to make sure that the change-counter 
36820 **   (the 4-byte header field at byte offset 24 of the database file) is 
36821 **   not updated more often than necessary. 
36822 **
36823 **   It is set to true when the change-counter field is updated, which 
36824 **   can only happen if an exclusive lock is held on the database file.
36825 **   It is cleared (set to false) whenever an exclusive lock is 
36826 **   relinquished on the database file. Each time a transaction is committed,
36827 **   The changeCountDone flag is inspected. If it is true, the work of
36828 **   updating the change-counter is omitted for the current transaction.
36829 **
36830 **   This mechanism means that when running in exclusive mode, a connection 
36831 **   need only update the change-counter once, for the first transaction
36832 **   committed.
36833 **
36834 ** setMaster
36835 **
36836 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
36837 **   (or may not) specify a master-journal name to be written into the 
36838 **   journal file before it is synced to disk.
36839 **
36840 **   Whether or not a journal file contains a master-journal pointer affects 
36841 **   the way in which the journal file is finalized after the transaction is 
36842 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
36843 **   If a journal file does not contain a master-journal pointer, it is
36844 **   finalized by overwriting the first journal header with zeroes. If
36845 **   it does contain a master-journal pointer the journal file is finalized 
36846 **   by truncating it to zero bytes, just as if the connection were 
36847 **   running in "journal_mode=truncate" mode.
36848 **
36849 **   Journal files that contain master journal pointers cannot be finalized
36850 **   simply by overwriting the first journal-header with zeroes, as the
36851 **   master journal pointer could interfere with hot-journal rollback of any
36852 **   subsequently interrupted transaction that reuses the journal file.
36853 **
36854 **   The flag is cleared as soon as the journal file is finalized (either
36855 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
36856 **   journal file from being successfully finalized, the setMaster flag
36857 **   is cleared anyway (and the pager will move to ERROR state).
36858 **
36859 ** doNotSpill, doNotSyncSpill
36860 **
36861 **   These two boolean variables control the behaviour of cache-spills
36862 **   (calls made by the pcache module to the pagerStress() routine to
36863 **   write cached data to the file-system in order to free up memory).
36864 **
36865 **   When doNotSpill is non-zero, writing to the database from pagerStress()
36866 **   is disabled altogether. This is done in a very obscure case that
36867 **   comes up during savepoint rollback that requires the pcache module
36868 **   to allocate a new page to prevent the journal file from being written
36869 **   while it is being traversed by code in pager_playback().
36870 ** 
36871 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
36872 **   is permitted, but syncing the journal file is not. This flag is set
36873 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
36874 **   the database page-size in order to prevent a journal sync from happening 
36875 **   in between the journalling of two pages on the same sector. 
36876 **
36877 ** subjInMemory
36878 **
36879 **   This is a boolean variable. If true, then any required sub-journal
36880 **   is opened as an in-memory journal file. If false, then in-memory
36881 **   sub-journals are only used for in-memory pager files.
36882 **
36883 **   This variable is updated by the upper layer each time a new 
36884 **   write-transaction is opened.
36885 **
36886 ** dbSize, dbOrigSize, dbFileSize
36887 **
36888 **   Variable dbSize is set to the number of pages in the database file.
36889 **   It is valid in PAGER_READER and higher states (all states except for
36890 **   OPEN and ERROR). 
36891 **
36892 **   dbSize is set based on the size of the database file, which may be 
36893 **   larger than the size of the database (the value stored at offset
36894 **   28 of the database header by the btree). If the size of the file
36895 **   is not an integer multiple of the page-size, the value stored in
36896 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
36897 **   Except, any file that is greater than 0 bytes in size is considered
36898 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
36899 **   to dbSize==1).
36900 **
36901 **   During a write-transaction, if pages with page-numbers greater than
36902 **   dbSize are modified in the cache, dbSize is updated accordingly.
36903 **   Similarly, if the database is truncated using PagerTruncateImage(), 
36904 **   dbSize is updated.
36905 **
36906 **   Variables dbOrigSize and dbFileSize are valid in states 
36907 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
36908 **   variable at the start of the transaction. It is used during rollback,
36909 **   and to determine whether or not pages need to be journalled before
36910 **   being modified.
36911 **
36912 **   Throughout a write-transaction, dbFileSize contains the size of
36913 **   the file on disk in pages. It is set to a copy of dbSize when the
36914 **   write-transaction is first opened, and updated when VFS calls are made
36915 **   to write or truncate the database file on disk. 
36916 **
36917 **   The only reason the dbFileSize variable is required is to suppress 
36918 **   unnecessary calls to xTruncate() after committing a transaction. If, 
36919 **   when a transaction is committed, the dbFileSize variable indicates 
36920 **   that the database file is larger than the database image (Pager.dbSize), 
36921 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
36922 **   to measure the database file on disk, and then truncates it if required.
36923 **   dbFileSize is not used when rolling back a transaction. In this case
36924 **   pager_truncate() is called unconditionally (which means there may be
36925 **   a call to xFilesize() that is not strictly required). In either case,
36926 **   pager_truncate() may cause the file to become smaller or larger.
36927 **
36928 ** dbHintSize
36929 **
36930 **   The dbHintSize variable is used to limit the number of calls made to
36931 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
36932 **
36933 **   dbHintSize is set to a copy of the dbSize variable when a
36934 **   write-transaction is opened (at the same time as dbFileSize and
36935 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
36936 **   dbHintSize is increased to the number of pages that correspond to the
36937 **   size-hint passed to the method call. See pager_write_pagelist() for 
36938 **   details.
36939 **
36940 ** errCode
36941 **
36942 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
36943 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
36944 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
36945 **   sub-codes.
36946 */
36947 struct Pager {
36948   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
36949   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
36950   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
36951   u8 useJournal;              /* Use a rollback journal on this file */
36952   u8 noReadlock;              /* Do not bother to obtain readlocks */
36953   u8 noSync;                  /* Do not sync the journal if true */
36954   u8 fullSync;                /* Do extra syncs of the journal for robustness */
36955   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
36956   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
36957   u8 tempFile;                /* zFilename is a temporary file */
36958   u8 readOnly;                /* True for a read-only database */
36959   u8 memDb;                   /* True to inhibit all file I/O */
36960
36961   /**************************************************************************
36962   ** The following block contains those class members that change during
36963   ** routine opertion.  Class members not in this block are either fixed
36964   ** when the pager is first created or else only change when there is a
36965   ** significant mode change (such as changing the page_size, locking_mode,
36966   ** or the journal_mode).  From another view, these class members describe
36967   ** the "state" of the pager, while other class members describe the
36968   ** "configuration" of the pager.
36969   */
36970   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
36971   u8 eLock;                   /* Current lock held on database file */
36972   u8 changeCountDone;         /* Set after incrementing the change-counter */
36973   u8 setMaster;               /* True if a m-j name has been written to jrnl */
36974   u8 doNotSpill;              /* Do not spill the cache when non-zero */
36975   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
36976   u8 subjInMemory;            /* True to use in-memory sub-journals */
36977   Pgno dbSize;                /* Number of pages in the database */
36978   Pgno dbOrigSize;            /* dbSize before the current transaction */
36979   Pgno dbFileSize;            /* Number of pages in the database file */
36980   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
36981   int errCode;                /* One of several kinds of errors */
36982   int nRec;                   /* Pages journalled since last j-header written */
36983   u32 cksumInit;              /* Quasi-random value added to every checksum */
36984   u32 nSubRec;                /* Number of records written to sub-journal */
36985   Bitvec *pInJournal;         /* One bit for each page in the database file */
36986   sqlite3_file *fd;           /* File descriptor for database */
36987   sqlite3_file *jfd;          /* File descriptor for main journal */
36988   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
36989   i64 journalOff;             /* Current write offset in the journal file */
36990   i64 journalHdr;             /* Byte offset to previous journal header */
36991   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
36992   PagerSavepoint *aSavepoint; /* Array of active savepoints */
36993   int nSavepoint;             /* Number of elements in aSavepoint[] */
36994   char dbFileVers[16];        /* Changes whenever database file changes */
36995   /*
36996   ** End of the routinely-changing class members
36997   ***************************************************************************/
36998
36999   u16 nExtra;                 /* Add this many bytes to each in-memory page */
37000   i16 nReserve;               /* Number of unused bytes at end of each page */
37001   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37002   u32 sectorSize;             /* Assumed sector size during rollback */
37003   int pageSize;               /* Number of bytes in a page */
37004   Pgno mxPgno;                /* Maximum allowed size of the database */
37005   i64 journalSizeLimit;       /* Size limit for persistent journal files */
37006   char *zFilename;            /* Name of the database file */
37007   char *zJournal;             /* Name of the journal file */
37008   int (*xBusyHandler)(void*); /* Function to call when busy */
37009   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37010 #ifdef SQLITE_TEST
37011   int nHit, nMiss;            /* Cache hits and missing */
37012   int nRead, nWrite;          /* Database pages read/written */
37013 #endif
37014   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37015 #ifdef SQLITE_HAS_CODEC
37016   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37017   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37018   void (*xCodecFree)(void*);             /* Destructor for the codec */
37019   void *pCodec;               /* First argument to xCodec... methods */
37020 #endif
37021   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
37022   PCache *pPCache;            /* Pointer to page cache object */
37023 #ifndef SQLITE_OMIT_WAL
37024   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
37025   char *zWal;                 /* File name for write-ahead log */
37026 #endif
37027 };
37028
37029 /*
37030 ** The following global variables hold counters used for
37031 ** testing purposes only.  These variables do not exist in
37032 ** a non-testing build.  These variables are not thread-safe.
37033 */
37034 #ifdef SQLITE_TEST
37035 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
37036 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
37037 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
37038 # define PAGER_INCR(v)  v++
37039 #else
37040 # define PAGER_INCR(v)
37041 #endif
37042
37043
37044
37045 /*
37046 ** Journal files begin with the following magic string.  The data
37047 ** was obtained from /dev/random.  It is used only as a sanity check.
37048 **
37049 ** Since version 2.8.0, the journal format contains additional sanity
37050 ** checking information.  If the power fails while the journal is being
37051 ** written, semi-random garbage data might appear in the journal
37052 ** file after power is restored.  If an attempt is then made
37053 ** to roll the journal back, the database could be corrupted.  The additional
37054 ** sanity checking data is an attempt to discover the garbage in the
37055 ** journal and ignore it.
37056 **
37057 ** The sanity checking information for the new journal format consists
37058 ** of a 32-bit checksum on each page of data.  The checksum covers both
37059 ** the page number and the pPager->pageSize bytes of data for the page.
37060 ** This cksum is initialized to a 32-bit random value that appears in the
37061 ** journal file right after the header.  The random initializer is important,
37062 ** because garbage data that appears at the end of a journal is likely
37063 ** data that was once in other files that have now been deleted.  If the
37064 ** garbage data came from an obsolete journal file, the checksums might
37065 ** be correct.  But by initializing the checksum to random value which
37066 ** is different for every journal, we minimize that risk.
37067 */
37068 static const unsigned char aJournalMagic[] = {
37069   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37070 };
37071
37072 /*
37073 ** The size of the of each page record in the journal is given by
37074 ** the following macro.
37075 */
37076 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
37077
37078 /*
37079 ** The journal header size for this pager. This is usually the same 
37080 ** size as a single disk sector. See also setSectorSize().
37081 */
37082 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37083
37084 /*
37085 ** The macro MEMDB is true if we are dealing with an in-memory database.
37086 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37087 ** the value of MEMDB will be a constant and the compiler will optimize
37088 ** out code that would never execute.
37089 */
37090 #ifdef SQLITE_OMIT_MEMORYDB
37091 # define MEMDB 0
37092 #else
37093 # define MEMDB pPager->memDb
37094 #endif
37095
37096 /*
37097 ** The maximum legal page number is (2^31 - 1).
37098 */
37099 #define PAGER_MAX_PGNO 2147483647
37100
37101 /*
37102 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37103 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37104 **
37105 ** This is so that expressions can be written as:
37106 **
37107 **   if( isOpen(pPager->jfd) ){ ...
37108 **
37109 ** instead of
37110 **
37111 **   if( pPager->jfd->pMethods ){ ...
37112 */
37113 #define isOpen(pFd) ((pFd)->pMethods)
37114
37115 /*
37116 ** Return true if this pager uses a write-ahead log instead of the usual
37117 ** rollback journal. Otherwise false.
37118 */
37119 #ifndef SQLITE_OMIT_WAL
37120 static int pagerUseWal(Pager *pPager){
37121   return (pPager->pWal!=0);
37122 }
37123 #else
37124 # define pagerUseWal(x) 0
37125 # define pagerRollbackWal(x) 0
37126 # define pagerWalFrames(v,w,x,y,z) 0
37127 # define pagerOpenWalIfPresent(z) SQLITE_OK
37128 # define pagerBeginReadTransaction(z) SQLITE_OK
37129 #endif
37130
37131 #ifndef NDEBUG 
37132 /*
37133 ** Usage:
37134 **
37135 **   assert( assert_pager_state(pPager) );
37136 **
37137 ** This function runs many asserts to try to find inconsistencies in
37138 ** the internal state of the Pager object.
37139 */
37140 static int assert_pager_state(Pager *p){
37141   Pager *pPager = p;
37142
37143   /* State must be valid. */
37144   assert( p->eState==PAGER_OPEN
37145        || p->eState==PAGER_READER
37146        || p->eState==PAGER_WRITER_LOCKED
37147        || p->eState==PAGER_WRITER_CACHEMOD
37148        || p->eState==PAGER_WRITER_DBMOD
37149        || p->eState==PAGER_WRITER_FINISHED
37150        || p->eState==PAGER_ERROR
37151   );
37152
37153   /* Regardless of the current state, a temp-file connection always behaves
37154   ** as if it has an exclusive lock on the database file. It never updates
37155   ** the change-counter field, so the changeCountDone flag is always set.
37156   */
37157   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37158   assert( p->tempFile==0 || pPager->changeCountDone );
37159
37160   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
37161   ** And if the journal-mode is "OFF", the journal file must not be open.
37162   */
37163   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37164   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37165
37166   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
37167   ** this means an in-memory pager performs no IO at all, it cannot encounter 
37168   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
37169   ** a journal file. (although the in-memory journal implementation may 
37170   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
37171   ** is therefore not possible for an in-memory pager to enter the ERROR 
37172   ** state.
37173   */
37174   if( MEMDB ){
37175     assert( p->noSync );
37176     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
37177          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
37178     );
37179     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37180     assert( pagerUseWal(p)==0 );
37181   }
37182
37183   /* If changeCountDone is set, a RESERVED lock or greater must be held
37184   ** on the file.
37185   */
37186   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37187   assert( p->eLock!=PENDING_LOCK );
37188
37189   switch( p->eState ){
37190     case PAGER_OPEN:
37191       assert( !MEMDB );
37192       assert( pPager->errCode==SQLITE_OK );
37193       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37194       break;
37195
37196     case PAGER_READER:
37197       assert( pPager->errCode==SQLITE_OK );
37198       assert( p->eLock!=UNKNOWN_LOCK );
37199       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37200       break;
37201
37202     case PAGER_WRITER_LOCKED:
37203       assert( p->eLock!=UNKNOWN_LOCK );
37204       assert( pPager->errCode==SQLITE_OK );
37205       if( !pagerUseWal(pPager) ){
37206         assert( p->eLock>=RESERVED_LOCK );
37207       }
37208       assert( pPager->dbSize==pPager->dbOrigSize );
37209       assert( pPager->dbOrigSize==pPager->dbFileSize );
37210       assert( pPager->dbOrigSize==pPager->dbHintSize );
37211       assert( pPager->setMaster==0 );
37212       break;
37213
37214     case PAGER_WRITER_CACHEMOD:
37215       assert( p->eLock!=UNKNOWN_LOCK );
37216       assert( pPager->errCode==SQLITE_OK );
37217       if( !pagerUseWal(pPager) ){
37218         /* It is possible that if journal_mode=wal here that neither the
37219         ** journal file nor the WAL file are open. This happens during
37220         ** a rollback transaction that switches from journal_mode=off
37221         ** to journal_mode=wal.
37222         */
37223         assert( p->eLock>=RESERVED_LOCK );
37224         assert( isOpen(p->jfd) 
37225              || p->journalMode==PAGER_JOURNALMODE_OFF 
37226              || p->journalMode==PAGER_JOURNALMODE_WAL 
37227         );
37228       }
37229       assert( pPager->dbOrigSize==pPager->dbFileSize );
37230       assert( pPager->dbOrigSize==pPager->dbHintSize );
37231       break;
37232
37233     case PAGER_WRITER_DBMOD:
37234       assert( p->eLock==EXCLUSIVE_LOCK );
37235       assert( pPager->errCode==SQLITE_OK );
37236       assert( !pagerUseWal(pPager) );
37237       assert( p->eLock>=EXCLUSIVE_LOCK );
37238       assert( isOpen(p->jfd) 
37239            || p->journalMode==PAGER_JOURNALMODE_OFF 
37240            || p->journalMode==PAGER_JOURNALMODE_WAL 
37241       );
37242       assert( pPager->dbOrigSize<=pPager->dbHintSize );
37243       break;
37244
37245     case PAGER_WRITER_FINISHED:
37246       assert( p->eLock==EXCLUSIVE_LOCK );
37247       assert( pPager->errCode==SQLITE_OK );
37248       assert( !pagerUseWal(pPager) );
37249       assert( isOpen(p->jfd) 
37250            || p->journalMode==PAGER_JOURNALMODE_OFF 
37251            || p->journalMode==PAGER_JOURNALMODE_WAL 
37252       );
37253       break;
37254
37255     case PAGER_ERROR:
37256       /* There must be at least one outstanding reference to the pager if
37257       ** in ERROR state. Otherwise the pager should have already dropped
37258       ** back to OPEN state.
37259       */
37260       assert( pPager->errCode!=SQLITE_OK );
37261       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37262       break;
37263   }
37264
37265   return 1;
37266 }
37267 #endif /* ifndef NDEBUG */
37268
37269 #ifdef SQLITE_DEBUG 
37270 /*
37271 ** Return a pointer to a human readable string in a static buffer
37272 ** containing the state of the Pager object passed as an argument. This
37273 ** is intended to be used within debuggers. For example, as an alternative
37274 ** to "print *pPager" in gdb:
37275 **
37276 ** (gdb) printf "%s", print_pager_state(pPager)
37277 */
37278 static char *print_pager_state(Pager *p){
37279   static char zRet[1024];
37280
37281   sqlite3_snprintf(1024, zRet,
37282       "Filename:      %s\n"
37283       "State:         %s errCode=%d\n"
37284       "Lock:          %s\n"
37285       "Locking mode:  locking_mode=%s\n"
37286       "Journal mode:  journal_mode=%s\n"
37287       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37288       "Journal:       journalOff=%lld journalHdr=%lld\n"
37289       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37290       , p->zFilename
37291       , p->eState==PAGER_OPEN            ? "OPEN" :
37292         p->eState==PAGER_READER          ? "READER" :
37293         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
37294         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37295         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
37296         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37297         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
37298       , (int)p->errCode
37299       , p->eLock==NO_LOCK         ? "NO_LOCK" :
37300         p->eLock==RESERVED_LOCK   ? "RESERVED" :
37301         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
37302         p->eLock==SHARED_LOCK     ? "SHARED" :
37303         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
37304       , p->exclusiveMode ? "exclusive" : "normal"
37305       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
37306         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
37307         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
37308         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
37309         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37310         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
37311       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37312       , p->journalOff, p->journalHdr
37313       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37314   );
37315
37316   return zRet;
37317 }
37318 #endif
37319
37320 /*
37321 ** Return true if it is necessary to write page *pPg into the sub-journal.
37322 ** A page needs to be written into the sub-journal if there exists one
37323 ** or more open savepoints for which:
37324 **
37325 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
37326 **   * The bit corresponding to the page-number is not set in
37327 **     PagerSavepoint.pInSavepoint.
37328 */
37329 static int subjRequiresPage(PgHdr *pPg){
37330   Pgno pgno = pPg->pgno;
37331   Pager *pPager = pPg->pPager;
37332   int i;
37333   for(i=0; i<pPager->nSavepoint; i++){
37334     PagerSavepoint *p = &pPager->aSavepoint[i];
37335     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37336       return 1;
37337     }
37338   }
37339   return 0;
37340 }
37341
37342 /*
37343 ** Return true if the page is already in the journal file.
37344 */
37345 static int pageInJournal(PgHdr *pPg){
37346   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37347 }
37348
37349 /*
37350 ** Read a 32-bit integer from the given file descriptor.  Store the integer
37351 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
37352 ** error code is something goes wrong.
37353 **
37354 ** All values are stored on disk as big-endian.
37355 */
37356 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37357   unsigned char ac[4];
37358   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37359   if( rc==SQLITE_OK ){
37360     *pRes = sqlite3Get4byte(ac);
37361   }
37362   return rc;
37363 }
37364
37365 /*
37366 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37367 */
37368 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
37369
37370
37371 /*
37372 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
37373 ** on success or an error code is something goes wrong.
37374 */
37375 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37376   char ac[4];
37377   put32bits(ac, val);
37378   return sqlite3OsWrite(fd, ac, 4, offset);
37379 }
37380
37381 /*
37382 ** Unlock the database file to level eLock, which must be either NO_LOCK
37383 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37384 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37385 **
37386 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37387 ** called, do not modify it. See the comment above the #define of 
37388 ** UNKNOWN_LOCK for an explanation of this.
37389 */
37390 static int pagerUnlockDb(Pager *pPager, int eLock){
37391   int rc = SQLITE_OK;
37392
37393   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37394   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37395   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37396   if( isOpen(pPager->fd) ){
37397     assert( pPager->eLock>=eLock );
37398     rc = sqlite3OsUnlock(pPager->fd, eLock);
37399     if( pPager->eLock!=UNKNOWN_LOCK ){
37400       pPager->eLock = (u8)eLock;
37401     }
37402     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37403   }
37404   return rc;
37405 }
37406
37407 /*
37408 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
37409 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37410 ** Pager.eLock variable to the new locking state. 
37411 **
37412 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
37413 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
37414 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
37415 ** of this.
37416 */
37417 static int pagerLockDb(Pager *pPager, int eLock){
37418   int rc = SQLITE_OK;
37419
37420   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37421   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37422     rc = sqlite3OsLock(pPager->fd, eLock);
37423     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37424       pPager->eLock = (u8)eLock;
37425       IOTRACE(("LOCK %p %d\n", pPager, eLock))
37426     }
37427   }
37428   return rc;
37429 }
37430
37431 /*
37432 ** This function determines whether or not the atomic-write optimization
37433 ** can be used with this pager. The optimization can be used if:
37434 **
37435 **  (a) the value returned by OsDeviceCharacteristics() indicates that
37436 **      a database page may be written atomically, and
37437 **  (b) the value returned by OsSectorSize() is less than or equal
37438 **      to the page size.
37439 **
37440 ** The optimization is also always enabled for temporary files. It is
37441 ** an error to call this function if pPager is opened on an in-memory
37442 ** database.
37443 **
37444 ** If the optimization cannot be used, 0 is returned. If it can be used,
37445 ** then the value returned is the size of the journal file when it
37446 ** contains rollback data for exactly one page.
37447 */
37448 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37449 static int jrnlBufferSize(Pager *pPager){
37450   assert( !MEMDB );
37451   if( !pPager->tempFile ){
37452     int dc;                           /* Device characteristics */
37453     int nSector;                      /* Sector size */
37454     int szPage;                       /* Page size */
37455
37456     assert( isOpen(pPager->fd) );
37457     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37458     nSector = pPager->sectorSize;
37459     szPage = pPager->pageSize;
37460
37461     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37462     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37463     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37464       return 0;
37465     }
37466   }
37467
37468   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37469 }
37470 #endif
37471
37472 /*
37473 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37474 ** on the cache using a hash function.  This is used for testing
37475 ** and debugging only.
37476 */
37477 #ifdef SQLITE_CHECK_PAGES
37478 /*
37479 ** Return a 32-bit hash of the page data for pPage.
37480 */
37481 static u32 pager_datahash(int nByte, unsigned char *pData){
37482   u32 hash = 0;
37483   int i;
37484   for(i=0; i<nByte; i++){
37485     hash = (hash*1039) + pData[i];
37486   }
37487   return hash;
37488 }
37489 static u32 pager_pagehash(PgHdr *pPage){
37490   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37491 }
37492 static void pager_set_pagehash(PgHdr *pPage){
37493   pPage->pageHash = pager_pagehash(pPage);
37494 }
37495
37496 /*
37497 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37498 ** is defined, and NDEBUG is not defined, an assert() statement checks
37499 ** that the page is either dirty or still matches the calculated page-hash.
37500 */
37501 #define CHECK_PAGE(x) checkPage(x)
37502 static void checkPage(PgHdr *pPg){
37503   Pager *pPager = pPg->pPager;
37504   assert( pPager->eState!=PAGER_ERROR );
37505   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37506 }
37507
37508 #else
37509 #define pager_datahash(X,Y)  0
37510 #define pager_pagehash(X)  0
37511 #define pager_set_pagehash(X)
37512 #define CHECK_PAGE(x)
37513 #endif  /* SQLITE_CHECK_PAGES */
37514
37515 /*
37516 ** When this is called the journal file for pager pPager must be open.
37517 ** This function attempts to read a master journal file name from the 
37518 ** end of the file and, if successful, copies it into memory supplied 
37519 ** by the caller. See comments above writeMasterJournal() for the format
37520 ** used to store a master journal file name at the end of a journal file.
37521 **
37522 ** zMaster must point to a buffer of at least nMaster bytes allocated by
37523 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37524 ** enough space to write the master journal name). If the master journal
37525 ** name in the journal is longer than nMaster bytes (including a
37526 ** nul-terminator), then this is handled as if no master journal name
37527 ** were present in the journal.
37528 **
37529 ** If a master journal file name is present at the end of the journal
37530 ** file, then it is copied into the buffer pointed to by zMaster. A
37531 ** nul-terminator byte is appended to the buffer following the master
37532 ** journal file name.
37533 **
37534 ** If it is determined that no master journal file name is present 
37535 ** zMaster[0] is set to 0 and SQLITE_OK returned.
37536 **
37537 ** If an error occurs while reading from the journal file, an SQLite
37538 ** error code is returned.
37539 */
37540 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37541   int rc;                    /* Return code */
37542   u32 len;                   /* Length in bytes of master journal name */
37543   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
37544   u32 cksum;                 /* MJ checksum value read from journal */
37545   u32 u;                     /* Unsigned loop counter */
37546   unsigned char aMagic[8];   /* A buffer to hold the magic header */
37547   zMaster[0] = '\0';
37548
37549   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
37550    || szJ<16
37551    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
37552    || len>=nMaster 
37553    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
37554    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
37555    || memcmp(aMagic, aJournalMagic, 8)
37556    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
37557   ){
37558     return rc;
37559   }
37560
37561   /* See if the checksum matches the master journal name */
37562   for(u=0; u<len; u++){
37563     cksum -= zMaster[u];
37564   }
37565   if( cksum ){
37566     /* If the checksum doesn't add up, then one or more of the disk sectors
37567     ** containing the master journal filename is corrupted. This means
37568     ** definitely roll back, so just return SQLITE_OK and report a (nul)
37569     ** master-journal filename.
37570     */
37571     len = 0;
37572   }
37573   zMaster[len] = '\0';
37574    
37575   return SQLITE_OK;
37576 }
37577
37578 /*
37579 ** Return the offset of the sector boundary at or immediately 
37580 ** following the value in pPager->journalOff, assuming a sector 
37581 ** size of pPager->sectorSize bytes.
37582 **
37583 ** i.e for a sector size of 512:
37584 **
37585 **   Pager.journalOff          Return value
37586 **   ---------------------------------------
37587 **   0                         0
37588 **   512                       512
37589 **   100                       512
37590 **   2000                      2048
37591 ** 
37592 */
37593 static i64 journalHdrOffset(Pager *pPager){
37594   i64 offset = 0;
37595   i64 c = pPager->journalOff;
37596   if( c ){
37597     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
37598   }
37599   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
37600   assert( offset>=c );
37601   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
37602   return offset;
37603 }
37604
37605 /*
37606 ** The journal file must be open when this function is called.
37607 **
37608 ** This function is a no-op if the journal file has not been written to
37609 ** within the current transaction (i.e. if Pager.journalOff==0).
37610 **
37611 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
37612 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
37613 ** zero the 28-byte header at the start of the journal file. In either case, 
37614 ** if the pager is not in no-sync mode, sync the journal file immediately 
37615 ** after writing or truncating it.
37616 **
37617 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
37618 ** following the truncation or zeroing described above the size of the 
37619 ** journal file in bytes is larger than this value, then truncate the
37620 ** journal file to Pager.journalSizeLimit bytes. The journal file does
37621 ** not need to be synced following this operation.
37622 **
37623 ** If an IO error occurs, abandon processing and return the IO error code.
37624 ** Otherwise, return SQLITE_OK.
37625 */
37626 static int zeroJournalHdr(Pager *pPager, int doTruncate){
37627   int rc = SQLITE_OK;                               /* Return code */
37628   assert( isOpen(pPager->jfd) );
37629   if( pPager->journalOff ){
37630     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
37631
37632     IOTRACE(("JZEROHDR %p\n", pPager))
37633     if( doTruncate || iLimit==0 ){
37634       rc = sqlite3OsTruncate(pPager->jfd, 0);
37635     }else{
37636       static const char zeroHdr[28] = {0};
37637       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
37638     }
37639     if( rc==SQLITE_OK && !pPager->noSync ){
37640       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
37641     }
37642
37643     /* At this point the transaction is committed but the write lock 
37644     ** is still held on the file. If there is a size limit configured for 
37645     ** the persistent journal and the journal file currently consumes more
37646     ** space than that limit allows for, truncate it now. There is no need
37647     ** to sync the file following this operation.
37648     */
37649     if( rc==SQLITE_OK && iLimit>0 ){
37650       i64 sz;
37651       rc = sqlite3OsFileSize(pPager->jfd, &sz);
37652       if( rc==SQLITE_OK && sz>iLimit ){
37653         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
37654       }
37655     }
37656   }
37657   return rc;
37658 }
37659
37660 /*
37661 ** The journal file must be open when this routine is called. A journal
37662 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
37663 ** current location.
37664 **
37665 ** The format for the journal header is as follows:
37666 ** - 8 bytes: Magic identifying journal format.
37667 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
37668 ** - 4 bytes: Random number used for page hash.
37669 ** - 4 bytes: Initial database page count.
37670 ** - 4 bytes: Sector size used by the process that wrote this journal.
37671 ** - 4 bytes: Database page size.
37672 ** 
37673 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
37674 */
37675 static int writeJournalHdr(Pager *pPager){
37676   int rc = SQLITE_OK;                 /* Return code */
37677   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
37678   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
37679   u32 nWrite;                         /* Bytes of header sector written */
37680   int ii;                             /* Loop counter */
37681
37682   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37683
37684   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
37685     nHeader = JOURNAL_HDR_SZ(pPager);
37686   }
37687
37688   /* If there are active savepoints and any of them were created 
37689   ** since the most recent journal header was written, update the 
37690   ** PagerSavepoint.iHdrOffset fields now.
37691   */
37692   for(ii=0; ii<pPager->nSavepoint; ii++){
37693     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
37694       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
37695     }
37696   }
37697
37698   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
37699
37700   /* 
37701   ** Write the nRec Field - the number of page records that follow this
37702   ** journal header. Normally, zero is written to this value at this time.
37703   ** After the records are added to the journal (and the journal synced, 
37704   ** if in full-sync mode), the zero is overwritten with the true number
37705   ** of records (see syncJournal()).
37706   **
37707   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
37708   ** reading the journal this value tells SQLite to assume that the
37709   ** rest of the journal file contains valid page records. This assumption
37710   ** is dangerous, as if a failure occurred whilst writing to the journal
37711   ** file it may contain some garbage data. There are two scenarios
37712   ** where this risk can be ignored:
37713   **
37714   **   * When the pager is in no-sync mode. Corruption can follow a
37715   **     power failure in this case anyway.
37716   **
37717   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
37718   **     that garbage data is never appended to the journal file.
37719   */
37720   assert( isOpen(pPager->fd) || pPager->noSync );
37721   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
37722    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
37723   ){
37724     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37725     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
37726   }else{
37727     memset(zHeader, 0, sizeof(aJournalMagic)+4);
37728   }
37729
37730   /* The random check-hash initialiser */ 
37731   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
37732   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
37733   /* The initial database size */
37734   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
37735   /* The assumed sector size for this process */
37736   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
37737
37738   /* The page size */
37739   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
37740
37741   /* Initializing the tail of the buffer is not necessary.  Everything
37742   ** works find if the following memset() is omitted.  But initializing
37743   ** the memory prevents valgrind from complaining, so we are willing to
37744   ** take the performance hit.
37745   */
37746   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
37747          nHeader-(sizeof(aJournalMagic)+20));
37748
37749   /* In theory, it is only necessary to write the 28 bytes that the 
37750   ** journal header consumes to the journal file here. Then increment the 
37751   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
37752   ** record is written to the following sector (leaving a gap in the file
37753   ** that will be implicitly filled in by the OS).
37754   **
37755   ** However it has been discovered that on some systems this pattern can 
37756   ** be significantly slower than contiguously writing data to the file,
37757   ** even if that means explicitly writing data to the block of 
37758   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
37759   ** is done. 
37760   **
37761   ** The loop is required here in case the sector-size is larger than the 
37762   ** database page size. Since the zHeader buffer is only Pager.pageSize
37763   ** bytes in size, more than one call to sqlite3OsWrite() may be required
37764   ** to populate the entire journal header sector.
37765   */ 
37766   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
37767     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
37768     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
37769     assert( pPager->journalHdr <= pPager->journalOff );
37770     pPager->journalOff += nHeader;
37771   }
37772
37773   return rc;
37774 }
37775
37776 /*
37777 ** The journal file must be open when this is called. A journal header file
37778 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
37779 ** file. The current location in the journal file is given by
37780 ** pPager->journalOff. See comments above function writeJournalHdr() for
37781 ** a description of the journal header format.
37782 **
37783 ** If the header is read successfully, *pNRec is set to the number of
37784 ** page records following this header and *pDbSize is set to the size of the
37785 ** database before the transaction began, in pages. Also, pPager->cksumInit
37786 ** is set to the value read from the journal header. SQLITE_OK is returned
37787 ** in this case.
37788 **
37789 ** If the journal header file appears to be corrupted, SQLITE_DONE is
37790 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
37791 ** cannot be read from the journal file an error code is returned.
37792 */
37793 static int readJournalHdr(
37794   Pager *pPager,               /* Pager object */
37795   int isHot,
37796   i64 journalSize,             /* Size of the open journal file in bytes */
37797   u32 *pNRec,                  /* OUT: Value read from the nRec field */
37798   u32 *pDbSize                 /* OUT: Value of original database size field */
37799 ){
37800   int rc;                      /* Return code */
37801   unsigned char aMagic[8];     /* A buffer to hold the magic header */
37802   i64 iHdrOff;                 /* Offset of journal header being read */
37803
37804   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
37805
37806   /* Advance Pager.journalOff to the start of the next sector. If the
37807   ** journal file is too small for there to be a header stored at this
37808   ** point, return SQLITE_DONE.
37809   */
37810   pPager->journalOff = journalHdrOffset(pPager);
37811   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
37812     return SQLITE_DONE;
37813   }
37814   iHdrOff = pPager->journalOff;
37815
37816   /* Read in the first 8 bytes of the journal header. If they do not match
37817   ** the  magic string found at the start of each journal header, return
37818   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
37819   ** proceed.
37820   */
37821   if( isHot || iHdrOff!=pPager->journalHdr ){
37822     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
37823     if( rc ){
37824       return rc;
37825     }
37826     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
37827       return SQLITE_DONE;
37828     }
37829   }
37830
37831   /* Read the first three 32-bit fields of the journal header: The nRec
37832   ** field, the checksum-initializer and the database size at the start
37833   ** of the transaction. Return an error code if anything goes wrong.
37834   */
37835   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
37836    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
37837    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
37838   ){
37839     return rc;
37840   }
37841
37842   if( pPager->journalOff==0 ){
37843     u32 iPageSize;               /* Page-size field of journal header */
37844     u32 iSectorSize;             /* Sector-size field of journal header */
37845
37846     /* Read the page-size and sector-size journal header fields. */
37847     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
37848      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
37849     ){
37850       return rc;
37851     }
37852
37853     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
37854     ** journal header to zero. In this case, assume that the Pager.pageSize
37855     ** variable is already set to the correct page size.
37856     */
37857     if( iPageSize==0 ){
37858       iPageSize = pPager->pageSize;
37859     }
37860
37861     /* Check that the values read from the page-size and sector-size fields
37862     ** are within range. To be 'in range', both values need to be a power
37863     ** of two greater than or equal to 512 or 32, and not greater than their 
37864     ** respective compile time maximum limits.
37865     */
37866     if( iPageSize<512                  || iSectorSize<32
37867      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
37868      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
37869     ){
37870       /* If the either the page-size or sector-size in the journal-header is 
37871       ** invalid, then the process that wrote the journal-header must have 
37872       ** crashed before the header was synced. In this case stop reading 
37873       ** the journal file here.
37874       */
37875       return SQLITE_DONE;
37876     }
37877
37878     /* Update the page-size to match the value read from the journal. 
37879     ** Use a testcase() macro to make sure that malloc failure within 
37880     ** PagerSetPagesize() is tested.
37881     */
37882     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
37883     testcase( rc!=SQLITE_OK );
37884
37885     /* Update the assumed sector-size to match the value used by 
37886     ** the process that created this journal. If this journal was
37887     ** created by a process other than this one, then this routine
37888     ** is being called from within pager_playback(). The local value
37889     ** of Pager.sectorSize is restored at the end of that routine.
37890     */
37891     pPager->sectorSize = iSectorSize;
37892   }
37893
37894   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
37895   return rc;
37896 }
37897
37898
37899 /*
37900 ** Write the supplied master journal name into the journal file for pager
37901 ** pPager at the current location. The master journal name must be the last
37902 ** thing written to a journal file. If the pager is in full-sync mode, the
37903 ** journal file descriptor is advanced to the next sector boundary before
37904 ** anything is written. The format is:
37905 **
37906 **   + 4 bytes: PAGER_MJ_PGNO.
37907 **   + N bytes: Master journal filename in utf-8.
37908 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
37909 **   + 4 bytes: Master journal name checksum.
37910 **   + 8 bytes: aJournalMagic[].
37911 **
37912 ** The master journal page checksum is the sum of the bytes in the master
37913 ** journal name, where each byte is interpreted as a signed 8-bit integer.
37914 **
37915 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
37916 ** this call is a no-op.
37917 */
37918 static int writeMasterJournal(Pager *pPager, const char *zMaster){
37919   int rc;                          /* Return code */
37920   int nMaster;                     /* Length of string zMaster */
37921   i64 iHdrOff;                     /* Offset of header in journal file */
37922   i64 jrnlSize;                    /* Size of journal file on disk */
37923   u32 cksum = 0;                   /* Checksum of string zMaster */
37924
37925   assert( pPager->setMaster==0 );
37926   assert( !pagerUseWal(pPager) );
37927
37928   if( !zMaster 
37929    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
37930    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
37931   ){
37932     return SQLITE_OK;
37933   }
37934   pPager->setMaster = 1;
37935   assert( isOpen(pPager->jfd) );
37936   assert( pPager->journalHdr <= pPager->journalOff );
37937
37938   /* Calculate the length in bytes and the checksum of zMaster */
37939   for(nMaster=0; zMaster[nMaster]; nMaster++){
37940     cksum += zMaster[nMaster];
37941   }
37942
37943   /* If in full-sync mode, advance to the next disk sector before writing
37944   ** the master journal name. This is in case the previous page written to
37945   ** the journal has already been synced.
37946   */
37947   if( pPager->fullSync ){
37948     pPager->journalOff = journalHdrOffset(pPager);
37949   }
37950   iHdrOff = pPager->journalOff;
37951
37952   /* Write the master journal data to the end of the journal file. If
37953   ** an error occurs, return the error code to the caller.
37954   */
37955   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
37956    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
37957    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
37958    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
37959    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
37960   ){
37961     return rc;
37962   }
37963   pPager->journalOff += (nMaster+20);
37964
37965   /* If the pager is in peristent-journal mode, then the physical 
37966   ** journal-file may extend past the end of the master-journal name
37967   ** and 8 bytes of magic data just written to the file. This is 
37968   ** dangerous because the code to rollback a hot-journal file
37969   ** will not be able to find the master-journal name to determine 
37970   ** whether or not the journal is hot. 
37971   **
37972   ** Easiest thing to do in this scenario is to truncate the journal 
37973   ** file to the required size.
37974   */ 
37975   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
37976    && jrnlSize>pPager->journalOff
37977   ){
37978     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
37979   }
37980   return rc;
37981 }
37982
37983 /*
37984 ** Find a page in the hash table given its page number. Return
37985 ** a pointer to the page or NULL if the requested page is not 
37986 ** already in memory.
37987 */
37988 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
37989   PgHdr *p;                         /* Return value */
37990
37991   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
37992   ** fail, since no attempt to allocate dynamic memory will be made.
37993   */
37994   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
37995   return p;
37996 }
37997
37998 /*
37999 ** Discard the entire contents of the in-memory page-cache.
38000 */
38001 static void pager_reset(Pager *pPager){
38002   sqlite3BackupRestart(pPager->pBackup);
38003   sqlite3PcacheClear(pPager->pPCache);
38004 }
38005
38006 /*
38007 ** Free all structures in the Pager.aSavepoint[] array and set both
38008 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38009 ** if it is open and the pager is not in exclusive mode.
38010 */
38011 static void releaseAllSavepoints(Pager *pPager){
38012   int ii;               /* Iterator for looping through Pager.aSavepoint */
38013   for(ii=0; ii<pPager->nSavepoint; ii++){
38014     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38015   }
38016   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38017     sqlite3OsClose(pPager->sjfd);
38018   }
38019   sqlite3_free(pPager->aSavepoint);
38020   pPager->aSavepoint = 0;
38021   pPager->nSavepoint = 0;
38022   pPager->nSubRec = 0;
38023 }
38024
38025 /*
38026 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
38027 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38028 ** or SQLITE_NOMEM if a malloc failure occurs.
38029 */
38030 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38031   int ii;                   /* Loop counter */
38032   int rc = SQLITE_OK;       /* Result code */
38033
38034   for(ii=0; ii<pPager->nSavepoint; ii++){
38035     PagerSavepoint *p = &pPager->aSavepoint[ii];
38036     if( pgno<=p->nOrig ){
38037       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38038       testcase( rc==SQLITE_NOMEM );
38039       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38040     }
38041   }
38042   return rc;
38043 }
38044
38045 /*
38046 ** This function is a no-op if the pager is in exclusive mode and not
38047 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38048 ** state.
38049 **
38050 ** If the pager is not in exclusive-access mode, the database file is
38051 ** completely unlocked. If the file is unlocked and the file-system does
38052 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38053 ** closed (if it is open).
38054 **
38055 ** If the pager is in ERROR state when this function is called, the 
38056 ** contents of the pager cache are discarded before switching back to 
38057 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38058 ** or not, any journal file left in the file-system will be treated
38059 ** as a hot-journal and rolled back the next time a read-transaction
38060 ** is opened (by this or by any other connection).
38061 */
38062 static void pager_unlock(Pager *pPager){
38063
38064   assert( pPager->eState==PAGER_READER 
38065        || pPager->eState==PAGER_OPEN 
38066        || pPager->eState==PAGER_ERROR 
38067   );
38068
38069   sqlite3BitvecDestroy(pPager->pInJournal);
38070   pPager->pInJournal = 0;
38071   releaseAllSavepoints(pPager);
38072
38073   if( pagerUseWal(pPager) ){
38074     assert( !isOpen(pPager->jfd) );
38075     sqlite3WalEndReadTransaction(pPager->pWal);
38076     pPager->eState = PAGER_OPEN;
38077   }else if( !pPager->exclusiveMode ){
38078     int rc;                       /* Error code returned by pagerUnlockDb() */
38079     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38080
38081     /* If the operating system support deletion of open files, then
38082     ** close the journal file when dropping the database lock.  Otherwise
38083     ** another connection with journal_mode=delete might delete the file
38084     ** out from under us.
38085     */
38086     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
38087     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
38088     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
38089     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
38090     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38091     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
38092     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38093      || 1!=(pPager->journalMode & 5)
38094     ){
38095       sqlite3OsClose(pPager->jfd);
38096     }
38097
38098     /* If the pager is in the ERROR state and the call to unlock the database
38099     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38100     ** above the #define for UNKNOWN_LOCK for an explanation of why this
38101     ** is necessary.
38102     */
38103     rc = pagerUnlockDb(pPager, NO_LOCK);
38104     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38105       pPager->eLock = UNKNOWN_LOCK;
38106     }
38107
38108     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38109     ** without clearing the error code. This is intentional - the error
38110     ** code is cleared and the cache reset in the block below.
38111     */
38112     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38113     pPager->changeCountDone = 0;
38114     pPager->eState = PAGER_OPEN;
38115   }
38116
38117   /* If Pager.errCode is set, the contents of the pager cache cannot be
38118   ** trusted. Now that there are no outstanding references to the pager,
38119   ** it can safely move back to PAGER_OPEN state. This happens in both
38120   ** normal and exclusive-locking mode.
38121   */
38122   if( pPager->errCode ){
38123     assert( !MEMDB );
38124     pager_reset(pPager);
38125     pPager->changeCountDone = pPager->tempFile;
38126     pPager->eState = PAGER_OPEN;
38127     pPager->errCode = SQLITE_OK;
38128   }
38129
38130   pPager->journalOff = 0;
38131   pPager->journalHdr = 0;
38132   pPager->setMaster = 0;
38133 }
38134
38135 /*
38136 ** This function is called whenever an IOERR or FULL error that requires
38137 ** the pager to transition into the ERROR state may ahve occurred.
38138 ** The first argument is a pointer to the pager structure, the second 
38139 ** the error-code about to be returned by a pager API function. The 
38140 ** value returned is a copy of the second argument to this function. 
38141 **
38142 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38143 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38144 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38145 ** all major API calls on the Pager will immediately return Pager.errCode.
38146 **
38147 ** The ERROR state indicates that the contents of the pager-cache 
38148 ** cannot be trusted. This state can be cleared by completely discarding 
38149 ** the contents of the pager-cache. If a transaction was active when
38150 ** the persistent error occurred, then the rollback journal may need
38151 ** to be replayed to restore the contents of the database file (as if
38152 ** it were a hot-journal).
38153 */
38154 static int pager_error(Pager *pPager, int rc){
38155   int rc2 = rc & 0xff;
38156   assert( rc==SQLITE_OK || !MEMDB );
38157   assert(
38158        pPager->errCode==SQLITE_FULL ||
38159        pPager->errCode==SQLITE_OK ||
38160        (pPager->errCode & 0xff)==SQLITE_IOERR
38161   );
38162   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38163     pPager->errCode = rc;
38164     pPager->eState = PAGER_ERROR;
38165   }
38166   return rc;
38167 }
38168
38169 /*
38170 ** This routine ends a transaction. A transaction is usually ended by 
38171 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
38172 ** after rollback of a hot-journal, or if an error occurs while opening
38173 ** the journal file or writing the very first journal-header of a
38174 ** database transaction.
38175 ** 
38176 ** This routine is never called in PAGER_ERROR state. If it is called
38177 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38178 ** exclusive than a RESERVED lock, it is a no-op.
38179 **
38180 ** Otherwise, any active savepoints are released.
38181 **
38182 ** If the journal file is open, then it is "finalized". Once a journal 
38183 ** file has been finalized it is not possible to use it to roll back a 
38184 ** transaction. Nor will it be considered to be a hot-journal by this
38185 ** or any other database connection. Exactly how a journal is finalized
38186 ** depends on whether or not the pager is running in exclusive mode and
38187 ** the current journal-mode (Pager.journalMode value), as follows:
38188 **
38189 **   journalMode==MEMORY
38190 **     Journal file descriptor is simply closed. This destroys an 
38191 **     in-memory journal.
38192 **
38193 **   journalMode==TRUNCATE
38194 **     Journal file is truncated to zero bytes in size.
38195 **
38196 **   journalMode==PERSIST
38197 **     The first 28 bytes of the journal file are zeroed. This invalidates
38198 **     the first journal header in the file, and hence the entire journal
38199 **     file. An invalid journal file cannot be rolled back.
38200 **
38201 **   journalMode==DELETE
38202 **     The journal file is closed and deleted using sqlite3OsDelete().
38203 **
38204 **     If the pager is running in exclusive mode, this method of finalizing
38205 **     the journal file is never used. Instead, if the journalMode is
38206 **     DELETE and the pager is in exclusive mode, the method described under
38207 **     journalMode==PERSIST is used instead.
38208 **
38209 ** After the journal is finalized, the pager moves to PAGER_READER state.
38210 ** If running in non-exclusive rollback mode, the lock on the file is 
38211 ** downgraded to a SHARED_LOCK.
38212 **
38213 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38214 ** any of the IO operations to finalize the journal file or unlock the
38215 ** database then the IO error code is returned to the user. If the 
38216 ** operation to finalize the journal file fails, then the code still
38217 ** tries to unlock the database file if not in exclusive mode. If the
38218 ** unlock operation fails as well, then the first error code related
38219 ** to the first error encountered (the journal finalization one) is
38220 ** returned.
38221 */
38222 static int pager_end_transaction(Pager *pPager, int hasMaster){
38223   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
38224   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
38225
38226   /* Do nothing if the pager does not have an open write transaction
38227   ** or at least a RESERVED lock. This function may be called when there
38228   ** is no write-transaction active but a RESERVED or greater lock is
38229   ** held under two circumstances:
38230   **
38231   **   1. After a successful hot-journal rollback, it is called with
38232   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38233   **
38234   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
38235   **      lock switches back to locking_mode=normal and then executes a
38236   **      read-transaction, this function is called with eState==PAGER_READER 
38237   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38238   */
38239   assert( assert_pager_state(pPager) );
38240   assert( pPager->eState!=PAGER_ERROR );
38241   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38242     return SQLITE_OK;
38243   }
38244
38245   releaseAllSavepoints(pPager);
38246   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38247   if( isOpen(pPager->jfd) ){
38248     assert( !pagerUseWal(pPager) );
38249
38250     /* Finalize the journal file. */
38251     if( sqlite3IsMemJournal(pPager->jfd) ){
38252       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38253       sqlite3OsClose(pPager->jfd);
38254     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38255       if( pPager->journalOff==0 ){
38256         rc = SQLITE_OK;
38257       }else{
38258         rc = sqlite3OsTruncate(pPager->jfd, 0);
38259       }
38260       pPager->journalOff = 0;
38261     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38262       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38263     ){
38264       rc = zeroJournalHdr(pPager, hasMaster);
38265       pPager->journalOff = 0;
38266     }else{
38267       /* This branch may be executed with Pager.journalMode==MEMORY if
38268       ** a hot-journal was just rolled back. In this case the journal
38269       ** file should be closed and deleted. If this connection writes to
38270       ** the database file, it will do so using an in-memory journal. 
38271       */
38272       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
38273            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38274            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
38275       );
38276       sqlite3OsClose(pPager->jfd);
38277       if( !pPager->tempFile ){
38278         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38279       }
38280     }
38281   }
38282
38283 #ifdef SQLITE_CHECK_PAGES
38284   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38285   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38286     PgHdr *p = pager_lookup(pPager, 1);
38287     if( p ){
38288       p->pageHash = 0;
38289       sqlite3PagerUnref(p);
38290     }
38291   }
38292 #endif
38293
38294   sqlite3BitvecDestroy(pPager->pInJournal);
38295   pPager->pInJournal = 0;
38296   pPager->nRec = 0;
38297   sqlite3PcacheCleanAll(pPager->pPCache);
38298   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38299
38300   if( pagerUseWal(pPager) ){
38301     /* Drop the WAL write-lock, if any. Also, if the connection was in 
38302     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
38303     ** lock held on the database file.
38304     */
38305     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38306     assert( rc2==SQLITE_OK );
38307   }
38308   if( !pPager->exclusiveMode 
38309    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38310   ){
38311     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38312     pPager->changeCountDone = 0;
38313   }
38314   pPager->eState = PAGER_READER;
38315   pPager->setMaster = 0;
38316
38317   return (rc==SQLITE_OK?rc2:rc);
38318 }
38319
38320 /*
38321 ** Execute a rollback if a transaction is active and unlock the 
38322 ** database file. 
38323 **
38324 ** If the pager has already entered the ERROR state, do not attempt 
38325 ** the rollback at this time. Instead, pager_unlock() is called. The
38326 ** call to pager_unlock() will discard all in-memory pages, unlock
38327 ** the database file and move the pager back to OPEN state. If this 
38328 ** means that there is a hot-journal left in the file-system, the next 
38329 ** connection to obtain a shared lock on the pager (which may be this one) 
38330 ** will roll it back.
38331 **
38332 ** If the pager has not already entered the ERROR state, but an IO or
38333 ** malloc error occurs during a rollback, then this will itself cause 
38334 ** the pager to enter the ERROR state. Which will be cleared by the
38335 ** call to pager_unlock(), as described above.
38336 */
38337 static void pagerUnlockAndRollback(Pager *pPager){
38338   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38339     assert( assert_pager_state(pPager) );
38340     if( pPager->eState>=PAGER_WRITER_LOCKED ){
38341       sqlite3BeginBenignMalloc();
38342       sqlite3PagerRollback(pPager);
38343       sqlite3EndBenignMalloc();
38344     }else if( !pPager->exclusiveMode ){
38345       assert( pPager->eState==PAGER_READER );
38346       pager_end_transaction(pPager, 0);
38347     }
38348   }
38349   pager_unlock(pPager);
38350 }
38351
38352 /*
38353 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38354 ** of data. Compute and return a checksum based ont the contents of the 
38355 ** page of data and the current value of pPager->cksumInit.
38356 **
38357 ** This is not a real checksum. It is really just the sum of the 
38358 ** random initial value (pPager->cksumInit) and every 200th byte
38359 ** of the page data, starting with byte offset (pPager->pageSize%200).
38360 ** Each byte is interpreted as an 8-bit unsigned integer.
38361 **
38362 ** Changing the formula used to compute this checksum results in an
38363 ** incompatible journal file format.
38364 **
38365 ** If journal corruption occurs due to a power failure, the most likely 
38366 ** scenario is that one end or the other of the record will be changed. 
38367 ** It is much less likely that the two ends of the journal record will be
38368 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
38369 ** though fast and simple, catches the mostly likely kind of corruption.
38370 */
38371 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38372   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
38373   int i = pPager->pageSize-200;          /* Loop counter */
38374   while( i>0 ){
38375     cksum += aData[i];
38376     i -= 200;
38377   }
38378   return cksum;
38379 }
38380
38381 /*
38382 ** Report the current page size and number of reserved bytes back
38383 ** to the codec.
38384 */
38385 #ifdef SQLITE_HAS_CODEC
38386 static void pagerReportSize(Pager *pPager){
38387   if( pPager->xCodecSizeChng ){
38388     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38389                            (int)pPager->nReserve);
38390   }
38391 }
38392 #else
38393 # define pagerReportSize(X)     /* No-op if we do not support a codec */
38394 #endif
38395
38396 /*
38397 ** Read a single page from either the journal file (if isMainJrnl==1) or
38398 ** from the sub-journal (if isMainJrnl==0) and playback that page.
38399 ** The page begins at offset *pOffset into the file. The *pOffset
38400 ** value is increased to the start of the next page in the journal.
38401 **
38402 ** The main rollback journal uses checksums - the statement journal does 
38403 ** not.
38404 **
38405 ** If the page number of the page record read from the (sub-)journal file
38406 ** is greater than the current value of Pager.dbSize, then playback is
38407 ** skipped and SQLITE_OK is returned.
38408 **
38409 ** If pDone is not NULL, then it is a record of pages that have already
38410 ** been played back.  If the page at *pOffset has already been played back
38411 ** (if the corresponding pDone bit is set) then skip the playback.
38412 ** Make sure the pDone bit corresponding to the *pOffset page is set
38413 ** prior to returning.
38414 **
38415 ** If the page record is successfully read from the (sub-)journal file
38416 ** and played back, then SQLITE_OK is returned. If an IO error occurs
38417 ** while reading the record from the (sub-)journal file or while writing
38418 ** to the database file, then the IO error code is returned. If data
38419 ** is successfully read from the (sub-)journal file but appears to be
38420 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38421 ** two circumstances:
38422 ** 
38423 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38424 **   * If the record is being rolled back from the main journal file
38425 **     and the checksum field does not match the record content.
38426 **
38427 ** Neither of these two scenarios are possible during a savepoint rollback.
38428 **
38429 ** If this is a savepoint rollback, then memory may have to be dynamically
38430 ** allocated by this function. If this is the case and an allocation fails,
38431 ** SQLITE_NOMEM is returned.
38432 */
38433 static int pager_playback_one_page(
38434   Pager *pPager,                /* The pager being played back */
38435   i64 *pOffset,                 /* Offset of record to playback */
38436   Bitvec *pDone,                /* Bitvec of pages already played back */
38437   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
38438   int isSavepnt                 /* True for a savepoint rollback */
38439 ){
38440   int rc;
38441   PgHdr *pPg;                   /* An existing page in the cache */
38442   Pgno pgno;                    /* The page number of a page in journal */
38443   u32 cksum;                    /* Checksum used for sanity checking */
38444   char *aData;                  /* Temporary storage for the page */
38445   sqlite3_file *jfd;            /* The file descriptor for the journal file */
38446   int isSynced;                 /* True if journal page is synced */
38447
38448   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
38449   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
38450   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
38451   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
38452
38453   aData = pPager->pTmpSpace;
38454   assert( aData );         /* Temp storage must have already been allocated */
38455   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38456
38457   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
38458   ** or savepoint rollback done at the request of the caller) or this is
38459   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38460   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38461   ** only reads from the main journal, not the sub-journal.
38462   */
38463   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38464        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38465   );
38466   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38467
38468   /* Read the page number and page data from the journal or sub-journal
38469   ** file. Return an error code to the caller if an IO error occurs.
38470   */
38471   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38472   rc = read32bits(jfd, *pOffset, &pgno);
38473   if( rc!=SQLITE_OK ) return rc;
38474   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38475   if( rc!=SQLITE_OK ) return rc;
38476   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38477
38478   /* Sanity checking on the page.  This is more important that I originally
38479   ** thought.  If a power failure occurs while the journal is being written,
38480   ** it could cause invalid data to be written into the journal.  We need to
38481   ** detect this invalid data (with high probability) and ignore it.
38482   */
38483   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38484     assert( !isSavepnt );
38485     return SQLITE_DONE;
38486   }
38487   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38488     return SQLITE_OK;
38489   }
38490   if( isMainJrnl ){
38491     rc = read32bits(jfd, (*pOffset)-4, &cksum);
38492     if( rc ) return rc;
38493     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38494       return SQLITE_DONE;
38495     }
38496   }
38497
38498   /* If this page has already been played by before during the current
38499   ** rollback, then don't bother to play it back again.
38500   */
38501   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38502     return rc;
38503   }
38504
38505   /* When playing back page 1, restore the nReserve setting
38506   */
38507   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38508     pPager->nReserve = ((u8*)aData)[20];
38509     pagerReportSize(pPager);
38510   }
38511
38512   /* If the pager is in CACHEMOD state, then there must be a copy of this
38513   ** page in the pager cache. In this case just update the pager cache,
38514   ** not the database file. The page is left marked dirty in this case.
38515   **
38516   ** An exception to the above rule: If the database is in no-sync mode
38517   ** and a page is moved during an incremental vacuum then the page may
38518   ** not be in the pager cache. Later: if a malloc() or IO error occurs
38519   ** during a Movepage() call, then the page may not be in the cache
38520   ** either. So the condition described in the above paragraph is not
38521   ** assert()able.
38522   **
38523   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38524   ** pager cache if it exists and the main file. The page is then marked 
38525   ** not dirty. Since this code is only executed in PAGER_OPEN state for
38526   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38527   ** if the pager is in OPEN state.
38528   **
38529   ** Ticket #1171:  The statement journal might contain page content that is
38530   ** different from the page content at the start of the transaction.
38531   ** This occurs when a page is changed prior to the start of a statement
38532   ** then changed again within the statement.  When rolling back such a
38533   ** statement we must not write to the original database unless we know
38534   ** for certain that original page contents are synced into the main rollback
38535   ** journal.  Otherwise, a power loss might leave modified data in the
38536   ** database file without an entry in the rollback journal that can
38537   ** restore the database to its original form.  Two conditions must be
38538   ** met before writing to the database files. (1) the database must be
38539   ** locked.  (2) we know that the original page content is fully synced
38540   ** in the main journal either because the page is not in cache or else
38541   ** the page is marked as needSync==0.
38542   **
38543   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
38544   ** is possible to fail a statement on a database that does not yet exist.
38545   ** Do not attempt to write if database file has never been opened.
38546   */
38547   if( pagerUseWal(pPager) ){
38548     pPg = 0;
38549   }else{
38550     pPg = pager_lookup(pPager, pgno);
38551   }
38552   assert( pPg || !MEMDB );
38553   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
38554   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
38555            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
38556            (isMainJrnl?"main-journal":"sub-journal")
38557   ));
38558   if( isMainJrnl ){
38559     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
38560   }else{
38561     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
38562   }
38563   if( isOpen(pPager->fd)
38564    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38565    && isSynced
38566   ){
38567     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
38568     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
38569     assert( !pagerUseWal(pPager) );
38570     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
38571     if( pgno>pPager->dbFileSize ){
38572       pPager->dbFileSize = pgno;
38573     }
38574     if( pPager->pBackup ){
38575       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
38576       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
38577       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
38578     }
38579   }else if( !isMainJrnl && pPg==0 ){
38580     /* If this is a rollback of a savepoint and data was not written to
38581     ** the database and the page is not in-memory, there is a potential
38582     ** problem. When the page is next fetched by the b-tree layer, it 
38583     ** will be read from the database file, which may or may not be 
38584     ** current. 
38585     **
38586     ** There are a couple of different ways this can happen. All are quite
38587     ** obscure. When running in synchronous mode, this can only happen 
38588     ** if the page is on the free-list at the start of the transaction, then
38589     ** populated, then moved using sqlite3PagerMovepage().
38590     **
38591     ** The solution is to add an in-memory page to the cache containing
38592     ** the data just read from the sub-journal. Mark the page as dirty 
38593     ** and if the pager requires a journal-sync, then mark the page as 
38594     ** requiring a journal-sync before it is written.
38595     */
38596     assert( isSavepnt );
38597     assert( pPager->doNotSpill==0 );
38598     pPager->doNotSpill++;
38599     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
38600     assert( pPager->doNotSpill==1 );
38601     pPager->doNotSpill--;
38602     if( rc!=SQLITE_OK ) return rc;
38603     pPg->flags &= ~PGHDR_NEED_READ;
38604     sqlite3PcacheMakeDirty(pPg);
38605   }
38606   if( pPg ){
38607     /* No page should ever be explicitly rolled back that is in use, except
38608     ** for page 1 which is held in use in order to keep the lock on the
38609     ** database active. However such a page may be rolled back as a result
38610     ** of an internal error resulting in an automatic call to
38611     ** sqlite3PagerRollback().
38612     */
38613     void *pData;
38614     pData = pPg->pData;
38615     memcpy(pData, (u8*)aData, pPager->pageSize);
38616     pPager->xReiniter(pPg);
38617     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
38618       /* If the contents of this page were just restored from the main 
38619       ** journal file, then its content must be as they were when the 
38620       ** transaction was first opened. In this case we can mark the page
38621       ** as clean, since there will be no need to write it out to the
38622       ** database.
38623       **
38624       ** There is one exception to this rule. If the page is being rolled
38625       ** back as part of a savepoint (or statement) rollback from an 
38626       ** unsynced portion of the main journal file, then it is not safe
38627       ** to mark the page as clean. This is because marking the page as
38628       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
38629       ** already in the journal file (recorded in Pager.pInJournal) and
38630       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
38631       ** again within this transaction, it will be marked as dirty but
38632       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
38633       ** be written out into the database file before its journal file
38634       ** segment is synced. If a crash occurs during or following this,
38635       ** database corruption may ensue.
38636       */
38637       assert( !pagerUseWal(pPager) );
38638       sqlite3PcacheMakeClean(pPg);
38639     }
38640     pager_set_pagehash(pPg);
38641
38642     /* If this was page 1, then restore the value of Pager.dbFileVers.
38643     ** Do this before any decoding. */
38644     if( pgno==1 ){
38645       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
38646     }
38647
38648     /* Decode the page just read from disk */
38649     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
38650     sqlite3PcacheRelease(pPg);
38651   }
38652   return rc;
38653 }
38654
38655 /*
38656 ** Parameter zMaster is the name of a master journal file. A single journal
38657 ** file that referred to the master journal file has just been rolled back.
38658 ** This routine checks if it is possible to delete the master journal file,
38659 ** and does so if it is.
38660 **
38661 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
38662 ** available for use within this function.
38663 **
38664 ** When a master journal file is created, it is populated with the names 
38665 ** of all of its child journals, one after another, formatted as utf-8 
38666 ** encoded text. The end of each child journal file is marked with a 
38667 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
38668 ** file for a transaction involving two databases might be:
38669 **
38670 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
38671 **
38672 ** A master journal file may only be deleted once all of its child 
38673 ** journals have been rolled back.
38674 **
38675 ** This function reads the contents of the master-journal file into 
38676 ** memory and loops through each of the child journal names. For
38677 ** each child journal, it checks if:
38678 **
38679 **   * if the child journal exists, and if so
38680 **   * if the child journal contains a reference to master journal 
38681 **     file zMaster
38682 **
38683 ** If a child journal can be found that matches both of the criteria
38684 ** above, this function returns without doing anything. Otherwise, if
38685 ** no such child journal can be found, file zMaster is deleted from
38686 ** the file-system using sqlite3OsDelete().
38687 **
38688 ** If an IO error within this function, an error code is returned. This
38689 ** function allocates memory by calling sqlite3Malloc(). If an allocation
38690 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
38691 ** occur, SQLITE_OK is returned.
38692 **
38693 ** TODO: This function allocates a single block of memory to load
38694 ** the entire contents of the master journal file. This could be
38695 ** a couple of kilobytes or so - potentially larger than the page 
38696 ** size.
38697 */
38698 static int pager_delmaster(Pager *pPager, const char *zMaster){
38699   sqlite3_vfs *pVfs = pPager->pVfs;
38700   int rc;                   /* Return code */
38701   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
38702   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
38703   char *zMasterJournal = 0; /* Contents of master journal file */
38704   i64 nMasterJournal;       /* Size of master journal file */
38705   char *zJournal;           /* Pointer to one journal within MJ file */
38706   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
38707   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
38708
38709   /* Allocate space for both the pJournal and pMaster file descriptors.
38710   ** If successful, open the master journal file for reading.
38711   */
38712   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
38713   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
38714   if( !pMaster ){
38715     rc = SQLITE_NOMEM;
38716   }else{
38717     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
38718     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
38719   }
38720   if( rc!=SQLITE_OK ) goto delmaster_out;
38721
38722   /* Load the entire master journal file into space obtained from
38723   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
38724   ** sufficient space (in zMasterPtr) to hold the names of master
38725   ** journal files extracted from regular rollback-journals.
38726   */
38727   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
38728   if( rc!=SQLITE_OK ) goto delmaster_out;
38729   nMasterPtr = pVfs->mxPathname+1;
38730   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
38731   if( !zMasterJournal ){
38732     rc = SQLITE_NOMEM;
38733     goto delmaster_out;
38734   }
38735   zMasterPtr = &zMasterJournal[nMasterJournal+1];
38736   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
38737   if( rc!=SQLITE_OK ) goto delmaster_out;
38738   zMasterJournal[nMasterJournal] = 0;
38739
38740   zJournal = zMasterJournal;
38741   while( (zJournal-zMasterJournal)<nMasterJournal ){
38742     int exists;
38743     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
38744     if( rc!=SQLITE_OK ){
38745       goto delmaster_out;
38746     }
38747     if( exists ){
38748       /* One of the journals pointed to by the master journal exists.
38749       ** Open it and check if it points at the master journal. If
38750       ** so, return without deleting the master journal file.
38751       */
38752       int c;
38753       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
38754       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
38755       if( rc!=SQLITE_OK ){
38756         goto delmaster_out;
38757       }
38758
38759       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
38760       sqlite3OsClose(pJournal);
38761       if( rc!=SQLITE_OK ){
38762         goto delmaster_out;
38763       }
38764
38765       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
38766       if( c ){
38767         /* We have a match. Do not delete the master journal file. */
38768         goto delmaster_out;
38769       }
38770     }
38771     zJournal += (sqlite3Strlen30(zJournal)+1);
38772   }
38773  
38774   sqlite3OsClose(pMaster);
38775   rc = sqlite3OsDelete(pVfs, zMaster, 0);
38776
38777 delmaster_out:
38778   sqlite3_free(zMasterJournal);
38779   if( pMaster ){
38780     sqlite3OsClose(pMaster);
38781     assert( !isOpen(pJournal) );
38782     sqlite3_free(pMaster);
38783   }
38784   return rc;
38785 }
38786
38787
38788 /*
38789 ** This function is used to change the actual size of the database 
38790 ** file in the file-system. This only happens when committing a transaction,
38791 ** or rolling back a transaction (including rolling back a hot-journal).
38792 **
38793 ** If the main database file is not open, or the pager is not in either
38794 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
38795 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
38796 ** If the file on disk is currently larger than nPage pages, then use the VFS
38797 ** xTruncate() method to truncate it.
38798 **
38799 ** Or, it might might be the case that the file on disk is smaller than 
38800 ** nPage pages. Some operating system implementations can get confused if 
38801 ** you try to truncate a file to some size that is larger than it 
38802 ** currently is, so detect this case and write a single zero byte to 
38803 ** the end of the new file instead.
38804 **
38805 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
38806 ** the database file, return the error code to the caller.
38807 */
38808 static int pager_truncate(Pager *pPager, Pgno nPage){
38809   int rc = SQLITE_OK;
38810   assert( pPager->eState!=PAGER_ERROR );
38811   assert( pPager->eState!=PAGER_READER );
38812   
38813   if( isOpen(pPager->fd) 
38814    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
38815   ){
38816     i64 currentSize, newSize;
38817     int szPage = pPager->pageSize;
38818     assert( pPager->eLock==EXCLUSIVE_LOCK );
38819     /* TODO: Is it safe to use Pager.dbFileSize here? */
38820     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
38821     newSize = szPage*(i64)nPage;
38822     if( rc==SQLITE_OK && currentSize!=newSize ){
38823       if( currentSize>newSize ){
38824         rc = sqlite3OsTruncate(pPager->fd, newSize);
38825       }else{
38826         char *pTmp = pPager->pTmpSpace;
38827         memset(pTmp, 0, szPage);
38828         testcase( (newSize-szPage) <  currentSize );
38829         testcase( (newSize-szPage) == currentSize );
38830         testcase( (newSize-szPage) >  currentSize );
38831         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
38832       }
38833       if( rc==SQLITE_OK ){
38834         pPager->dbFileSize = nPage;
38835       }
38836     }
38837   }
38838   return rc;
38839 }
38840
38841 /*
38842 ** Set the value of the Pager.sectorSize variable for the given
38843 ** pager based on the value returned by the xSectorSize method
38844 ** of the open database file. The sector size will be used used 
38845 ** to determine the size and alignment of journal header and 
38846 ** master journal pointers within created journal files.
38847 **
38848 ** For temporary files the effective sector size is always 512 bytes.
38849 **
38850 ** Otherwise, for non-temporary files, the effective sector size is
38851 ** the value returned by the xSectorSize() method rounded up to 32 if
38852 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
38853 ** is greater than MAX_SECTOR_SIZE.
38854 */
38855 static void setSectorSize(Pager *pPager){
38856   assert( isOpen(pPager->fd) || pPager->tempFile );
38857
38858   if( !pPager->tempFile ){
38859     /* Sector size doesn't matter for temporary files. Also, the file
38860     ** may not have been opened yet, in which case the OsSectorSize()
38861     ** call will segfault.
38862     */
38863     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
38864   }
38865   if( pPager->sectorSize<32 ){
38866     pPager->sectorSize = 512;
38867   }
38868   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
38869     assert( MAX_SECTOR_SIZE>=512 );
38870     pPager->sectorSize = MAX_SECTOR_SIZE;
38871   }
38872 }
38873
38874 /*
38875 ** Playback the journal and thus restore the database file to
38876 ** the state it was in before we started making changes.  
38877 **
38878 ** The journal file format is as follows: 
38879 **
38880 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
38881 **  (2)  4 byte big-endian integer which is the number of valid page records
38882 **       in the journal.  If this value is 0xffffffff, then compute the
38883 **       number of page records from the journal size.
38884 **  (3)  4 byte big-endian integer which is the initial value for the 
38885 **       sanity checksum.
38886 **  (4)  4 byte integer which is the number of pages to truncate the
38887 **       database to during a rollback.
38888 **  (5)  4 byte big-endian integer which is the sector size.  The header
38889 **       is this many bytes in size.
38890 **  (6)  4 byte big-endian integer which is the page size.
38891 **  (7)  zero padding out to the next sector size.
38892 **  (8)  Zero or more pages instances, each as follows:
38893 **        +  4 byte page number.
38894 **        +  pPager->pageSize bytes of data.
38895 **        +  4 byte checksum
38896 **
38897 ** When we speak of the journal header, we mean the first 7 items above.
38898 ** Each entry in the journal is an instance of the 8th item.
38899 **
38900 ** Call the value from the second bullet "nRec".  nRec is the number of
38901 ** valid page entries in the journal.  In most cases, you can compute the
38902 ** value of nRec from the size of the journal file.  But if a power
38903 ** failure occurred while the journal was being written, it could be the
38904 ** case that the size of the journal file had already been increased but
38905 ** the extra entries had not yet made it safely to disk.  In such a case,
38906 ** the value of nRec computed from the file size would be too large.  For
38907 ** that reason, we always use the nRec value in the header.
38908 **
38909 ** If the nRec value is 0xffffffff it means that nRec should be computed
38910 ** from the file size.  This value is used when the user selects the
38911 ** no-sync option for the journal.  A power failure could lead to corruption
38912 ** in this case.  But for things like temporary table (which will be
38913 ** deleted when the power is restored) we don't care.  
38914 **
38915 ** If the file opened as the journal file is not a well-formed
38916 ** journal file then all pages up to the first corrupted page are rolled
38917 ** back (or no pages if the journal header is corrupted). The journal file
38918 ** is then deleted and SQLITE_OK returned, just as if no corruption had
38919 ** been encountered.
38920 **
38921 ** If an I/O or malloc() error occurs, the journal-file is not deleted
38922 ** and an error code is returned.
38923 **
38924 ** The isHot parameter indicates that we are trying to rollback a journal
38925 ** that might be a hot journal.  Or, it could be that the journal is 
38926 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
38927 ** If the journal really is hot, reset the pager cache prior rolling
38928 ** back any content.  If the journal is merely persistent, no reset is
38929 ** needed.
38930 */
38931 static int pager_playback(Pager *pPager, int isHot){
38932   sqlite3_vfs *pVfs = pPager->pVfs;
38933   i64 szJ;                 /* Size of the journal file in bytes */
38934   u32 nRec;                /* Number of Records in the journal */
38935   u32 u;                   /* Unsigned loop counter */
38936   Pgno mxPg = 0;           /* Size of the original file in pages */
38937   int rc;                  /* Result code of a subroutine */
38938   int res = 1;             /* Value returned by sqlite3OsAccess() */
38939   char *zMaster = 0;       /* Name of master journal file if any */
38940   int needPagerReset;      /* True to reset page prior to first page rollback */
38941
38942   /* Figure out how many records are in the journal.  Abort early if
38943   ** the journal is empty.
38944   */
38945   assert( isOpen(pPager->jfd) );
38946   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
38947   if( rc!=SQLITE_OK ){
38948     goto end_playback;
38949   }
38950
38951   /* Read the master journal name from the journal, if it is present.
38952   ** If a master journal file name is specified, but the file is not
38953   ** present on disk, then the journal is not hot and does not need to be
38954   ** played back.
38955   **
38956   ** TODO: Technically the following is an error because it assumes that
38957   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
38958   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
38959   **  mxPathname is 512, which is the same as the minimum allowable value
38960   ** for pageSize.
38961   */
38962   zMaster = pPager->pTmpSpace;
38963   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
38964   if( rc==SQLITE_OK && zMaster[0] ){
38965     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
38966   }
38967   zMaster = 0;
38968   if( rc!=SQLITE_OK || !res ){
38969     goto end_playback;
38970   }
38971   pPager->journalOff = 0;
38972   needPagerReset = isHot;
38973
38974   /* This loop terminates either when a readJournalHdr() or 
38975   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
38976   ** occurs. 
38977   */
38978   while( 1 ){
38979     /* Read the next journal header from the journal file.  If there are
38980     ** not enough bytes left in the journal file for a complete header, or
38981     ** it is corrupted, then a process must have failed while writing it.
38982     ** This indicates nothing more needs to be rolled back.
38983     */
38984     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
38985     if( rc!=SQLITE_OK ){ 
38986       if( rc==SQLITE_DONE ){
38987         rc = SQLITE_OK;
38988       }
38989       goto end_playback;
38990     }
38991
38992     /* If nRec is 0xffffffff, then this journal was created by a process
38993     ** working in no-sync mode. This means that the rest of the journal
38994     ** file consists of pages, there are no more journal headers. Compute
38995     ** the value of nRec based on this assumption.
38996     */
38997     if( nRec==0xffffffff ){
38998       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
38999       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39000     }
39001
39002     /* If nRec is 0 and this rollback is of a transaction created by this
39003     ** process and if this is the final header in the journal, then it means
39004     ** that this part of the journal was being filled but has not yet been
39005     ** synced to disk.  Compute the number of pages based on the remaining
39006     ** size of the file.
39007     **
39008     ** The third term of the test was added to fix ticket #2565.
39009     ** When rolling back a hot journal, nRec==0 always means that the next
39010     ** chunk of the journal contains zero pages to be rolled back.  But
39011     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39012     ** the journal, it means that the journal might contain additional
39013     ** pages that need to be rolled back and that the number of pages 
39014     ** should be computed based on the journal file size.
39015     */
39016     if( nRec==0 && !isHot &&
39017         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39018       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39019     }
39020
39021     /* If this is the first header read from the journal, truncate the
39022     ** database file back to its original size.
39023     */
39024     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39025       rc = pager_truncate(pPager, mxPg);
39026       if( rc!=SQLITE_OK ){
39027         goto end_playback;
39028       }
39029       pPager->dbSize = mxPg;
39030     }
39031
39032     /* Copy original pages out of the journal and back into the 
39033     ** database file and/or page cache.
39034     */
39035     for(u=0; u<nRec; u++){
39036       if( needPagerReset ){
39037         pager_reset(pPager);
39038         needPagerReset = 0;
39039       }
39040       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39041       if( rc!=SQLITE_OK ){
39042         if( rc==SQLITE_DONE ){
39043           rc = SQLITE_OK;
39044           pPager->journalOff = szJ;
39045           break;
39046         }else if( rc==SQLITE_IOERR_SHORT_READ ){
39047           /* If the journal has been truncated, simply stop reading and
39048           ** processing the journal. This might happen if the journal was
39049           ** not completely written and synced prior to a crash.  In that
39050           ** case, the database should have never been written in the
39051           ** first place so it is OK to simply abandon the rollback. */
39052           rc = SQLITE_OK;
39053           goto end_playback;
39054         }else{
39055           /* If we are unable to rollback, quit and return the error
39056           ** code.  This will cause the pager to enter the error state
39057           ** so that no further harm will be done.  Perhaps the next
39058           ** process to come along will be able to rollback the database.
39059           */
39060           goto end_playback;
39061         }
39062       }
39063     }
39064   }
39065   /*NOTREACHED*/
39066   assert( 0 );
39067
39068 end_playback:
39069   /* Following a rollback, the database file should be back in its original
39070   ** state prior to the start of the transaction, so invoke the
39071   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39072   ** assertion that the transaction counter was modified.
39073   */
39074   assert(
39075     pPager->fd->pMethods==0 ||
39076     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39077   );
39078
39079   /* If this playback is happening automatically as a result of an IO or 
39080   ** malloc error that occurred after the change-counter was updated but 
39081   ** before the transaction was committed, then the change-counter 
39082   ** modification may just have been reverted. If this happens in exclusive 
39083   ** mode, then subsequent transactions performed by the connection will not
39084   ** update the change-counter at all. This may lead to cache inconsistency
39085   ** problems for other processes at some point in the future. So, just
39086   ** in case this has happened, clear the changeCountDone flag now.
39087   */
39088   pPager->changeCountDone = pPager->tempFile;
39089
39090   if( rc==SQLITE_OK ){
39091     zMaster = pPager->pTmpSpace;
39092     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39093     testcase( rc!=SQLITE_OK );
39094   }
39095   if( rc==SQLITE_OK
39096    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39097   ){
39098     rc = sqlite3PagerSync(pPager);
39099   }
39100   if( rc==SQLITE_OK ){
39101     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39102     testcase( rc!=SQLITE_OK );
39103   }
39104   if( rc==SQLITE_OK && zMaster[0] && res ){
39105     /* If there was a master journal and this routine will return success,
39106     ** see if it is possible to delete the master journal.
39107     */
39108     rc = pager_delmaster(pPager, zMaster);
39109     testcase( rc!=SQLITE_OK );
39110   }
39111
39112   /* The Pager.sectorSize variable may have been updated while rolling
39113   ** back a journal created by a process with a different sector size
39114   ** value. Reset it to the correct value for this process.
39115   */
39116   setSectorSize(pPager);
39117   return rc;
39118 }
39119
39120
39121 /*
39122 ** Read the content for page pPg out of the database file and into 
39123 ** pPg->pData. A shared lock or greater must be held on the database
39124 ** file before this function is called.
39125 **
39126 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39127 ** the value read from the database file.
39128 **
39129 ** If an IO error occurs, then the IO error is returned to the caller.
39130 ** Otherwise, SQLITE_OK is returned.
39131 */
39132 static int readDbPage(PgHdr *pPg){
39133   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39134   Pgno pgno = pPg->pgno;       /* Page number to read */
39135   int rc = SQLITE_OK;          /* Return code */
39136   int isInWal = 0;             /* True if page is in log file */
39137   int pgsz = pPager->pageSize; /* Number of bytes to read */
39138
39139   assert( pPager->eState>=PAGER_READER && !MEMDB );
39140   assert( isOpen(pPager->fd) );
39141
39142   if( NEVER(!isOpen(pPager->fd)) ){
39143     assert( pPager->tempFile );
39144     memset(pPg->pData, 0, pPager->pageSize);
39145     return SQLITE_OK;
39146   }
39147
39148   if( pagerUseWal(pPager) ){
39149     /* Try to pull the page from the write-ahead log. */
39150     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39151   }
39152   if( rc==SQLITE_OK && !isInWal ){
39153     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39154     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39155     if( rc==SQLITE_IOERR_SHORT_READ ){
39156       rc = SQLITE_OK;
39157     }
39158   }
39159
39160   if( pgno==1 ){
39161     if( rc ){
39162       /* If the read is unsuccessful, set the dbFileVers[] to something
39163       ** that will never be a valid file version.  dbFileVers[] is a copy
39164       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
39165       ** zero or the size of the database in page. Bytes 32..35 and 35..39
39166       ** should be page numbers which are never 0xffffffff.  So filling
39167       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39168       **
39169       ** For an encrypted database, the situation is more complex:  bytes
39170       ** 24..39 of the database are white noise.  But the probability of
39171       ** white noising equaling 16 bytes of 0xff is vanishingly small so
39172       ** we should still be ok.
39173       */
39174       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39175     }else{
39176       u8 *dbFileVers = &((u8*)pPg->pData)[24];
39177       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39178     }
39179   }
39180   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39181
39182   PAGER_INCR(sqlite3_pager_readdb_count);
39183   PAGER_INCR(pPager->nRead);
39184   IOTRACE(("PGIN %p %d\n", pPager, pgno));
39185   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39186                PAGERID(pPager), pgno, pager_pagehash(pPg)));
39187
39188   return rc;
39189 }
39190
39191 /*
39192 ** Update the value of the change-counter at offsets 24 and 92 in
39193 ** the header and the sqlite version number at offset 96.
39194 **
39195 ** This is an unconditional update.  See also the pager_incr_changecounter()
39196 ** routine which only updates the change-counter if the update is actually
39197 ** needed, as determined by the pPager->changeCountDone state variable.
39198 */
39199 static void pager_write_changecounter(PgHdr *pPg){
39200   u32 change_counter;
39201
39202   /* Increment the value just read and write it back to byte 24. */
39203   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39204   put32bits(((char*)pPg->pData)+24, change_counter);
39205
39206   /* Also store the SQLite version number in bytes 96..99 and in
39207   ** bytes 92..95 store the change counter for which the version number
39208   ** is valid. */
39209   put32bits(((char*)pPg->pData)+92, change_counter);
39210   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39211 }
39212
39213 #ifndef SQLITE_OMIT_WAL
39214 /*
39215 ** This function is invoked once for each page that has already been 
39216 ** written into the log file when a WAL transaction is rolled back.
39217 ** Parameter iPg is the page number of said page. The pCtx argument 
39218 ** is actually a pointer to the Pager structure.
39219 **
39220 ** If page iPg is present in the cache, and has no outstanding references,
39221 ** it is discarded. Otherwise, if there are one or more outstanding
39222 ** references, the page content is reloaded from the database. If the
39223 ** attempt to reload content from the database is required and fails, 
39224 ** return an SQLite error code. Otherwise, SQLITE_OK.
39225 */
39226 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39227   int rc = SQLITE_OK;
39228   Pager *pPager = (Pager *)pCtx;
39229   PgHdr *pPg;
39230
39231   pPg = sqlite3PagerLookup(pPager, iPg);
39232   if( pPg ){
39233     if( sqlite3PcachePageRefcount(pPg)==1 ){
39234       sqlite3PcacheDrop(pPg);
39235     }else{
39236       rc = readDbPage(pPg);
39237       if( rc==SQLITE_OK ){
39238         pPager->xReiniter(pPg);
39239       }
39240       sqlite3PagerUnref(pPg);
39241     }
39242   }
39243
39244   /* Normally, if a transaction is rolled back, any backup processes are
39245   ** updated as data is copied out of the rollback journal and into the
39246   ** database. This is not generally possible with a WAL database, as
39247   ** rollback involves simply truncating the log file. Therefore, if one
39248   ** or more frames have already been written to the log (and therefore 
39249   ** also copied into the backup databases) as part of this transaction,
39250   ** the backups must be restarted.
39251   */
39252   sqlite3BackupRestart(pPager->pBackup);
39253
39254   return rc;
39255 }
39256
39257 /*
39258 ** This function is called to rollback a transaction on a WAL database.
39259 */
39260 static int pagerRollbackWal(Pager *pPager){
39261   int rc;                         /* Return Code */
39262   PgHdr *pList;                   /* List of dirty pages to revert */
39263
39264   /* For all pages in the cache that are currently dirty or have already
39265   ** been written (but not committed) to the log file, do one of the 
39266   ** following:
39267   **
39268   **   + Discard the cached page (if refcount==0), or
39269   **   + Reload page content from the database (if refcount>0).
39270   */
39271   pPager->dbSize = pPager->dbOrigSize;
39272   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39273   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39274   while( pList && rc==SQLITE_OK ){
39275     PgHdr *pNext = pList->pDirty;
39276     rc = pagerUndoCallback((void *)pPager, pList->pgno);
39277     pList = pNext;
39278   }
39279
39280   return rc;
39281 }
39282
39283 /*
39284 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39285 ** the contents of the list of pages headed by pList (connected by pDirty),
39286 ** this function notifies any active backup processes that the pages have
39287 ** changed. 
39288 **
39289 ** The list of pages passed into this routine is always sorted by page number.
39290 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39291 */ 
39292 static int pagerWalFrames(
39293   Pager *pPager,                  /* Pager object */
39294   PgHdr *pList,                   /* List of frames to log */
39295   Pgno nTruncate,                 /* Database size after this commit */
39296   int isCommit,                   /* True if this is a commit */
39297   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
39298 ){
39299   int rc;                         /* Return code */
39300 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39301   PgHdr *p;                       /* For looping over pages */
39302 #endif
39303
39304   assert( pPager->pWal );
39305 #ifdef SQLITE_DEBUG
39306   /* Verify that the page list is in accending order */
39307   for(p=pList; p && p->pDirty; p=p->pDirty){
39308     assert( p->pgno < p->pDirty->pgno );
39309   }
39310 #endif
39311
39312   if( isCommit ){
39313     /* If a WAL transaction is being committed, there is no point in writing
39314     ** any pages with page numbers greater than nTruncate into the WAL file.
39315     ** They will never be read by any client. So remove them from the pDirty
39316     ** list here. */
39317     PgHdr *p;
39318     PgHdr **ppNext = &pList;
39319     for(p=pList; (*ppNext = p); p=p->pDirty){
39320       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39321     }
39322     assert( pList );
39323   }
39324
39325   if( pList->pgno==1 ) pager_write_changecounter(pList);
39326   rc = sqlite3WalFrames(pPager->pWal, 
39327       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39328   );
39329   if( rc==SQLITE_OK && pPager->pBackup ){
39330     PgHdr *p;
39331     for(p=pList; p; p=p->pDirty){
39332       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39333     }
39334   }
39335
39336 #ifdef SQLITE_CHECK_PAGES
39337   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39338   for(p=pList; p; p=p->pDirty){
39339     pager_set_pagehash(p);
39340   }
39341 #endif
39342
39343   return rc;
39344 }
39345
39346 /*
39347 ** Begin a read transaction on the WAL.
39348 **
39349 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39350 ** makes a snapshot of the database at the current point in time and preserves
39351 ** that snapshot for use by the reader in spite of concurrently changes by
39352 ** other writers or checkpointers.
39353 */
39354 static int pagerBeginReadTransaction(Pager *pPager){
39355   int rc;                         /* Return code */
39356   int changed = 0;                /* True if cache must be reset */
39357
39358   assert( pagerUseWal(pPager) );
39359   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39360
39361   /* sqlite3WalEndReadTransaction() was not called for the previous
39362   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
39363   ** are in locking_mode=NORMAL and EndRead() was previously called,
39364   ** the duplicate call is harmless.
39365   */
39366   sqlite3WalEndReadTransaction(pPager->pWal);
39367
39368   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39369   if( rc!=SQLITE_OK || changed ){
39370     pager_reset(pPager);
39371   }
39372
39373   return rc;
39374 }
39375 #endif
39376
39377 /*
39378 ** This function is called as part of the transition from PAGER_OPEN
39379 ** to PAGER_READER state to determine the size of the database file
39380 ** in pages (assuming the page size currently stored in Pager.pageSize).
39381 **
39382 ** If no error occurs, SQLITE_OK is returned and the size of the database
39383 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39384 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39385 */
39386 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39387   Pgno nPage;                     /* Value to return via *pnPage */
39388
39389   /* Query the WAL sub-system for the database size. The WalDbsize()
39390   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39391   ** if the database size is not available. The database size is not
39392   ** available from the WAL sub-system if the log file is empty or
39393   ** contains no valid committed transactions.
39394   */
39395   assert( pPager->eState==PAGER_OPEN );
39396   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39397   nPage = sqlite3WalDbsize(pPager->pWal);
39398
39399   /* If the database size was not available from the WAL sub-system,
39400   ** determine it based on the size of the database file. If the size
39401   ** of the database file is not an integer multiple of the page-size,
39402   ** round down to the nearest page. Except, any file larger than 0
39403   ** bytes in size is considered to contain at least one page.
39404   */
39405   if( nPage==0 ){
39406     i64 n = 0;                    /* Size of db file in bytes */
39407     assert( isOpen(pPager->fd) || pPager->tempFile );
39408     if( isOpen(pPager->fd) ){
39409       int rc = sqlite3OsFileSize(pPager->fd, &n);
39410       if( rc!=SQLITE_OK ){
39411         return rc;
39412       }
39413     }
39414     nPage = (Pgno)(n / pPager->pageSize);
39415     if( nPage==0 && n>0 ){
39416       nPage = 1;
39417     }
39418   }
39419
39420   /* If the current number of pages in the file is greater than the
39421   ** configured maximum pager number, increase the allowed limit so
39422   ** that the file can be read.
39423   */
39424   if( nPage>pPager->mxPgno ){
39425     pPager->mxPgno = (Pgno)nPage;
39426   }
39427
39428   *pnPage = nPage;
39429   return SQLITE_OK;
39430 }
39431
39432 #ifndef SQLITE_OMIT_WAL
39433 /*
39434 ** Check if the *-wal file that corresponds to the database opened by pPager
39435 ** exists if the database is not empy, or verify that the *-wal file does
39436 ** not exist (by deleting it) if the database file is empty.
39437 **
39438 ** If the database is not empty and the *-wal file exists, open the pager
39439 ** in WAL mode.  If the database is empty or if no *-wal file exists and
39440 ** if no error occurs, make sure Pager.journalMode is not set to
39441 ** PAGER_JOURNALMODE_WAL.
39442 **
39443 ** Return SQLITE_OK or an error code.
39444 **
39445 ** The caller must hold a SHARED lock on the database file to call this
39446 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
39447 ** a WAL on a none-empty database, this ensures there is no race condition 
39448 ** between the xAccess() below and an xDelete() being executed by some 
39449 ** other connection.
39450 */
39451 static int pagerOpenWalIfPresent(Pager *pPager){
39452   int rc = SQLITE_OK;
39453   assert( pPager->eState==PAGER_OPEN );
39454   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39455
39456   if( !pPager->tempFile ){
39457     int isWal;                    /* True if WAL file exists */
39458     Pgno nPage;                   /* Size of the database file */
39459
39460     rc = pagerPagecount(pPager, &nPage);
39461     if( rc ) return rc;
39462     if( nPage==0 ){
39463       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39464       isWal = 0;
39465     }else{
39466       rc = sqlite3OsAccess(
39467           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39468       );
39469     }
39470     if( rc==SQLITE_OK ){
39471       if( isWal ){
39472         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39473         rc = sqlite3PagerOpenWal(pPager, 0);
39474       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39475         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39476       }
39477     }
39478   }
39479   return rc;
39480 }
39481 #endif
39482
39483 /*
39484 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39485 ** the entire master journal file. The case pSavepoint==NULL occurs when 
39486 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
39487 ** savepoint.
39488 **
39489 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
39490 ** being rolled back), then the rollback consists of up to three stages,
39491 ** performed in the order specified:
39492 **
39493 **   * Pages are played back from the main journal starting at byte
39494 **     offset PagerSavepoint.iOffset and continuing to 
39495 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
39496 **     file if PagerSavepoint.iHdrOffset is zero.
39497 **
39498 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39499 **     back starting from the journal header immediately following 
39500 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
39501 **
39502 **   * Pages are then played back from the sub-journal file, starting
39503 **     with the PagerSavepoint.iSubRec and continuing to the end of
39504 **     the journal file.
39505 **
39506 ** Throughout the rollback process, each time a page is rolled back, the
39507 ** corresponding bit is set in a bitvec structure (variable pDone in the
39508 ** implementation below). This is used to ensure that a page is only
39509 ** rolled back the first time it is encountered in either journal.
39510 **
39511 ** If pSavepoint is NULL, then pages are only played back from the main
39512 ** journal file. There is no need for a bitvec in this case.
39513 **
39514 ** In either case, before playback commences the Pager.dbSize variable
39515 ** is reset to the value that it held at the start of the savepoint 
39516 ** (or transaction). No page with a page-number greater than this value
39517 ** is played back. If one is encountered it is simply skipped.
39518 */
39519 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39520   i64 szJ;                 /* Effective size of the main journal */
39521   i64 iHdrOff;             /* End of first segment of main-journal records */
39522   int rc = SQLITE_OK;      /* Return code */
39523   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
39524
39525   assert( pPager->eState!=PAGER_ERROR );
39526   assert( pPager->eState>=PAGER_WRITER_LOCKED );
39527
39528   /* Allocate a bitvec to use to store the set of pages rolled back */
39529   if( pSavepoint ){
39530     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39531     if( !pDone ){
39532       return SQLITE_NOMEM;
39533     }
39534   }
39535
39536   /* Set the database size back to the value it was before the savepoint 
39537   ** being reverted was opened.
39538   */
39539   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39540   pPager->changeCountDone = pPager->tempFile;
39541
39542   if( !pSavepoint && pagerUseWal(pPager) ){
39543     return pagerRollbackWal(pPager);
39544   }
39545
39546   /* Use pPager->journalOff as the effective size of the main rollback
39547   ** journal.  The actual file might be larger than this in
39548   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
39549   ** past pPager->journalOff is off-limits to us.
39550   */
39551   szJ = pPager->journalOff;
39552   assert( pagerUseWal(pPager)==0 || szJ==0 );
39553
39554   /* Begin by rolling back records from the main journal starting at
39555   ** PagerSavepoint.iOffset and continuing to the next journal header.
39556   ** There might be records in the main journal that have a page number
39557   ** greater than the current database size (pPager->dbSize) but those
39558   ** will be skipped automatically.  Pages are added to pDone as they
39559   ** are played back.
39560   */
39561   if( pSavepoint && !pagerUseWal(pPager) ){
39562     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
39563     pPager->journalOff = pSavepoint->iOffset;
39564     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
39565       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39566     }
39567     assert( rc!=SQLITE_DONE );
39568   }else{
39569     pPager->journalOff = 0;
39570   }
39571
39572   /* Continue rolling back records out of the main journal starting at
39573   ** the first journal header seen and continuing until the effective end
39574   ** of the main journal file.  Continue to skip out-of-range pages and
39575   ** continue adding pages rolled back to pDone.
39576   */
39577   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
39578     u32 ii;            /* Loop counter */
39579     u32 nJRec = 0;     /* Number of Journal Records */
39580     u32 dummy;
39581     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
39582     assert( rc!=SQLITE_DONE );
39583
39584     /*
39585     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
39586     ** test is related to ticket #2565.  See the discussion in the
39587     ** pager_playback() function for additional information.
39588     */
39589     if( nJRec==0 
39590      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
39591     ){
39592       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
39593     }
39594     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
39595       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39596     }
39597     assert( rc!=SQLITE_DONE );
39598   }
39599   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
39600
39601   /* Finally,  rollback pages from the sub-journal.  Page that were
39602   ** previously rolled back out of the main journal (and are hence in pDone)
39603   ** will be skipped.  Out-of-range pages are also skipped.
39604   */
39605   if( pSavepoint ){
39606     u32 ii;            /* Loop counter */
39607     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
39608
39609     if( pagerUseWal(pPager) ){
39610       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
39611     }
39612     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
39613       assert( offset==ii*(4+pPager->pageSize) );
39614       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
39615     }
39616     assert( rc!=SQLITE_DONE );
39617   }
39618
39619   sqlite3BitvecDestroy(pDone);
39620   if( rc==SQLITE_OK ){
39621     pPager->journalOff = szJ;
39622   }
39623
39624   return rc;
39625 }
39626
39627 /*
39628 ** Change the maximum number of in-memory pages that are allowed.
39629 */
39630 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
39631   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
39632 }
39633
39634 /*
39635 ** Adjust the robustness of the database to damage due to OS crashes
39636 ** or power failures by changing the number of syncs()s when writing
39637 ** the rollback journal.  There are three levels:
39638 **
39639 **    OFF       sqlite3OsSync() is never called.  This is the default
39640 **              for temporary and transient files.
39641 **
39642 **    NORMAL    The journal is synced once before writes begin on the
39643 **              database.  This is normally adequate protection, but
39644 **              it is theoretically possible, though very unlikely,
39645 **              that an inopertune power failure could leave the journal
39646 **              in a state which would cause damage to the database
39647 **              when it is rolled back.
39648 **
39649 **    FULL      The journal is synced twice before writes begin on the
39650 **              database (with some additional information - the nRec field
39651 **              of the journal header - being written in between the two
39652 **              syncs).  If we assume that writing a
39653 **              single disk sector is atomic, then this mode provides
39654 **              assurance that the journal will not be corrupted to the
39655 **              point of causing damage to the database during rollback.
39656 **
39657 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
39658 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
39659 ** prior to the start of checkpoint and that the database file is synced
39660 ** at the conclusion of the checkpoint if the entire content of the WAL
39661 ** was written back into the database.  But no sync operations occur for
39662 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
39663 ** file is synced following each commit operation, in addition to the
39664 ** syncs associated with NORMAL.
39665 **
39666 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
39667 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
39668 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
39669 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
39670 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
39671 ** synchronous=FULL versus synchronous=NORMAL setting determines when
39672 ** the xSync primitive is called and is relevant to all platforms.
39673 **
39674 ** Numeric values associated with these states are OFF==1, NORMAL=2,
39675 ** and FULL=3.
39676 */
39677 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39678 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
39679   Pager *pPager,        /* The pager to set safety level for */
39680   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
39681   int bFullFsync,       /* PRAGMA fullfsync */
39682   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
39683 ){
39684   assert( level>=1 && level<=3 );
39685   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
39686   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
39687   if( pPager->noSync ){
39688     pPager->syncFlags = 0;
39689     pPager->ckptSyncFlags = 0;
39690   }else if( bFullFsync ){
39691     pPager->syncFlags = SQLITE_SYNC_FULL;
39692     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39693   }else if( bCkptFullFsync ){
39694     pPager->syncFlags = SQLITE_SYNC_NORMAL;
39695     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39696   }else{
39697     pPager->syncFlags = SQLITE_SYNC_NORMAL;
39698     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
39699   }
39700 }
39701 #endif
39702
39703 /*
39704 ** The following global variable is incremented whenever the library
39705 ** attempts to open a temporary file.  This information is used for
39706 ** testing and analysis only.  
39707 */
39708 #ifdef SQLITE_TEST
39709 SQLITE_API int sqlite3_opentemp_count = 0;
39710 #endif
39711
39712 /*
39713 ** Open a temporary file.
39714 **
39715 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
39716 ** or some other error code if we fail. The OS will automatically 
39717 ** delete the temporary file when it is closed.
39718 **
39719 ** The flags passed to the VFS layer xOpen() call are those specified
39720 ** by parameter vfsFlags ORed with the following:
39721 **
39722 **     SQLITE_OPEN_READWRITE
39723 **     SQLITE_OPEN_CREATE
39724 **     SQLITE_OPEN_EXCLUSIVE
39725 **     SQLITE_OPEN_DELETEONCLOSE
39726 */
39727 static int pagerOpentemp(
39728   Pager *pPager,        /* The pager object */
39729   sqlite3_file *pFile,  /* Write the file descriptor here */
39730   int vfsFlags          /* Flags passed through to the VFS */
39731 ){
39732   int rc;               /* Return code */
39733
39734 #ifdef SQLITE_TEST
39735   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
39736 #endif
39737
39738   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
39739             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
39740   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
39741   assert( rc!=SQLITE_OK || isOpen(pFile) );
39742   return rc;
39743 }
39744
39745 /*
39746 ** Set the busy handler function.
39747 **
39748 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
39749 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
39750 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
39751 ** lock. It does *not* invoke the busy handler when upgrading from
39752 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
39753 ** (which occurs during hot-journal rollback). Summary:
39754 **
39755 **   Transition                        | Invokes xBusyHandler
39756 **   --------------------------------------------------------
39757 **   NO_LOCK       -> SHARED_LOCK      | Yes
39758 **   SHARED_LOCK   -> RESERVED_LOCK    | No
39759 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
39760 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
39761 **
39762 ** If the busy-handler callback returns non-zero, the lock is 
39763 ** retried. If it returns zero, then the SQLITE_BUSY error is
39764 ** returned to the caller of the pager API function.
39765 */
39766 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
39767   Pager *pPager,                       /* Pager object */
39768   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
39769   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
39770 ){  
39771   pPager->xBusyHandler = xBusyHandler;
39772   pPager->pBusyHandlerArg = pBusyHandlerArg;
39773 }
39774
39775 /*
39776 ** Change the page size used by the Pager object. The new page size 
39777 ** is passed in *pPageSize.
39778 **
39779 ** If the pager is in the error state when this function is called, it
39780 ** is a no-op. The value returned is the error state error code (i.e. 
39781 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
39782 **
39783 ** Otherwise, if all of the following are true:
39784 **
39785 **   * the new page size (value of *pPageSize) is valid (a power 
39786 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
39787 **
39788 **   * there are no outstanding page references, and
39789 **
39790 **   * the database is either not an in-memory database or it is
39791 **     an in-memory database that currently consists of zero pages.
39792 **
39793 ** then the pager object page size is set to *pPageSize.
39794 **
39795 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
39796 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
39797 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
39798 ** In all other cases, SQLITE_OK is returned.
39799 **
39800 ** If the page size is not changed, either because one of the enumerated
39801 ** conditions above is not true, the pager was in error state when this
39802 ** function was called, or because the memory allocation attempt failed, 
39803 ** then *pPageSize is set to the old, retained page size before returning.
39804 */
39805 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
39806   int rc = SQLITE_OK;
39807
39808   /* It is not possible to do a full assert_pager_state() here, as this
39809   ** function may be called from within PagerOpen(), before the state
39810   ** of the Pager object is internally consistent.
39811   **
39812   ** At one point this function returned an error if the pager was in 
39813   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
39814   ** there is at least one outstanding page reference, this function
39815   ** is a no-op for that case anyhow.
39816   */
39817
39818   u32 pageSize = *pPageSize;
39819   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
39820   if( (pPager->memDb==0 || pPager->dbSize==0)
39821    && sqlite3PcacheRefCount(pPager->pPCache)==0 
39822    && pageSize && pageSize!=(u32)pPager->pageSize 
39823   ){
39824     char *pNew = NULL;             /* New temp space */
39825     i64 nByte = 0;
39826
39827     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
39828       rc = sqlite3OsFileSize(pPager->fd, &nByte);
39829     }
39830     if( rc==SQLITE_OK ){
39831       pNew = (char *)sqlite3PageMalloc(pageSize);
39832       if( !pNew ) rc = SQLITE_NOMEM;
39833     }
39834
39835     if( rc==SQLITE_OK ){
39836       pager_reset(pPager);
39837       pPager->dbSize = (Pgno)(nByte/pageSize);
39838       pPager->pageSize = pageSize;
39839       sqlite3PageFree(pPager->pTmpSpace);
39840       pPager->pTmpSpace = pNew;
39841       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
39842     }
39843   }
39844
39845   *pPageSize = pPager->pageSize;
39846   if( rc==SQLITE_OK ){
39847     if( nReserve<0 ) nReserve = pPager->nReserve;
39848     assert( nReserve>=0 && nReserve<1000 );
39849     pPager->nReserve = (i16)nReserve;
39850     pagerReportSize(pPager);
39851   }
39852   return rc;
39853 }
39854
39855 /*
39856 ** Return a pointer to the "temporary page" buffer held internally
39857 ** by the pager.  This is a buffer that is big enough to hold the
39858 ** entire content of a database page.  This buffer is used internally
39859 ** during rollback and will be overwritten whenever a rollback
39860 ** occurs.  But other modules are free to use it too, as long as
39861 ** no rollbacks are happening.
39862 */
39863 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
39864   return pPager->pTmpSpace;
39865 }
39866
39867 /*
39868 ** Attempt to set the maximum database page count if mxPage is positive. 
39869 ** Make no changes if mxPage is zero or negative.  And never reduce the
39870 ** maximum page count below the current size of the database.
39871 **
39872 ** Regardless of mxPage, return the current maximum page count.
39873 */
39874 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
39875   if( mxPage>0 ){
39876     pPager->mxPgno = mxPage;
39877   }
39878   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
39879   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
39880   return pPager->mxPgno;
39881 }
39882
39883 /*
39884 ** The following set of routines are used to disable the simulated
39885 ** I/O error mechanism.  These routines are used to avoid simulated
39886 ** errors in places where we do not care about errors.
39887 **
39888 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
39889 ** and generate no code.
39890 */
39891 #ifdef SQLITE_TEST
39892 SQLITE_API extern int sqlite3_io_error_pending;
39893 SQLITE_API extern int sqlite3_io_error_hit;
39894 static int saved_cnt;
39895 void disable_simulated_io_errors(void){
39896   saved_cnt = sqlite3_io_error_pending;
39897   sqlite3_io_error_pending = -1;
39898 }
39899 void enable_simulated_io_errors(void){
39900   sqlite3_io_error_pending = saved_cnt;
39901 }
39902 #else
39903 # define disable_simulated_io_errors()
39904 # define enable_simulated_io_errors()
39905 #endif
39906
39907 /*
39908 ** Read the first N bytes from the beginning of the file into memory
39909 ** that pDest points to. 
39910 **
39911 ** If the pager was opened on a transient file (zFilename==""), or
39912 ** opened on a file less than N bytes in size, the output buffer is
39913 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
39914 ** function is used to read database headers, and a new transient or
39915 ** zero sized database has a header than consists entirely of zeroes.
39916 **
39917 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
39918 ** the error code is returned to the caller and the contents of the
39919 ** output buffer undefined.
39920 */
39921 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
39922   int rc = SQLITE_OK;
39923   memset(pDest, 0, N);
39924   assert( isOpen(pPager->fd) || pPager->tempFile );
39925
39926   /* This routine is only called by btree immediately after creating
39927   ** the Pager object.  There has not been an opportunity to transition
39928   ** to WAL mode yet.
39929   */
39930   assert( !pagerUseWal(pPager) );
39931
39932   if( isOpen(pPager->fd) ){
39933     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
39934     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
39935     if( rc==SQLITE_IOERR_SHORT_READ ){
39936       rc = SQLITE_OK;
39937     }
39938   }
39939   return rc;
39940 }
39941
39942 /*
39943 ** This function may only be called when a read-transaction is open on
39944 ** the pager. It returns the total number of pages in the database.
39945 **
39946 ** However, if the file is between 1 and <page-size> bytes in size, then 
39947 ** this is considered a 1 page file.
39948 */
39949 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
39950   assert( pPager->eState>=PAGER_READER );
39951   assert( pPager->eState!=PAGER_WRITER_FINISHED );
39952   *pnPage = (int)pPager->dbSize;
39953 }
39954
39955
39956 /*
39957 ** Try to obtain a lock of type locktype on the database file. If
39958 ** a similar or greater lock is already held, this function is a no-op
39959 ** (returning SQLITE_OK immediately).
39960 **
39961 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
39962 ** the busy callback if the lock is currently not available. Repeat 
39963 ** until the busy callback returns false or until the attempt to 
39964 ** obtain the lock succeeds.
39965 **
39966 ** Return SQLITE_OK on success and an error code if we cannot obtain
39967 ** the lock. If the lock is obtained successfully, set the Pager.state 
39968 ** variable to locktype before returning.
39969 */
39970 static int pager_wait_on_lock(Pager *pPager, int locktype){
39971   int rc;                              /* Return code */
39972
39973   /* Check that this is either a no-op (because the requested lock is 
39974   ** already held, or one of the transistions that the busy-handler
39975   ** may be invoked during, according to the comment above
39976   ** sqlite3PagerSetBusyhandler().
39977   */
39978   assert( (pPager->eLock>=locktype)
39979        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
39980        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
39981   );
39982
39983   do {
39984     rc = pagerLockDb(pPager, locktype);
39985   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
39986   return rc;
39987 }
39988
39989 /*
39990 ** Function assertTruncateConstraint(pPager) checks that one of the 
39991 ** following is true for all dirty pages currently in the page-cache:
39992 **
39993 **   a) The page number is less than or equal to the size of the 
39994 **      current database image, in pages, OR
39995 **
39996 **   b) if the page content were written at this time, it would not
39997 **      be necessary to write the current content out to the sub-journal
39998 **      (as determined by function subjRequiresPage()).
39999 **
40000 ** If the condition asserted by this function were not true, and the
40001 ** dirty page were to be discarded from the cache via the pagerStress()
40002 ** routine, pagerStress() would not write the current page content to
40003 ** the database file. If a savepoint transaction were rolled back after
40004 ** this happened, the correct behaviour would be to restore the current
40005 ** content of the page. However, since this content is not present in either
40006 ** the database file or the portion of the rollback journal and 
40007 ** sub-journal rolled back the content could not be restored and the
40008 ** database image would become corrupt. It is therefore fortunate that 
40009 ** this circumstance cannot arise.
40010 */
40011 #if defined(SQLITE_DEBUG)
40012 static void assertTruncateConstraintCb(PgHdr *pPg){
40013   assert( pPg->flags&PGHDR_DIRTY );
40014   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40015 }
40016 static void assertTruncateConstraint(Pager *pPager){
40017   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40018 }
40019 #else
40020 # define assertTruncateConstraint(pPager)
40021 #endif
40022
40023 /*
40024 ** Truncate the in-memory database file image to nPage pages. This 
40025 ** function does not actually modify the database file on disk. It 
40026 ** just sets the internal state of the pager object so that the 
40027 ** truncation will be done when the current transaction is committed.
40028 */
40029 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40030   assert( pPager->dbSize>=nPage );
40031   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40032   pPager->dbSize = nPage;
40033   assertTruncateConstraint(pPager);
40034 }
40035
40036
40037 /*
40038 ** This function is called before attempting a hot-journal rollback. It
40039 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40040 ** size of the journal file so that the pager_playback() routine knows
40041 ** that the entire journal file has been synced.
40042 **
40043 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
40044 ** that if a power-failure occurs during the rollback, the process that
40045 ** attempts rollback following system recovery sees the same journal
40046 ** content as this process.
40047 **
40048 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
40049 ** an SQLite error code.
40050 */
40051 static int pagerSyncHotJournal(Pager *pPager){
40052   int rc = SQLITE_OK;
40053   if( !pPager->noSync ){
40054     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40055   }
40056   if( rc==SQLITE_OK ){
40057     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40058   }
40059   return rc;
40060 }
40061
40062 /*
40063 ** Shutdown the page cache.  Free all memory and close all files.
40064 **
40065 ** If a transaction was in progress when this routine is called, that
40066 ** transaction is rolled back.  All outstanding pages are invalidated
40067 ** and their memory is freed.  Any attempt to use a page associated
40068 ** with this page cache after this function returns will likely
40069 ** result in a coredump.
40070 **
40071 ** This function always succeeds. If a transaction is active an attempt
40072 ** is made to roll it back. If an error occurs during the rollback 
40073 ** a hot journal may be left in the filesystem but no error is returned
40074 ** to the caller.
40075 */
40076 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40077   u8 *pTmp = (u8 *)pPager->pTmpSpace;
40078
40079   disable_simulated_io_errors();
40080   sqlite3BeginBenignMalloc();
40081   /* pPager->errCode = 0; */
40082   pPager->exclusiveMode = 0;
40083 #ifndef SQLITE_OMIT_WAL
40084   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40085   pPager->pWal = 0;
40086 #endif
40087   pager_reset(pPager);
40088   if( MEMDB ){
40089     pager_unlock(pPager);
40090   }else{
40091     /* If it is open, sync the journal file before calling UnlockAndRollback.
40092     ** If this is not done, then an unsynced portion of the open journal 
40093     ** file may be played back into the database. If a power failure occurs 
40094     ** while this is happening, the database could become corrupt.
40095     **
40096     ** If an error occurs while trying to sync the journal, shift the pager
40097     ** into the ERROR state. This causes UnlockAndRollback to unlock the
40098     ** database and close the journal file without attempting to roll it
40099     ** back or finalize it. The next database user will have to do hot-journal
40100     ** rollback before accessing the database file.
40101     */
40102     if( isOpen(pPager->jfd) ){
40103       pager_error(pPager, pagerSyncHotJournal(pPager));
40104     }
40105     pagerUnlockAndRollback(pPager);
40106   }
40107   sqlite3EndBenignMalloc();
40108   enable_simulated_io_errors();
40109   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40110   IOTRACE(("CLOSE %p\n", pPager))
40111   sqlite3OsClose(pPager->jfd);
40112   sqlite3OsClose(pPager->fd);
40113   sqlite3PageFree(pTmp);
40114   sqlite3PcacheClose(pPager->pPCache);
40115
40116 #ifdef SQLITE_HAS_CODEC
40117   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40118 #endif
40119
40120   assert( !pPager->aSavepoint && !pPager->pInJournal );
40121   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40122
40123   sqlite3_free(pPager);
40124   return SQLITE_OK;
40125 }
40126
40127 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40128 /*
40129 ** Return the page number for page pPg.
40130 */
40131 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40132   return pPg->pgno;
40133 }
40134 #endif
40135
40136 /*
40137 ** Increment the reference count for page pPg.
40138 */
40139 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40140   sqlite3PcacheRef(pPg);
40141 }
40142
40143 /*
40144 ** Sync the journal. In other words, make sure all the pages that have
40145 ** been written to the journal have actually reached the surface of the
40146 ** disk and can be restored in the event of a hot-journal rollback.
40147 **
40148 ** If the Pager.noSync flag is set, then this function is a no-op.
40149 ** Otherwise, the actions required depend on the journal-mode and the 
40150 ** device characteristics of the the file-system, as follows:
40151 **
40152 **   * If the journal file is an in-memory journal file, no action need
40153 **     be taken.
40154 **
40155 **   * Otherwise, if the device does not support the SAFE_APPEND property,
40156 **     then the nRec field of the most recently written journal header
40157 **     is updated to contain the number of journal records that have
40158 **     been written following it. If the pager is operating in full-sync
40159 **     mode, then the journal file is synced before this field is updated.
40160 **
40161 **   * If the device does not support the SEQUENTIAL property, then 
40162 **     journal file is synced.
40163 **
40164 ** Or, in pseudo-code:
40165 **
40166 **   if( NOT <in-memory journal> ){
40167 **     if( NOT SAFE_APPEND ){
40168 **       if( <full-sync mode> ) xSync(<journal file>);
40169 **       <update nRec field>
40170 **     } 
40171 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
40172 **   }
40173 **
40174 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
40175 ** page currently held in memory before returning SQLITE_OK. If an IO
40176 ** error is encountered, then the IO error code is returned to the caller.
40177 */
40178 static int syncJournal(Pager *pPager, int newHdr){
40179   int rc;                         /* Return code */
40180
40181   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40182        || pPager->eState==PAGER_WRITER_DBMOD
40183   );
40184   assert( assert_pager_state(pPager) );
40185   assert( !pagerUseWal(pPager) );
40186
40187   rc = sqlite3PagerExclusiveLock(pPager);
40188   if( rc!=SQLITE_OK ) return rc;
40189
40190   if( !pPager->noSync ){
40191     assert( !pPager->tempFile );
40192     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40193       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40194       assert( isOpen(pPager->jfd) );
40195
40196       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40197         /* This block deals with an obscure problem. If the last connection
40198         ** that wrote to this database was operating in persistent-journal
40199         ** mode, then the journal file may at this point actually be larger
40200         ** than Pager.journalOff bytes. If the next thing in the journal
40201         ** file happens to be a journal-header (written as part of the
40202         ** previous connection's transaction), and a crash or power-failure 
40203         ** occurs after nRec is updated but before this connection writes 
40204         ** anything else to the journal file (or commits/rolls back its 
40205         ** transaction), then SQLite may become confused when doing the 
40206         ** hot-journal rollback following recovery. It may roll back all
40207         ** of this connections data, then proceed to rolling back the old,
40208         ** out-of-date data that follows it. Database corruption.
40209         **
40210         ** To work around this, if the journal file does appear to contain
40211         ** a valid header following Pager.journalOff, then write a 0x00
40212         ** byte to the start of it to prevent it from being recognized.
40213         **
40214         ** Variable iNextHdrOffset is set to the offset at which this
40215         ** problematic header will occur, if it exists. aMagic is used 
40216         ** as a temporary buffer to inspect the first couple of bytes of
40217         ** the potential journal header.
40218         */
40219         i64 iNextHdrOffset;
40220         u8 aMagic[8];
40221         u8 zHeader[sizeof(aJournalMagic)+4];
40222
40223         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40224         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40225
40226         iNextHdrOffset = journalHdrOffset(pPager);
40227         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40228         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40229           static const u8 zerobyte = 0;
40230           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40231         }
40232         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40233           return rc;
40234         }
40235
40236         /* Write the nRec value into the journal file header. If in
40237         ** full-synchronous mode, sync the journal first. This ensures that
40238         ** all data has really hit the disk before nRec is updated to mark
40239         ** it as a candidate for rollback.
40240         **
40241         ** This is not required if the persistent media supports the
40242         ** SAFE_APPEND property. Because in this case it is not possible 
40243         ** for garbage data to be appended to the file, the nRec field
40244         ** is populated with 0xFFFFFFFF when the journal header is written
40245         ** and never needs to be updated.
40246         */
40247         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40248           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40249           IOTRACE(("JSYNC %p\n", pPager))
40250           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40251           if( rc!=SQLITE_OK ) return rc;
40252         }
40253         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40254         rc = sqlite3OsWrite(
40255             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40256         );
40257         if( rc!=SQLITE_OK ) return rc;
40258       }
40259       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40260         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40261         IOTRACE(("JSYNC %p\n", pPager))
40262         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
40263           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40264         );
40265         if( rc!=SQLITE_OK ) return rc;
40266       }
40267
40268       pPager->journalHdr = pPager->journalOff;
40269       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40270         pPager->nRec = 0;
40271         rc = writeJournalHdr(pPager);
40272         if( rc!=SQLITE_OK ) return rc;
40273       }
40274     }else{
40275       pPager->journalHdr = pPager->journalOff;
40276     }
40277   }
40278
40279   /* Unless the pager is in noSync mode, the journal file was just 
40280   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
40281   ** all pages.
40282   */
40283   sqlite3PcacheClearSyncFlags(pPager->pPCache);
40284   pPager->eState = PAGER_WRITER_DBMOD;
40285   assert( assert_pager_state(pPager) );
40286   return SQLITE_OK;
40287 }
40288
40289 /*
40290 ** The argument is the first in a linked list of dirty pages connected
40291 ** by the PgHdr.pDirty pointer. This function writes each one of the
40292 ** in-memory pages in the list to the database file. The argument may
40293 ** be NULL, representing an empty list. In this case this function is
40294 ** a no-op.
40295 **
40296 ** The pager must hold at least a RESERVED lock when this function
40297 ** is called. Before writing anything to the database file, this lock
40298 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40299 ** SQLITE_BUSY is returned and no data is written to the database file.
40300 ** 
40301 ** If the pager is a temp-file pager and the actual file-system file
40302 ** is not yet open, it is created and opened before any data is 
40303 ** written out.
40304 **
40305 ** Once the lock has been upgraded and, if necessary, the file opened,
40306 ** the pages are written out to the database file in list order. Writing
40307 ** a page is skipped if it meets either of the following criteria:
40308 **
40309 **   * The page number is greater than Pager.dbSize, or
40310 **   * The PGHDR_DONT_WRITE flag is set on the page.
40311 **
40312 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40313 ** is updated accordingly. If page 1 is written out, then the value cached
40314 ** in Pager.dbFileVers[] is updated to match the new value stored in
40315 ** the database file.
40316 **
40317 ** If everything is successful, SQLITE_OK is returned. If an IO error 
40318 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40319 ** be obtained, SQLITE_BUSY is returned.
40320 */
40321 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40322   int rc = SQLITE_OK;                  /* Return code */
40323
40324   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40325   assert( !pagerUseWal(pPager) );
40326   assert( pPager->eState==PAGER_WRITER_DBMOD );
40327   assert( pPager->eLock==EXCLUSIVE_LOCK );
40328
40329   /* If the file is a temp-file has not yet been opened, open it now. It
40330   ** is not possible for rc to be other than SQLITE_OK if this branch
40331   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40332   */
40333   if( !isOpen(pPager->fd) ){
40334     assert( pPager->tempFile && rc==SQLITE_OK );
40335     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40336   }
40337
40338   /* Before the first write, give the VFS a hint of what the final
40339   ** file size will be.
40340   */
40341   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40342   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40343     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40344     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40345     pPager->dbHintSize = pPager->dbSize;
40346   }
40347
40348   while( rc==SQLITE_OK && pList ){
40349     Pgno pgno = pList->pgno;
40350
40351     /* If there are dirty pages in the page cache with page numbers greater
40352     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40353     ** make the file smaller (presumably by auto-vacuum code). Do not write
40354     ** any such pages to the file.
40355     **
40356     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40357     ** set (set by sqlite3PagerDontWrite()).
40358     */
40359     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40360       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
40361       char *pData;                                   /* Data to write */    
40362
40363       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40364       if( pList->pgno==1 ) pager_write_changecounter(pList);
40365
40366       /* Encode the database */
40367       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40368
40369       /* Write out the page data. */
40370       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40371
40372       /* If page 1 was just written, update Pager.dbFileVers to match
40373       ** the value now stored in the database file. If writing this 
40374       ** page caused the database file to grow, update dbFileSize. 
40375       */
40376       if( pgno==1 ){
40377         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40378       }
40379       if( pgno>pPager->dbFileSize ){
40380         pPager->dbFileSize = pgno;
40381       }
40382
40383       /* Update any backup objects copying the contents of this pager. */
40384       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40385
40386       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40387                    PAGERID(pPager), pgno, pager_pagehash(pList)));
40388       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40389       PAGER_INCR(sqlite3_pager_writedb_count);
40390       PAGER_INCR(pPager->nWrite);
40391     }else{
40392       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40393     }
40394     pager_set_pagehash(pList);
40395     pList = pList->pDirty;
40396   }
40397
40398   return rc;
40399 }
40400
40401 /*
40402 ** Ensure that the sub-journal file is open. If it is already open, this 
40403 ** function is a no-op.
40404 **
40405 ** SQLITE_OK is returned if everything goes according to plan. An 
40406 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
40407 ** fails.
40408 */
40409 static int openSubJournal(Pager *pPager){
40410   int rc = SQLITE_OK;
40411   if( !isOpen(pPager->sjfd) ){
40412     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40413       sqlite3MemJournalOpen(pPager->sjfd);
40414     }else{
40415       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40416     }
40417   }
40418   return rc;
40419 }
40420
40421 /*
40422 ** Append a record of the current state of page pPg to the sub-journal. 
40423 ** It is the callers responsibility to use subjRequiresPage() to check 
40424 ** that it is really required before calling this function.
40425 **
40426 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40427 ** for all open savepoints before returning.
40428 **
40429 ** This function returns SQLITE_OK if everything is successful, an IO
40430 ** error code if the attempt to write to the sub-journal fails, or 
40431 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40432 ** bitvec.
40433 */
40434 static int subjournalPage(PgHdr *pPg){
40435   int rc = SQLITE_OK;
40436   Pager *pPager = pPg->pPager;
40437   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40438
40439     /* Open the sub-journal, if it has not already been opened */
40440     assert( pPager->useJournal );
40441     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40442     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40443     assert( pagerUseWal(pPager) 
40444          || pageInJournal(pPg) 
40445          || pPg->pgno>pPager->dbOrigSize 
40446     );
40447     rc = openSubJournal(pPager);
40448
40449     /* If the sub-journal was opened successfully (or was already open),
40450     ** write the journal record into the file.  */
40451     if( rc==SQLITE_OK ){
40452       void *pData = pPg->pData;
40453       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40454       char *pData2;
40455   
40456       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40457       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40458       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40459       if( rc==SQLITE_OK ){
40460         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40461       }
40462     }
40463   }
40464   if( rc==SQLITE_OK ){
40465     pPager->nSubRec++;
40466     assert( pPager->nSavepoint>0 );
40467     rc = addToSavepointBitvecs(pPager, pPg->pgno);
40468   }
40469   return rc;
40470 }
40471
40472 /*
40473 ** This function is called by the pcache layer when it has reached some
40474 ** soft memory limit. The first argument is a pointer to a Pager object
40475 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40476 ** database). The second argument is a reference to a page that is 
40477 ** currently dirty but has no outstanding references. The page
40478 ** is always associated with the Pager object passed as the first 
40479 ** argument.
40480 **
40481 ** The job of this function is to make pPg clean by writing its contents
40482 ** out to the database file, if possible. This may involve syncing the
40483 ** journal file. 
40484 **
40485 ** If successful, sqlite3PcacheMakeClean() is called on the page and
40486 ** SQLITE_OK returned. If an IO error occurs while trying to make the
40487 ** page clean, the IO error code is returned. If the page cannot be
40488 ** made clean for some other reason, but no error occurs, then SQLITE_OK
40489 ** is returned by sqlite3PcacheMakeClean() is not called.
40490 */
40491 static int pagerStress(void *p, PgHdr *pPg){
40492   Pager *pPager = (Pager *)p;
40493   int rc = SQLITE_OK;
40494
40495   assert( pPg->pPager==pPager );
40496   assert( pPg->flags&PGHDR_DIRTY );
40497
40498   /* The doNotSyncSpill flag is set during times when doing a sync of
40499   ** journal (and adding a new header) is not allowed.  This occurs
40500   ** during calls to sqlite3PagerWrite() while trying to journal multiple
40501   ** pages belonging to the same sector.
40502   **
40503   ** The doNotSpill flag inhibits all cache spilling regardless of whether
40504   ** or not a sync is required.  This is set during a rollback.
40505   **
40506   ** Spilling is also prohibited when in an error state since that could
40507   ** lead to database corruption.   In the current implementaton it 
40508   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40509   ** while in the error state, hence it is impossible for this routine to
40510   ** be called in the error state.  Nevertheless, we include a NEVER()
40511   ** test for the error state as a safeguard against future changes.
40512   */
40513   if( NEVER(pPager->errCode) ) return SQLITE_OK;
40514   if( pPager->doNotSpill ) return SQLITE_OK;
40515   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40516     return SQLITE_OK;
40517   }
40518
40519   pPg->pDirty = 0;
40520   if( pagerUseWal(pPager) ){
40521     /* Write a single frame for this page to the log. */
40522     if( subjRequiresPage(pPg) ){ 
40523       rc = subjournalPage(pPg); 
40524     }
40525     if( rc==SQLITE_OK ){
40526       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40527     }
40528   }else{
40529   
40530     /* Sync the journal file if required. */
40531     if( pPg->flags&PGHDR_NEED_SYNC 
40532      || pPager->eState==PAGER_WRITER_CACHEMOD
40533     ){
40534       rc = syncJournal(pPager, 1);
40535     }
40536   
40537     /* If the page number of this page is larger than the current size of
40538     ** the database image, it may need to be written to the sub-journal.
40539     ** This is because the call to pager_write_pagelist() below will not
40540     ** actually write data to the file in this case.
40541     **
40542     ** Consider the following sequence of events:
40543     **
40544     **   BEGIN;
40545     **     <journal page X>
40546     **     <modify page X>
40547     **     SAVEPOINT sp;
40548     **       <shrink database file to Y pages>
40549     **       pagerStress(page X)
40550     **     ROLLBACK TO sp;
40551     **
40552     ** If (X>Y), then when pagerStress is called page X will not be written
40553     ** out to the database file, but will be dropped from the cache. Then,
40554     ** following the "ROLLBACK TO sp" statement, reading page X will read
40555     ** data from the database file. This will be the copy of page X as it
40556     ** was when the transaction started, not as it was when "SAVEPOINT sp"
40557     ** was executed.
40558     **
40559     ** The solution is to write the current data for page X into the 
40560     ** sub-journal file now (if it is not already there), so that it will
40561     ** be restored to its current value when the "ROLLBACK TO sp" is 
40562     ** executed.
40563     */
40564     if( NEVER(
40565         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
40566     ) ){
40567       rc = subjournalPage(pPg);
40568     }
40569   
40570     /* Write the contents of the page out to the database file. */
40571     if( rc==SQLITE_OK ){
40572       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
40573       rc = pager_write_pagelist(pPager, pPg);
40574     }
40575   }
40576
40577   /* Mark the page as clean. */
40578   if( rc==SQLITE_OK ){
40579     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
40580     sqlite3PcacheMakeClean(pPg);
40581   }
40582
40583   return pager_error(pPager, rc); 
40584 }
40585
40586
40587 /*
40588 ** Allocate and initialize a new Pager object and put a pointer to it
40589 ** in *ppPager. The pager should eventually be freed by passing it
40590 ** to sqlite3PagerClose().
40591 **
40592 ** The zFilename argument is the path to the database file to open.
40593 ** If zFilename is NULL then a randomly-named temporary file is created
40594 ** and used as the file to be cached. Temporary files are be deleted
40595 ** automatically when they are closed. If zFilename is ":memory:" then 
40596 ** all information is held in cache. It is never written to disk. 
40597 ** This can be used to implement an in-memory database.
40598 **
40599 ** The nExtra parameter specifies the number of bytes of space allocated
40600 ** along with each page reference. This space is available to the user
40601 ** via the sqlite3PagerGetExtra() API.
40602 **
40603 ** The flags argument is used to specify properties that affect the
40604 ** operation of the pager. It should be passed some bitwise combination
40605 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
40606 **
40607 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
40608 ** of the xOpen() method of the supplied VFS when opening files. 
40609 **
40610 ** If the pager object is allocated and the specified file opened 
40611 ** successfully, SQLITE_OK is returned and *ppPager set to point to
40612 ** the new pager object. If an error occurs, *ppPager is set to NULL
40613 ** and error code returned. This function may return SQLITE_NOMEM
40614 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
40615 ** various SQLITE_IO_XXX errors.
40616 */
40617 SQLITE_PRIVATE int sqlite3PagerOpen(
40618   sqlite3_vfs *pVfs,       /* The virtual file system to use */
40619   Pager **ppPager,         /* OUT: Return the Pager structure here */
40620   const char *zFilename,   /* Name of the database file to open */
40621   int nExtra,              /* Extra bytes append to each in-memory page */
40622   int flags,               /* flags controlling this file */
40623   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
40624   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
40625 ){
40626   u8 *pPtr;
40627   Pager *pPager = 0;       /* Pager object to allocate and return */
40628   int rc = SQLITE_OK;      /* Return code */
40629   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
40630   int memDb = 0;           /* True if this is an in-memory file */
40631   int readOnly = 0;        /* True if this is a read-only file */
40632   int journalFileSize;     /* Bytes to allocate for each journal fd */
40633   char *zPathname = 0;     /* Full path to database file */
40634   int nPathname = 0;       /* Number of bytes in zPathname */
40635   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
40636   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
40637   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
40638   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
40639
40640   /* Figure out how much space is required for each journal file-handle
40641   ** (there are two of them, the main journal and the sub-journal). This
40642   ** is the maximum space required for an in-memory journal file handle 
40643   ** and a regular journal file-handle. Note that a "regular journal-handle"
40644   ** may be a wrapper capable of caching the first portion of the journal
40645   ** file in memory to implement the atomic-write optimization (see 
40646   ** source file journal.c).
40647   */
40648   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
40649     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
40650   }else{
40651     journalFileSize = ROUND8(sqlite3MemJournalSize());
40652   }
40653
40654   /* Set the output variable to NULL in case an error occurs. */
40655   *ppPager = 0;
40656
40657 #ifndef SQLITE_OMIT_MEMORYDB
40658   if( flags & PAGER_MEMORY ){
40659     memDb = 1;
40660     zFilename = 0;
40661   }
40662 #endif
40663
40664   /* Compute and store the full pathname in an allocated buffer pointed
40665   ** to by zPathname, length nPathname. Or, if this is a temporary file,
40666   ** leave both nPathname and zPathname set to 0.
40667   */
40668   if( zFilename && zFilename[0] ){
40669     nPathname = pVfs->mxPathname+1;
40670     zPathname = sqlite3Malloc(nPathname*2);
40671     if( zPathname==0 ){
40672       return SQLITE_NOMEM;
40673     }
40674     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
40675     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
40676     nPathname = sqlite3Strlen30(zPathname);
40677     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
40678       /* This branch is taken when the journal path required by
40679       ** the database being opened will be more than pVfs->mxPathname
40680       ** bytes in length. This means the database cannot be opened,
40681       ** as it will not be possible to open the journal file or even
40682       ** check for a hot-journal before reading.
40683       */
40684       rc = SQLITE_CANTOPEN_BKPT;
40685     }
40686     if( rc!=SQLITE_OK ){
40687       sqlite3_free(zPathname);
40688       return rc;
40689     }
40690   }
40691
40692   /* Allocate memory for the Pager structure, PCache object, the
40693   ** three file descriptors, the database file name and the journal 
40694   ** file name. The layout in memory is as follows:
40695   **
40696   **     Pager object                    (sizeof(Pager) bytes)
40697   **     PCache object                   (sqlite3PcacheSize() bytes)
40698   **     Database file handle            (pVfs->szOsFile bytes)
40699   **     Sub-journal file handle         (journalFileSize bytes)
40700   **     Main journal file handle        (journalFileSize bytes)
40701   **     Database file name              (nPathname+1 bytes)
40702   **     Journal file name               (nPathname+8+1 bytes)
40703   */
40704   pPtr = (u8 *)sqlite3MallocZero(
40705     ROUND8(sizeof(*pPager)) +      /* Pager structure */
40706     ROUND8(pcacheSize) +           /* PCache object */
40707     ROUND8(pVfs->szOsFile) +       /* The main db file */
40708     journalFileSize * 2 +          /* The two journal files */ 
40709     nPathname + 1 +                /* zFilename */
40710     nPathname + 8 + 1              /* zJournal */
40711 #ifndef SQLITE_OMIT_WAL
40712     + nPathname + 4 + 1              /* zWal */
40713 #endif
40714   );
40715   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
40716   if( !pPtr ){
40717     sqlite3_free(zPathname);
40718     return SQLITE_NOMEM;
40719   }
40720   pPager =              (Pager*)(pPtr);
40721   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
40722   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
40723   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
40724   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
40725   pPager->zFilename =    (char*)(pPtr += journalFileSize);
40726   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
40727
40728   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
40729   if( zPathname ){
40730     assert( nPathname>0 );
40731     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
40732     memcpy(pPager->zFilename, zPathname, nPathname);
40733     memcpy(pPager->zJournal, zPathname, nPathname);
40734     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
40735 #ifndef SQLITE_OMIT_WAL
40736     pPager->zWal = &pPager->zJournal[nPathname+8+1];
40737     memcpy(pPager->zWal, zPathname, nPathname);
40738     memcpy(&pPager->zWal[nPathname], "-wal", 4);
40739 #endif
40740     sqlite3_free(zPathname);
40741   }
40742   pPager->pVfs = pVfs;
40743   pPager->vfsFlags = vfsFlags;
40744
40745   /* Open the pager file.
40746   */
40747   if( zFilename && zFilename[0] ){
40748     int fout = 0;                    /* VFS flags returned by xOpen() */
40749     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
40750     assert( !memDb );
40751     readOnly = (fout&SQLITE_OPEN_READONLY);
40752
40753     /* If the file was successfully opened for read/write access,
40754     ** choose a default page size in case we have to create the
40755     ** database file. The default page size is the maximum of:
40756     **
40757     **    + SQLITE_DEFAULT_PAGE_SIZE,
40758     **    + The value returned by sqlite3OsSectorSize()
40759     **    + The largest page size that can be written atomically.
40760     */
40761     if( rc==SQLITE_OK && !readOnly ){
40762       setSectorSize(pPager);
40763       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
40764       if( szPageDflt<pPager->sectorSize ){
40765         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
40766           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
40767         }else{
40768           szPageDflt = (u32)pPager->sectorSize;
40769         }
40770       }
40771 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40772       {
40773         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40774         int ii;
40775         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40776         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40777         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
40778         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
40779           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
40780             szPageDflt = ii;
40781           }
40782         }
40783       }
40784 #endif
40785     }
40786   }else{
40787     /* If a temporary file is requested, it is not opened immediately.
40788     ** In this case we accept the default page size and delay actually
40789     ** opening the file until the first call to OsWrite().
40790     **
40791     ** This branch is also run for an in-memory database. An in-memory
40792     ** database is the same as a temp-file that is never written out to
40793     ** disk and uses an in-memory rollback journal.
40794     */ 
40795     tempFile = 1;
40796     pPager->eState = PAGER_READER;
40797     pPager->eLock = EXCLUSIVE_LOCK;
40798     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
40799   }
40800
40801   /* The following call to PagerSetPagesize() serves to set the value of 
40802   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
40803   */
40804   if( rc==SQLITE_OK ){
40805     assert( pPager->memDb==0 );
40806     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
40807     testcase( rc!=SQLITE_OK );
40808   }
40809
40810   /* If an error occurred in either of the blocks above, free the 
40811   ** Pager structure and close the file.
40812   */
40813   if( rc!=SQLITE_OK ){
40814     assert( !pPager->pTmpSpace );
40815     sqlite3OsClose(pPager->fd);
40816     sqlite3_free(pPager);
40817     return rc;
40818   }
40819
40820   /* Initialize the PCache object. */
40821   assert( nExtra<1000 );
40822   nExtra = ROUND8(nExtra);
40823   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
40824                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
40825
40826   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
40827   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
40828
40829   pPager->useJournal = (u8)useJournal;
40830   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
40831   /* pPager->stmtOpen = 0; */
40832   /* pPager->stmtInUse = 0; */
40833   /* pPager->nRef = 0; */
40834   /* pPager->stmtSize = 0; */
40835   /* pPager->stmtJSize = 0; */
40836   /* pPager->nPage = 0; */
40837   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
40838   /* pPager->state = PAGER_UNLOCK; */
40839 #if 0
40840   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
40841 #endif
40842   /* pPager->errMask = 0; */
40843   pPager->tempFile = (u8)tempFile;
40844   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
40845           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
40846   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
40847   pPager->exclusiveMode = (u8)tempFile; 
40848   pPager->changeCountDone = pPager->tempFile;
40849   pPager->memDb = (u8)memDb;
40850   pPager->readOnly = (u8)readOnly;
40851   assert( useJournal || pPager->tempFile );
40852   pPager->noSync = pPager->tempFile;
40853   pPager->fullSync = pPager->noSync ?0:1;
40854   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
40855   pPager->ckptSyncFlags = pPager->syncFlags;
40856   /* pPager->pFirst = 0; */
40857   /* pPager->pFirstSynced = 0; */
40858   /* pPager->pLast = 0; */
40859   pPager->nExtra = (u16)nExtra;
40860   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
40861   assert( isOpen(pPager->fd) || tempFile );
40862   setSectorSize(pPager);
40863   if( !useJournal ){
40864     pPager->journalMode = PAGER_JOURNALMODE_OFF;
40865   }else if( memDb ){
40866     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
40867   }
40868   /* pPager->xBusyHandler = 0; */
40869   /* pPager->pBusyHandlerArg = 0; */
40870   pPager->xReiniter = xReinit;
40871   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
40872
40873   *ppPager = pPager;
40874   return SQLITE_OK;
40875 }
40876
40877
40878
40879 /*
40880 ** This function is called after transitioning from PAGER_UNLOCK to
40881 ** PAGER_SHARED state. It tests if there is a hot journal present in
40882 ** the file-system for the given pager. A hot journal is one that 
40883 ** needs to be played back. According to this function, a hot-journal
40884 ** file exists if the following criteria are met:
40885 **
40886 **   * The journal file exists in the file system, and
40887 **   * No process holds a RESERVED or greater lock on the database file, and
40888 **   * The database file itself is greater than 0 bytes in size, and
40889 **   * The first byte of the journal file exists and is not 0x00.
40890 **
40891 ** If the current size of the database file is 0 but a journal file
40892 ** exists, that is probably an old journal left over from a prior
40893 ** database with the same name. In this case the journal file is
40894 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
40895 ** is returned.
40896 **
40897 ** This routine does not check if there is a master journal filename
40898 ** at the end of the file. If there is, and that master journal file
40899 ** does not exist, then the journal file is not really hot. In this
40900 ** case this routine will return a false-positive. The pager_playback()
40901 ** routine will discover that the journal file is not really hot and 
40902 ** will not roll it back. 
40903 **
40904 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
40905 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
40906 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
40907 ** to determine whether or not a hot-journal file exists, the IO error
40908 ** code is returned and the value of *pExists is undefined.
40909 */
40910 static int hasHotJournal(Pager *pPager, int *pExists){
40911   sqlite3_vfs * const pVfs = pPager->pVfs;
40912   int rc = SQLITE_OK;           /* Return code */
40913   int exists = 1;               /* True if a journal file is present */
40914   int jrnlOpen = !!isOpen(pPager->jfd);
40915
40916   assert( pPager->useJournal );
40917   assert( isOpen(pPager->fd) );
40918   assert( pPager->eState==PAGER_OPEN );
40919
40920   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
40921     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
40922   ));
40923
40924   *pExists = 0;
40925   if( !jrnlOpen ){
40926     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
40927   }
40928   if( rc==SQLITE_OK && exists ){
40929     int locked = 0;             /* True if some process holds a RESERVED lock */
40930
40931     /* Race condition here:  Another process might have been holding the
40932     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
40933     ** call above, but then delete the journal and drop the lock before
40934     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
40935     ** is the case, this routine might think there is a hot journal when
40936     ** in fact there is none.  This results in a false-positive which will
40937     ** be dealt with by the playback routine.  Ticket #3883.
40938     */
40939     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
40940     if( rc==SQLITE_OK && !locked ){
40941       Pgno nPage;                 /* Number of pages in database file */
40942
40943       /* Check the size of the database file. If it consists of 0 pages,
40944       ** then delete the journal file. See the header comment above for 
40945       ** the reasoning here.  Delete the obsolete journal file under
40946       ** a RESERVED lock to avoid race conditions and to avoid violating
40947       ** [H33020].
40948       */
40949       rc = pagerPagecount(pPager, &nPage);
40950       if( rc==SQLITE_OK ){
40951         if( nPage==0 ){
40952           sqlite3BeginBenignMalloc();
40953           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
40954             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
40955             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
40956           }
40957           sqlite3EndBenignMalloc();
40958         }else{
40959           /* The journal file exists and no other connection has a reserved
40960           ** or greater lock on the database file. Now check that there is
40961           ** at least one non-zero bytes at the start of the journal file.
40962           ** If there is, then we consider this journal to be hot. If not, 
40963           ** it can be ignored.
40964           */
40965           if( !jrnlOpen ){
40966             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
40967             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
40968           }
40969           if( rc==SQLITE_OK ){
40970             u8 first = 0;
40971             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
40972             if( rc==SQLITE_IOERR_SHORT_READ ){
40973               rc = SQLITE_OK;
40974             }
40975             if( !jrnlOpen ){
40976               sqlite3OsClose(pPager->jfd);
40977             }
40978             *pExists = (first!=0);
40979           }else if( rc==SQLITE_CANTOPEN ){
40980             /* If we cannot open the rollback journal file in order to see if
40981             ** its has a zero header, that might be due to an I/O error, or
40982             ** it might be due to the race condition described above and in
40983             ** ticket #3883.  Either way, assume that the journal is hot.
40984             ** This might be a false positive.  But if it is, then the
40985             ** automatic journal playback and recovery mechanism will deal
40986             ** with it under an EXCLUSIVE lock where we do not need to
40987             ** worry so much with race conditions.
40988             */
40989             *pExists = 1;
40990             rc = SQLITE_OK;
40991           }
40992         }
40993       }
40994     }
40995   }
40996
40997   return rc;
40998 }
40999
41000 /*
41001 ** This function is called to obtain a shared lock on the database file.
41002 ** It is illegal to call sqlite3PagerAcquire() until after this function
41003 ** has been successfully called. If a shared-lock is already held when
41004 ** this function is called, it is a no-op.
41005 **
41006 ** The following operations are also performed by this function.
41007 **
41008 **   1) If the pager is currently in PAGER_OPEN state (no lock held
41009 **      on the database file), then an attempt is made to obtain a
41010 **      SHARED lock on the database file. Immediately after obtaining
41011 **      the SHARED lock, the file-system is checked for a hot-journal,
41012 **      which is played back if present. Following any hot-journal 
41013 **      rollback, the contents of the cache are validated by checking
41014 **      the 'change-counter' field of the database file header and
41015 **      discarded if they are found to be invalid.
41016 **
41017 **   2) If the pager is running in exclusive-mode, and there are currently
41018 **      no outstanding references to any pages, and is in the error state,
41019 **      then an attempt is made to clear the error state by discarding
41020 **      the contents of the page cache and rolling back any open journal
41021 **      file.
41022 **
41023 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41024 ** occurs while locking the database, checking for a hot-journal file or 
41025 ** rolling back a journal file, the IO error code is returned.
41026 */
41027 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41028   int rc = SQLITE_OK;                /* Return code */
41029
41030   /* This routine is only called from b-tree and only when there are no
41031   ** outstanding pages. This implies that the pager state should either
41032   ** be OPEN or READER. READER is only possible if the pager is or was in 
41033   ** exclusive access mode.
41034   */
41035   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41036   assert( assert_pager_state(pPager) );
41037   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41038   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41039
41040   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41041     int bHotJournal = 1;          /* True if there exists a hot journal-file */
41042
41043     assert( !MEMDB );
41044     assert( pPager->noReadlock==0 || pPager->readOnly );
41045
41046     if( pPager->noReadlock==0 ){
41047       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41048       if( rc!=SQLITE_OK ){
41049         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41050         goto failed;
41051       }
41052     }
41053
41054     /* If a journal file exists, and there is no RESERVED lock on the
41055     ** database file, then it either needs to be played back or deleted.
41056     */
41057     if( pPager->eLock<=SHARED_LOCK ){
41058       rc = hasHotJournal(pPager, &bHotJournal);
41059     }
41060     if( rc!=SQLITE_OK ){
41061       goto failed;
41062     }
41063     if( bHotJournal ){
41064       /* Get an EXCLUSIVE lock on the database file. At this point it is
41065       ** important that a RESERVED lock is not obtained on the way to the
41066       ** EXCLUSIVE lock. If it were, another process might open the
41067       ** database file, detect the RESERVED lock, and conclude that the
41068       ** database is safe to read while this process is still rolling the 
41069       ** hot-journal back.
41070       ** 
41071       ** Because the intermediate RESERVED lock is not requested, any
41072       ** other process attempting to access the database file will get to 
41073       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
41074       ** on the database file.
41075       **
41076       ** Unless the pager is in locking_mode=exclusive mode, the lock is
41077       ** downgraded to SHARED_LOCK before this function returns.
41078       */
41079       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41080       if( rc!=SQLITE_OK ){
41081         goto failed;
41082       }
41083  
41084       /* If it is not already open and the file exists on disk, open the 
41085       ** journal for read/write access. Write access is required because 
41086       ** in exclusive-access mode the file descriptor will be kept open 
41087       ** and possibly used for a transaction later on. Also, write-access 
41088       ** is usually required to finalize the journal in journal_mode=persist 
41089       ** mode (and also for journal_mode=truncate on some systems).
41090       **
41091       ** If the journal does not exist, it usually means that some 
41092       ** other connection managed to get in and roll it back before 
41093       ** this connection obtained the exclusive lock above. Or, it 
41094       ** may mean that the pager was in the error-state when this
41095       ** function was called and the journal file does not exist.
41096       */
41097       if( !isOpen(pPager->jfd) ){
41098         sqlite3_vfs * const pVfs = pPager->pVfs;
41099         int bExists;              /* True if journal file exists */
41100         rc = sqlite3OsAccess(
41101             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41102         if( rc==SQLITE_OK && bExists ){
41103           int fout = 0;
41104           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41105           assert( !pPager->tempFile );
41106           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41107           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41108           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41109             rc = SQLITE_CANTOPEN_BKPT;
41110             sqlite3OsClose(pPager->jfd);
41111           }
41112         }
41113       }
41114  
41115       /* Playback and delete the journal.  Drop the database write
41116       ** lock and reacquire the read lock. Purge the cache before
41117       ** playing back the hot-journal so that we don't end up with
41118       ** an inconsistent cache.  Sync the hot journal before playing
41119       ** it back since the process that crashed and left the hot journal
41120       ** probably did not sync it and we are required to always sync
41121       ** the journal before playing it back.
41122       */
41123       if( isOpen(pPager->jfd) ){
41124         assert( rc==SQLITE_OK );
41125         rc = pagerSyncHotJournal(pPager);
41126         if( rc==SQLITE_OK ){
41127           rc = pager_playback(pPager, 1);
41128           pPager->eState = PAGER_OPEN;
41129         }
41130       }else if( !pPager->exclusiveMode ){
41131         pagerUnlockDb(pPager, SHARED_LOCK);
41132       }
41133
41134       if( rc!=SQLITE_OK ){
41135         /* This branch is taken if an error occurs while trying to open
41136         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41137         ** pager_unlock() routine will be called before returning to unlock
41138         ** the file. If the unlock attempt fails, then Pager.eLock must be
41139         ** set to UNKNOWN_LOCK (see the comment above the #define for 
41140         ** UNKNOWN_LOCK above for an explanation). 
41141         **
41142         ** In order to get pager_unlock() to do this, set Pager.eState to
41143         ** PAGER_ERROR now. This is not actually counted as a transition
41144         ** to ERROR state in the state diagram at the top of this file,
41145         ** since we know that the same call to pager_unlock() will very
41146         ** shortly transition the pager object to the OPEN state. Calling
41147         ** assert_pager_state() would fail now, as it should not be possible
41148         ** to be in ERROR state when there are zero outstanding page 
41149         ** references.
41150         */
41151         pager_error(pPager, rc);
41152         goto failed;
41153       }
41154
41155       assert( pPager->eState==PAGER_OPEN );
41156       assert( (pPager->eLock==SHARED_LOCK)
41157            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41158       );
41159     }
41160
41161     if( !pPager->tempFile 
41162      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
41163     ){
41164       /* The shared-lock has just been acquired on the database file
41165       ** and there are already pages in the cache (from a previous
41166       ** read or write transaction).  Check to see if the database
41167       ** has been modified.  If the database has changed, flush the
41168       ** cache.
41169       **
41170       ** Database changes is detected by looking at 15 bytes beginning
41171       ** at offset 24 into the file.  The first 4 of these 16 bytes are
41172       ** a 32-bit counter that is incremented with each change.  The
41173       ** other bytes change randomly with each file change when
41174       ** a codec is in use.
41175       ** 
41176       ** There is a vanishingly small chance that a change will not be 
41177       ** detected.  The chance of an undetected change is so small that
41178       ** it can be neglected.
41179       */
41180       Pgno nPage = 0;
41181       char dbFileVers[sizeof(pPager->dbFileVers)];
41182
41183       rc = pagerPagecount(pPager, &nPage);
41184       if( rc ) goto failed;
41185
41186       if( nPage>0 ){
41187         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41188         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41189         if( rc!=SQLITE_OK ){
41190           goto failed;
41191         }
41192       }else{
41193         memset(dbFileVers, 0, sizeof(dbFileVers));
41194       }
41195
41196       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41197         pager_reset(pPager);
41198       }
41199     }
41200
41201     /* If there is a WAL file in the file-system, open this database in WAL
41202     ** mode. Otherwise, the following function call is a no-op.
41203     */
41204     rc = pagerOpenWalIfPresent(pPager);
41205 #ifndef SQLITE_OMIT_WAL
41206     assert( pPager->pWal==0 || rc==SQLITE_OK );
41207 #endif
41208   }
41209
41210   if( pagerUseWal(pPager) ){
41211     assert( rc==SQLITE_OK );
41212     rc = pagerBeginReadTransaction(pPager);
41213   }
41214
41215   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41216     rc = pagerPagecount(pPager, &pPager->dbSize);
41217   }
41218
41219  failed:
41220   if( rc!=SQLITE_OK ){
41221     assert( !MEMDB );
41222     pager_unlock(pPager);
41223     assert( pPager->eState==PAGER_OPEN );
41224   }else{
41225     pPager->eState = PAGER_READER;
41226   }
41227   return rc;
41228 }
41229
41230 /*
41231 ** If the reference count has reached zero, rollback any active
41232 ** transaction and unlock the pager.
41233 **
41234 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41235 ** the rollback journal, the unlock is not performed and there is
41236 ** nothing to rollback, so this routine is a no-op.
41237 */ 
41238 static void pagerUnlockIfUnused(Pager *pPager){
41239   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41240     pagerUnlockAndRollback(pPager);
41241   }
41242 }
41243
41244 /*
41245 ** Acquire a reference to page number pgno in pager pPager (a page
41246 ** reference has type DbPage*). If the requested reference is 
41247 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41248 **
41249 ** If the requested page is already in the cache, it is returned. 
41250 ** Otherwise, a new page object is allocated and populated with data
41251 ** read from the database file. In some cases, the pcache module may
41252 ** choose not to allocate a new page object and may reuse an existing
41253 ** object with no outstanding references.
41254 **
41255 ** The extra data appended to a page is always initialized to zeros the 
41256 ** first time a page is loaded into memory. If the page requested is 
41257 ** already in the cache when this function is called, then the extra
41258 ** data is left as it was when the page object was last used.
41259 **
41260 ** If the database image is smaller than the requested page or if a 
41261 ** non-zero value is passed as the noContent parameter and the 
41262 ** requested page is not already stored in the cache, then no 
41263 ** actual disk read occurs. In this case the memory image of the 
41264 ** page is initialized to all zeros. 
41265 **
41266 ** If noContent is true, it means that we do not care about the contents
41267 ** of the page. This occurs in two seperate scenarios:
41268 **
41269 **   a) When reading a free-list leaf page from the database, and
41270 **
41271 **   b) When a savepoint is being rolled back and we need to load
41272 **      a new page into the cache to be filled with the data read
41273 **      from the savepoint journal.
41274 **
41275 ** If noContent is true, then the data returned is zeroed instead of
41276 ** being read from the database. Additionally, the bits corresponding
41277 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41278 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41279 ** savepoints are set. This means if the page is made writable at any
41280 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41281 ** will not be journaled. This saves IO.
41282 **
41283 ** The acquisition might fail for several reasons.  In all cases,
41284 ** an appropriate error code is returned and *ppPage is set to NULL.
41285 **
41286 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
41287 ** to find a page in the in-memory cache first.  If the page is not already
41288 ** in memory, this routine goes to disk to read it in whereas Lookup()
41289 ** just returns 0.  This routine acquires a read-lock the first time it
41290 ** has to go to disk, and could also playback an old journal if necessary.
41291 ** Since Lookup() never goes to disk, it never has to deal with locks
41292 ** or journal files.
41293 */
41294 SQLITE_PRIVATE int sqlite3PagerAcquire(
41295   Pager *pPager,      /* The pager open on the database file */
41296   Pgno pgno,          /* Page number to fetch */
41297   DbPage **ppPage,    /* Write a pointer to the page here */
41298   int noContent       /* Do not bother reading content from disk if true */
41299 ){
41300   int rc;
41301   PgHdr *pPg;
41302
41303   assert( pPager->eState>=PAGER_READER );
41304   assert( assert_pager_state(pPager) );
41305
41306   if( pgno==0 ){
41307     return SQLITE_CORRUPT_BKPT;
41308   }
41309
41310   /* If the pager is in the error state, return an error immediately. 
41311   ** Otherwise, request the page from the PCache layer. */
41312   if( pPager->errCode!=SQLITE_OK ){
41313     rc = pPager->errCode;
41314   }else{
41315     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41316   }
41317
41318   if( rc!=SQLITE_OK ){
41319     /* Either the call to sqlite3PcacheFetch() returned an error or the
41320     ** pager was already in the error-state when this function was called.
41321     ** Set pPg to 0 and jump to the exception handler.  */
41322     pPg = 0;
41323     goto pager_acquire_err;
41324   }
41325   assert( (*ppPage)->pgno==pgno );
41326   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41327
41328   if( (*ppPage)->pPager && !noContent ){
41329     /* In this case the pcache already contains an initialized copy of
41330     ** the page. Return without further ado.  */
41331     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41332     PAGER_INCR(pPager->nHit);
41333     return SQLITE_OK;
41334
41335   }else{
41336     /* The pager cache has created a new page. Its content needs to 
41337     ** be initialized.  */
41338
41339     PAGER_INCR(pPager->nMiss);
41340     pPg = *ppPage;
41341     pPg->pPager = pPager;
41342
41343     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41344     ** number greater than this, or the unused locking-page, is requested. */
41345     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41346       rc = SQLITE_CORRUPT_BKPT;
41347       goto pager_acquire_err;
41348     }
41349
41350     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41351       if( pgno>pPager->mxPgno ){
41352         rc = SQLITE_FULL;
41353         goto pager_acquire_err;
41354       }
41355       if( noContent ){
41356         /* Failure to set the bits in the InJournal bit-vectors is benign.
41357         ** It merely means that we might do some extra work to journal a 
41358         ** page that does not need to be journaled.  Nevertheless, be sure 
41359         ** to test the case where a malloc error occurs while trying to set 
41360         ** a bit in a bit vector.
41361         */
41362         sqlite3BeginBenignMalloc();
41363         if( pgno<=pPager->dbOrigSize ){
41364           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41365           testcase( rc==SQLITE_NOMEM );
41366         }
41367         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41368         testcase( rc==SQLITE_NOMEM );
41369         sqlite3EndBenignMalloc();
41370       }
41371       memset(pPg->pData, 0, pPager->pageSize);
41372       IOTRACE(("ZERO %p %d\n", pPager, pgno));
41373     }else{
41374       assert( pPg->pPager==pPager );
41375       rc = readDbPage(pPg);
41376       if( rc!=SQLITE_OK ){
41377         goto pager_acquire_err;
41378       }
41379     }
41380     pager_set_pagehash(pPg);
41381   }
41382
41383   return SQLITE_OK;
41384
41385 pager_acquire_err:
41386   assert( rc!=SQLITE_OK );
41387   if( pPg ){
41388     sqlite3PcacheDrop(pPg);
41389   }
41390   pagerUnlockIfUnused(pPager);
41391
41392   *ppPage = 0;
41393   return rc;
41394 }
41395
41396 /*
41397 ** Acquire a page if it is already in the in-memory cache.  Do
41398 ** not read the page from disk.  Return a pointer to the page,
41399 ** or 0 if the page is not in cache. 
41400 **
41401 ** See also sqlite3PagerGet().  The difference between this routine
41402 ** and sqlite3PagerGet() is that _get() will go to the disk and read
41403 ** in the page if the page is not already in cache.  This routine
41404 ** returns NULL if the page is not in cache or if a disk I/O error 
41405 ** has ever happened.
41406 */
41407 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41408   PgHdr *pPg = 0;
41409   assert( pPager!=0 );
41410   assert( pgno!=0 );
41411   assert( pPager->pPCache!=0 );
41412   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41413   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41414   return pPg;
41415 }
41416
41417 /*
41418 ** Release a page reference.
41419 **
41420 ** If the number of references to the page drop to zero, then the
41421 ** page is added to the LRU list.  When all references to all pages
41422 ** are released, a rollback occurs and the lock on the database is
41423 ** removed.
41424 */
41425 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41426   if( pPg ){
41427     Pager *pPager = pPg->pPager;
41428     sqlite3PcacheRelease(pPg);
41429     pagerUnlockIfUnused(pPager);
41430   }
41431 }
41432
41433 /*
41434 ** This function is called at the start of every write transaction.
41435 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
41436 ** file when this routine is called.
41437 **
41438 ** Open the journal file for pager pPager and write a journal header
41439 ** to the start of it. If there are active savepoints, open the sub-journal
41440 ** as well. This function is only used when the journal file is being 
41441 ** opened to write a rollback log for a transaction. It is not used 
41442 ** when opening a hot journal file to roll it back.
41443 **
41444 ** If the journal file is already open (as it may be in exclusive mode),
41445 ** then this function just writes a journal header to the start of the
41446 ** already open file. 
41447 **
41448 ** Whether or not the journal file is opened by this function, the
41449 ** Pager.pInJournal bitvec structure is allocated.
41450 **
41451 ** Return SQLITE_OK if everything is successful. Otherwise, return 
41452 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
41453 ** an IO error code if opening or writing the journal file fails.
41454 */
41455 static int pager_open_journal(Pager *pPager){
41456   int rc = SQLITE_OK;                        /* Return code */
41457   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
41458
41459   assert( pPager->eState==PAGER_WRITER_LOCKED );
41460   assert( assert_pager_state(pPager) );
41461   assert( pPager->pInJournal==0 );
41462   
41463   /* If already in the error state, this function is a no-op.  But on
41464   ** the other hand, this routine is never called if we are already in
41465   ** an error state. */
41466   if( NEVER(pPager->errCode) ) return pPager->errCode;
41467
41468   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41469     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41470     if( pPager->pInJournal==0 ){
41471       return SQLITE_NOMEM;
41472     }
41473   
41474     /* Open the journal file if it is not already open. */
41475     if( !isOpen(pPager->jfd) ){
41476       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41477         sqlite3MemJournalOpen(pPager->jfd);
41478       }else{
41479         const int flags =                   /* VFS flags to open journal file */
41480           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41481           (pPager->tempFile ? 
41482             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41483             (SQLITE_OPEN_MAIN_JOURNAL)
41484           );
41485   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41486         rc = sqlite3JournalOpen(
41487             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41488         );
41489   #else
41490         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41491   #endif
41492       }
41493       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41494     }
41495   
41496   
41497     /* Write the first journal header to the journal file and open 
41498     ** the sub-journal if necessary.
41499     */
41500     if( rc==SQLITE_OK ){
41501       /* TODO: Check if all of these are really required. */
41502       pPager->nRec = 0;
41503       pPager->journalOff = 0;
41504       pPager->setMaster = 0;
41505       pPager->journalHdr = 0;
41506       rc = writeJournalHdr(pPager);
41507     }
41508   }
41509
41510   if( rc!=SQLITE_OK ){
41511     sqlite3BitvecDestroy(pPager->pInJournal);
41512     pPager->pInJournal = 0;
41513   }else{
41514     assert( pPager->eState==PAGER_WRITER_LOCKED );
41515     pPager->eState = PAGER_WRITER_CACHEMOD;
41516   }
41517
41518   return rc;
41519 }
41520
41521 /*
41522 ** Begin a write-transaction on the specified pager object. If a 
41523 ** write-transaction has already been opened, this function is a no-op.
41524 **
41525 ** If the exFlag argument is false, then acquire at least a RESERVED
41526 ** lock on the database file. If exFlag is true, then acquire at least
41527 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
41528 ** functions need be called.
41529 **
41530 ** If the subjInMemory argument is non-zero, then any sub-journal opened
41531 ** within this transaction will be opened as an in-memory file. This
41532 ** has no effect if the sub-journal is already opened (as it may be when
41533 ** running in exclusive mode) or if the transaction does not require a
41534 ** sub-journal. If the subjInMemory argument is zero, then any required
41535 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
41536 ** or using a temporary file otherwise.
41537 */
41538 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
41539   int rc = SQLITE_OK;
41540
41541   if( pPager->errCode ) return pPager->errCode;
41542   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
41543   pPager->subjInMemory = (u8)subjInMemory;
41544
41545   if( ALWAYS(pPager->eState==PAGER_READER) ){
41546     assert( pPager->pInJournal==0 );
41547
41548     if( pagerUseWal(pPager) ){
41549       /* If the pager is configured to use locking_mode=exclusive, and an
41550       ** exclusive lock on the database is not already held, obtain it now.
41551       */
41552       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
41553         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41554         if( rc!=SQLITE_OK ){
41555           return rc;
41556         }
41557         sqlite3WalExclusiveMode(pPager->pWal, 1);
41558       }
41559
41560       /* Grab the write lock on the log file. If successful, upgrade to
41561       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
41562       ** The busy-handler is not invoked if another connection already
41563       ** holds the write-lock. If possible, the upper layer will call it.
41564       */
41565       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
41566     }else{
41567       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
41568       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
41569       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
41570       ** lock, but not when obtaining the RESERVED lock.
41571       */
41572       rc = pagerLockDb(pPager, RESERVED_LOCK);
41573       if( rc==SQLITE_OK && exFlag ){
41574         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
41575       }
41576     }
41577
41578     if( rc==SQLITE_OK ){
41579       /* Change to WRITER_LOCKED state.
41580       **
41581       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
41582       ** when it has an open transaction, but never to DBMOD or FINISHED.
41583       ** This is because in those states the code to roll back savepoint 
41584       ** transactions may copy data from the sub-journal into the database 
41585       ** file as well as into the page cache. Which would be incorrect in 
41586       ** WAL mode.
41587       */
41588       pPager->eState = PAGER_WRITER_LOCKED;
41589       pPager->dbHintSize = pPager->dbSize;
41590       pPager->dbFileSize = pPager->dbSize;
41591       pPager->dbOrigSize = pPager->dbSize;
41592       pPager->journalOff = 0;
41593     }
41594
41595     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
41596     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
41597     assert( assert_pager_state(pPager) );
41598   }
41599
41600   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
41601   return rc;
41602 }
41603
41604 /*
41605 ** Mark a single data page as writeable. The page is written into the 
41606 ** main journal or sub-journal as required. If the page is written into
41607 ** one of the journals, the corresponding bit is set in the 
41608 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
41609 ** of any open savepoints as appropriate.
41610 */
41611 static int pager_write(PgHdr *pPg){
41612   void *pData = pPg->pData;
41613   Pager *pPager = pPg->pPager;
41614   int rc = SQLITE_OK;
41615
41616   /* This routine is not called unless a write-transaction has already 
41617   ** been started. The journal file may or may not be open at this point.
41618   ** It is never called in the ERROR state.
41619   */
41620   assert( pPager->eState==PAGER_WRITER_LOCKED
41621        || pPager->eState==PAGER_WRITER_CACHEMOD
41622        || pPager->eState==PAGER_WRITER_DBMOD
41623   );
41624   assert( assert_pager_state(pPager) );
41625
41626   /* If an error has been previously detected, report the same error
41627   ** again. This should not happen, but the check provides robustness. */
41628   if( NEVER(pPager->errCode) )  return pPager->errCode;
41629
41630   /* Higher-level routines never call this function if database is not
41631   ** writable.  But check anyway, just for robustness. */
41632   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
41633
41634   CHECK_PAGE(pPg);
41635
41636   /* The journal file needs to be opened. Higher level routines have already
41637   ** obtained the necessary locks to begin the write-transaction, but the
41638   ** rollback journal might not yet be open. Open it now if this is the case.
41639   **
41640   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
41641   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
41642   ** an error might occur and the pager would end up in WRITER_LOCKED state
41643   ** with pages marked as dirty in the cache.
41644   */
41645   if( pPager->eState==PAGER_WRITER_LOCKED ){
41646     rc = pager_open_journal(pPager);
41647     if( rc!=SQLITE_OK ) return rc;
41648   }
41649   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41650   assert( assert_pager_state(pPager) );
41651
41652   /* Mark the page as dirty.  If the page has already been written
41653   ** to the journal then we can return right away.
41654   */
41655   sqlite3PcacheMakeDirty(pPg);
41656   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
41657     assert( !pagerUseWal(pPager) );
41658   }else{
41659   
41660     /* The transaction journal now exists and we have a RESERVED or an
41661     ** EXCLUSIVE lock on the main database file.  Write the current page to
41662     ** the transaction journal if it is not there already.
41663     */
41664     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
41665       assert( pagerUseWal(pPager)==0 );
41666       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
41667         u32 cksum;
41668         char *pData2;
41669         i64 iOff = pPager->journalOff;
41670
41671         /* We should never write to the journal file the page that
41672         ** contains the database locks.  The following assert verifies
41673         ** that we do not. */
41674         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
41675
41676         assert( pPager->journalHdr<=pPager->journalOff );
41677         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41678         cksum = pager_cksum(pPager, (u8*)pData2);
41679
41680         /* Even if an IO or diskfull error occurs while journalling the
41681         ** page in the block above, set the need-sync flag for the page.
41682         ** Otherwise, when the transaction is rolled back, the logic in
41683         ** playback_one_page() will think that the page needs to be restored
41684         ** in the database file. And if an IO error occurs while doing so,
41685         ** then corruption may follow.
41686         */
41687         pPg->flags |= PGHDR_NEED_SYNC;
41688
41689         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
41690         if( rc!=SQLITE_OK ) return rc;
41691         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
41692         if( rc!=SQLITE_OK ) return rc;
41693         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
41694         if( rc!=SQLITE_OK ) return rc;
41695
41696         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
41697                  pPager->journalOff, pPager->pageSize));
41698         PAGER_INCR(sqlite3_pager_writej_count);
41699         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
41700              PAGERID(pPager), pPg->pgno, 
41701              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
41702
41703         pPager->journalOff += 8 + pPager->pageSize;
41704         pPager->nRec++;
41705         assert( pPager->pInJournal!=0 );
41706         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
41707         testcase( rc==SQLITE_NOMEM );
41708         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41709         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
41710         if( rc!=SQLITE_OK ){
41711           assert( rc==SQLITE_NOMEM );
41712           return rc;
41713         }
41714       }else{
41715         if( pPager->eState!=PAGER_WRITER_DBMOD ){
41716           pPg->flags |= PGHDR_NEED_SYNC;
41717         }
41718         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
41719                 PAGERID(pPager), pPg->pgno,
41720                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
41721       }
41722     }
41723   
41724     /* If the statement journal is open and the page is not in it,
41725     ** then write the current page to the statement journal.  Note that
41726     ** the statement journal format differs from the standard journal format
41727     ** in that it omits the checksums and the header.
41728     */
41729     if( subjRequiresPage(pPg) ){
41730       rc = subjournalPage(pPg);
41731     }
41732   }
41733
41734   /* Update the database size and return.
41735   */
41736   if( pPager->dbSize<pPg->pgno ){
41737     pPager->dbSize = pPg->pgno;
41738   }
41739   return rc;
41740 }
41741
41742 /*
41743 ** Mark a data page as writeable. This routine must be called before 
41744 ** making changes to a page. The caller must check the return value 
41745 ** of this function and be careful not to change any page data unless 
41746 ** this routine returns SQLITE_OK.
41747 **
41748 ** The difference between this function and pager_write() is that this
41749 ** function also deals with the special case where 2 or more pages
41750 ** fit on a single disk sector. In this case all co-resident pages
41751 ** must have been written to the journal file before returning.
41752 **
41753 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
41754 ** as appropriate. Otherwise, SQLITE_OK.
41755 */
41756 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
41757   int rc = SQLITE_OK;
41758
41759   PgHdr *pPg = pDbPage;
41760   Pager *pPager = pPg->pPager;
41761   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
41762
41763   assert( pPager->eState>=PAGER_WRITER_LOCKED );
41764   assert( pPager->eState!=PAGER_ERROR );
41765   assert( assert_pager_state(pPager) );
41766
41767   if( nPagePerSector>1 ){
41768     Pgno nPageCount;          /* Total number of pages in database file */
41769     Pgno pg1;                 /* First page of the sector pPg is located on. */
41770     int nPage = 0;            /* Number of pages starting at pg1 to journal */
41771     int ii;                   /* Loop counter */
41772     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
41773
41774     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
41775     ** a journal header to be written between the pages journaled by
41776     ** this function.
41777     */
41778     assert( !MEMDB );
41779     assert( pPager->doNotSyncSpill==0 );
41780     pPager->doNotSyncSpill++;
41781
41782     /* This trick assumes that both the page-size and sector-size are
41783     ** an integer power of 2. It sets variable pg1 to the identifier
41784     ** of the first page of the sector pPg is located on.
41785     */
41786     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
41787
41788     nPageCount = pPager->dbSize;
41789     if( pPg->pgno>nPageCount ){
41790       nPage = (pPg->pgno - pg1)+1;
41791     }else if( (pg1+nPagePerSector-1)>nPageCount ){
41792       nPage = nPageCount+1-pg1;
41793     }else{
41794       nPage = nPagePerSector;
41795     }
41796     assert(nPage>0);
41797     assert(pg1<=pPg->pgno);
41798     assert((pg1+nPage)>pPg->pgno);
41799
41800     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
41801       Pgno pg = pg1+ii;
41802       PgHdr *pPage;
41803       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
41804         if( pg!=PAGER_MJ_PGNO(pPager) ){
41805           rc = sqlite3PagerGet(pPager, pg, &pPage);
41806           if( rc==SQLITE_OK ){
41807             rc = pager_write(pPage);
41808             if( pPage->flags&PGHDR_NEED_SYNC ){
41809               needSync = 1;
41810             }
41811             sqlite3PagerUnref(pPage);
41812           }
41813         }
41814       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
41815         if( pPage->flags&PGHDR_NEED_SYNC ){
41816           needSync = 1;
41817         }
41818         sqlite3PagerUnref(pPage);
41819       }
41820     }
41821
41822     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
41823     ** starting at pg1, then it needs to be set for all of them. Because
41824     ** writing to any of these nPage pages may damage the others, the
41825     ** journal file must contain sync()ed copies of all of them
41826     ** before any of them can be written out to the database file.
41827     */
41828     if( rc==SQLITE_OK && needSync ){
41829       assert( !MEMDB );
41830       for(ii=0; ii<nPage; ii++){
41831         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
41832         if( pPage ){
41833           pPage->flags |= PGHDR_NEED_SYNC;
41834           sqlite3PagerUnref(pPage);
41835         }
41836       }
41837     }
41838
41839     assert( pPager->doNotSyncSpill==1 );
41840     pPager->doNotSyncSpill--;
41841   }else{
41842     rc = pager_write(pDbPage);
41843   }
41844   return rc;
41845 }
41846
41847 /*
41848 ** Return TRUE if the page given in the argument was previously passed
41849 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
41850 ** to change the content of the page.
41851 */
41852 #ifndef NDEBUG
41853 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
41854   return pPg->flags&PGHDR_DIRTY;
41855 }
41856 #endif
41857
41858 /*
41859 ** A call to this routine tells the pager that it is not necessary to
41860 ** write the information on page pPg back to the disk, even though
41861 ** that page might be marked as dirty.  This happens, for example, when
41862 ** the page has been added as a leaf of the freelist and so its
41863 ** content no longer matters.
41864 **
41865 ** The overlying software layer calls this routine when all of the data
41866 ** on the given page is unused. The pager marks the page as clean so
41867 ** that it does not get written to disk.
41868 **
41869 ** Tests show that this optimization can quadruple the speed of large 
41870 ** DELETE operations.
41871 */
41872 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
41873   Pager *pPager = pPg->pPager;
41874   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
41875     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
41876     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
41877     pPg->flags |= PGHDR_DONT_WRITE;
41878     pager_set_pagehash(pPg);
41879   }
41880 }
41881
41882 /*
41883 ** This routine is called to increment the value of the database file 
41884 ** change-counter, stored as a 4-byte big-endian integer starting at 
41885 ** byte offset 24 of the pager file.  The secondary change counter at
41886 ** 92 is also updated, as is the SQLite version number at offset 96.
41887 **
41888 ** But this only happens if the pPager->changeCountDone flag is false.
41889 ** To avoid excess churning of page 1, the update only happens once.
41890 ** See also the pager_write_changecounter() routine that does an 
41891 ** unconditional update of the change counters.
41892 **
41893 ** If the isDirectMode flag is zero, then this is done by calling 
41894 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
41895 ** page data. In this case the file will be updated when the current
41896 ** transaction is committed.
41897 **
41898 ** The isDirectMode flag may only be non-zero if the library was compiled
41899 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
41900 ** if isDirect is non-zero, then the database file is updated directly
41901 ** by writing an updated version of page 1 using a call to the 
41902 ** sqlite3OsWrite() function.
41903 */
41904 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
41905   int rc = SQLITE_OK;
41906
41907   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41908        || pPager->eState==PAGER_WRITER_DBMOD
41909   );
41910   assert( assert_pager_state(pPager) );
41911
41912   /* Declare and initialize constant integer 'isDirect'. If the
41913   ** atomic-write optimization is enabled in this build, then isDirect
41914   ** is initialized to the value passed as the isDirectMode parameter
41915   ** to this function. Otherwise, it is always set to zero.
41916   **
41917   ** The idea is that if the atomic-write optimization is not
41918   ** enabled at compile time, the compiler can omit the tests of
41919   ** 'isDirect' below, as well as the block enclosed in the
41920   ** "if( isDirect )" condition.
41921   */
41922 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
41923 # define DIRECT_MODE 0
41924   assert( isDirectMode==0 );
41925   UNUSED_PARAMETER(isDirectMode);
41926 #else
41927 # define DIRECT_MODE isDirectMode
41928 #endif
41929
41930   if( !pPager->changeCountDone && pPager->dbSize>0 ){
41931     PgHdr *pPgHdr;                /* Reference to page 1 */
41932
41933     assert( !pPager->tempFile && isOpen(pPager->fd) );
41934
41935     /* Open page 1 of the file for writing. */
41936     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
41937     assert( pPgHdr==0 || rc==SQLITE_OK );
41938
41939     /* If page one was fetched successfully, and this function is not
41940     ** operating in direct-mode, make page 1 writable.  When not in 
41941     ** direct mode, page 1 is always held in cache and hence the PagerGet()
41942     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
41943     */
41944     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
41945       rc = sqlite3PagerWrite(pPgHdr);
41946     }
41947
41948     if( rc==SQLITE_OK ){
41949       /* Actually do the update of the change counter */
41950       pager_write_changecounter(pPgHdr);
41951
41952       /* If running in direct mode, write the contents of page 1 to the file. */
41953       if( DIRECT_MODE ){
41954         const void *zBuf;
41955         assert( pPager->dbFileSize>0 );
41956         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
41957         if( rc==SQLITE_OK ){
41958           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
41959         }
41960         if( rc==SQLITE_OK ){
41961           pPager->changeCountDone = 1;
41962         }
41963       }else{
41964         pPager->changeCountDone = 1;
41965       }
41966     }
41967
41968     /* Release the page reference. */
41969     sqlite3PagerUnref(pPgHdr);
41970   }
41971   return rc;
41972 }
41973
41974 /*
41975 ** Sync the database file to disk. This is a no-op for in-memory databases
41976 ** or pages with the Pager.noSync flag set.
41977 **
41978 ** If successful, or if called on a pager for which it is a no-op, this
41979 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
41980 */
41981 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
41982   int rc = SQLITE_OK;
41983   if( !pPager->noSync ){
41984     assert( !MEMDB );
41985     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
41986   }else if( isOpen(pPager->fd) ){
41987     assert( !MEMDB );
41988     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
41989   }
41990   return rc;
41991 }
41992
41993 /*
41994 ** This function may only be called while a write-transaction is active in
41995 ** rollback. If the connection is in WAL mode, this call is a no-op. 
41996 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
41997 ** the database file, an attempt is made to obtain one.
41998 **
41999 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42000 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42001 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
42002 ** returned.
42003 */
42004 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42005   int rc = SQLITE_OK;
42006   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
42007        || pPager->eState==PAGER_WRITER_DBMOD 
42008        || pPager->eState==PAGER_WRITER_LOCKED 
42009   );
42010   assert( assert_pager_state(pPager) );
42011   if( 0==pagerUseWal(pPager) ){
42012     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42013   }
42014   return rc;
42015 }
42016
42017 /*
42018 ** Sync the database file for the pager pPager. zMaster points to the name
42019 ** of a master journal file that should be written into the individual
42020 ** journal file. zMaster may be NULL, which is interpreted as no master
42021 ** journal (a single database transaction).
42022 **
42023 ** This routine ensures that:
42024 **
42025 **   * The database file change-counter is updated,
42026 **   * the journal is synced (unless the atomic-write optimization is used),
42027 **   * all dirty pages are written to the database file, 
42028 **   * the database file is truncated (if required), and
42029 **   * the database file synced. 
42030 **
42031 ** The only thing that remains to commit the transaction is to finalize 
42032 ** (delete, truncate or zero the first part of) the journal file (or 
42033 ** delete the master journal file if specified).
42034 **
42035 ** Note that if zMaster==NULL, this does not overwrite a previous value
42036 ** passed to an sqlite3PagerCommitPhaseOne() call.
42037 **
42038 ** If the final parameter - noSync - is true, then the database file itself
42039 ** is not synced. The caller must call sqlite3PagerSync() directly to
42040 ** sync the database file before calling CommitPhaseTwo() to delete the
42041 ** journal file in this case.
42042 */
42043 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42044   Pager *pPager,                  /* Pager object */
42045   const char *zMaster,            /* If not NULL, the master journal name */
42046   int noSync                      /* True to omit the xSync on the db file */
42047 ){
42048   int rc = SQLITE_OK;             /* Return code */
42049
42050   assert( pPager->eState==PAGER_WRITER_LOCKED
42051        || pPager->eState==PAGER_WRITER_CACHEMOD
42052        || pPager->eState==PAGER_WRITER_DBMOD
42053        || pPager->eState==PAGER_ERROR
42054   );
42055   assert( assert_pager_state(pPager) );
42056
42057   /* If a prior error occurred, report that error again. */
42058   if( NEVER(pPager->errCode) ) return pPager->errCode;
42059
42060   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
42061       pPager->zFilename, zMaster, pPager->dbSize));
42062
42063   /* If no database changes have been made, return early. */
42064   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42065
42066   if( MEMDB ){
42067     /* If this is an in-memory db, or no pages have been written to, or this
42068     ** function has already been called, it is mostly a no-op.  However, any
42069     ** backup in progress needs to be restarted.
42070     */
42071     sqlite3BackupRestart(pPager->pBackup);
42072   }else{
42073     if( pagerUseWal(pPager) ){
42074       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42075       PgHdr *pPageOne = 0;
42076       if( pList==0 ){
42077         /* Must have at least one page for the WAL commit flag.
42078         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42079         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42080         pList = pPageOne;
42081         pList->pDirty = 0;
42082       }
42083       assert( pList!=0 || rc!=SQLITE_OK );
42084       if( pList ){
42085         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
42086             (pPager->fullSync ? pPager->syncFlags : 0)
42087         );
42088       }
42089       sqlite3PagerUnref(pPageOne);
42090       if( rc==SQLITE_OK ){
42091         sqlite3PcacheCleanAll(pPager->pPCache);
42092       }
42093     }else{
42094       /* The following block updates the change-counter. Exactly how it
42095       ** does this depends on whether or not the atomic-update optimization
42096       ** was enabled at compile time, and if this transaction meets the 
42097       ** runtime criteria to use the operation: 
42098       **
42099       **    * The file-system supports the atomic-write property for
42100       **      blocks of size page-size, and 
42101       **    * This commit is not part of a multi-file transaction, and
42102       **    * Exactly one page has been modified and store in the journal file.
42103       **
42104       ** If the optimization was not enabled at compile time, then the
42105       ** pager_incr_changecounter() function is called to update the change
42106       ** counter in 'indirect-mode'. If the optimization is compiled in but
42107       ** is not applicable to this transaction, call sqlite3JournalCreate()
42108       ** to make sure the journal file has actually been created, then call
42109       ** pager_incr_changecounter() to update the change-counter in indirect
42110       ** mode. 
42111       **
42112       ** Otherwise, if the optimization is both enabled and applicable,
42113       ** then call pager_incr_changecounter() to update the change-counter
42114       ** in 'direct' mode. In this case the journal file will never be
42115       ** created for this transaction.
42116       */
42117   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42118       PgHdr *pPg;
42119       assert( isOpen(pPager->jfd) 
42120            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
42121            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
42122       );
42123       if( !zMaster && isOpen(pPager->jfd) 
42124        && pPager->journalOff==jrnlBufferSize(pPager) 
42125        && pPager->dbSize>=pPager->dbOrigSize
42126        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42127       ){
42128         /* Update the db file change counter via the direct-write method. The 
42129         ** following call will modify the in-memory representation of page 1 
42130         ** to include the updated change counter and then write page 1 
42131         ** directly to the database file. Because of the atomic-write 
42132         ** property of the host file-system, this is safe.
42133         */
42134         rc = pager_incr_changecounter(pPager, 1);
42135       }else{
42136         rc = sqlite3JournalCreate(pPager->jfd);
42137         if( rc==SQLITE_OK ){
42138           rc = pager_incr_changecounter(pPager, 0);
42139         }
42140       }
42141   #else
42142       rc = pager_incr_changecounter(pPager, 0);
42143   #endif
42144       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42145   
42146       /* If this transaction has made the database smaller, then all pages
42147       ** being discarded by the truncation must be written to the journal
42148       ** file. This can only happen in auto-vacuum mode.
42149       **
42150       ** Before reading the pages with page numbers larger than the 
42151       ** current value of Pager.dbSize, set dbSize back to the value
42152       ** that it took at the start of the transaction. Otherwise, the
42153       ** calls to sqlite3PagerGet() return zeroed pages instead of 
42154       ** reading data from the database file.
42155       */
42156   #ifndef SQLITE_OMIT_AUTOVACUUM
42157       if( pPager->dbSize<pPager->dbOrigSize 
42158        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42159       ){
42160         Pgno i;                                   /* Iterator variable */
42161         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42162         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
42163         pPager->dbSize = pPager->dbOrigSize;
42164         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42165           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42166             PgHdr *pPage;             /* Page to journal */
42167             rc = sqlite3PagerGet(pPager, i, &pPage);
42168             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42169             rc = sqlite3PagerWrite(pPage);
42170             sqlite3PagerUnref(pPage);
42171             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42172           }
42173         }
42174         pPager->dbSize = dbSize;
42175       } 
42176   #endif
42177   
42178       /* Write the master journal name into the journal file. If a master 
42179       ** journal file name has already been written to the journal file, 
42180       ** or if zMaster is NULL (no master journal), then this call is a no-op.
42181       */
42182       rc = writeMasterJournal(pPager, zMaster);
42183       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42184   
42185       /* Sync the journal file and write all dirty pages to the database.
42186       ** If the atomic-update optimization is being used, this sync will not 
42187       ** create the journal file or perform any real IO.
42188       **
42189       ** Because the change-counter page was just modified, unless the
42190       ** atomic-update optimization is used it is almost certain that the
42191       ** journal requires a sync here. However, in locking_mode=exclusive
42192       ** on a system under memory pressure it is just possible that this is 
42193       ** not the case. In this case it is likely enough that the redundant
42194       ** xSync() call will be changed to a no-op by the OS anyhow. 
42195       */
42196       rc = syncJournal(pPager, 0);
42197       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42198   
42199       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42200       if( rc!=SQLITE_OK ){
42201         assert( rc!=SQLITE_IOERR_BLOCKED );
42202         goto commit_phase_one_exit;
42203       }
42204       sqlite3PcacheCleanAll(pPager->pPCache);
42205   
42206       /* If the file on disk is not the same size as the database image,
42207       ** then use pager_truncate to grow or shrink the file here.
42208       */
42209       if( pPager->dbSize!=pPager->dbFileSize ){
42210         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42211         assert( pPager->eState==PAGER_WRITER_DBMOD );
42212         rc = pager_truncate(pPager, nNew);
42213         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42214       }
42215   
42216       /* Finally, sync the database file. */
42217       if( !noSync ){
42218         rc = sqlite3PagerSync(pPager);
42219       }
42220       IOTRACE(("DBSYNC %p\n", pPager))
42221     }
42222   }
42223
42224 commit_phase_one_exit:
42225   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42226     pPager->eState = PAGER_WRITER_FINISHED;
42227   }
42228   return rc;
42229 }
42230
42231
42232 /*
42233 ** When this function is called, the database file has been completely
42234 ** updated to reflect the changes made by the current transaction and
42235 ** synced to disk. The journal file still exists in the file-system 
42236 ** though, and if a failure occurs at this point it will eventually
42237 ** be used as a hot-journal and the current transaction rolled back.
42238 **
42239 ** This function finalizes the journal file, either by deleting, 
42240 ** truncating or partially zeroing it, so that it cannot be used 
42241 ** for hot-journal rollback. Once this is done the transaction is
42242 ** irrevocably committed.
42243 **
42244 ** If an error occurs, an IO error code is returned and the pager
42245 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42246 */
42247 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42248   int rc = SQLITE_OK;                  /* Return code */
42249
42250   /* This routine should not be called if a prior error has occurred.
42251   ** But if (due to a coding error elsewhere in the system) it does get
42252   ** called, just return the same error code without doing anything. */
42253   if( NEVER(pPager->errCode) ) return pPager->errCode;
42254
42255   assert( pPager->eState==PAGER_WRITER_LOCKED
42256        || pPager->eState==PAGER_WRITER_FINISHED
42257        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42258   );
42259   assert( assert_pager_state(pPager) );
42260
42261   /* An optimization. If the database was not actually modified during
42262   ** this transaction, the pager is running in exclusive-mode and is
42263   ** using persistent journals, then this function is a no-op.
42264   **
42265   ** The start of the journal file currently contains a single journal 
42266   ** header with the nRec field set to 0. If such a journal is used as
42267   ** a hot-journal during hot-journal rollback, 0 changes will be made
42268   ** to the database file. So there is no need to zero the journal 
42269   ** header. Since the pager is in exclusive mode, there is no need
42270   ** to drop any locks either.
42271   */
42272   if( pPager->eState==PAGER_WRITER_LOCKED 
42273    && pPager->exclusiveMode 
42274    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42275   ){
42276     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42277     pPager->eState = PAGER_READER;
42278     return SQLITE_OK;
42279   }
42280
42281   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42282   rc = pager_end_transaction(pPager, pPager->setMaster);
42283   return pager_error(pPager, rc);
42284 }
42285
42286 /*
42287 ** If a write transaction is open, then all changes made within the 
42288 ** transaction are reverted and the current write-transaction is closed.
42289 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42290 ** state if an error occurs.
42291 **
42292 ** If the pager is already in PAGER_ERROR state when this function is called,
42293 ** it returns Pager.errCode immediately. No work is performed in this case.
42294 **
42295 ** Otherwise, in rollback mode, this function performs two functions:
42296 **
42297 **   1) It rolls back the journal file, restoring all database file and 
42298 **      in-memory cache pages to the state they were in when the transaction
42299 **      was opened, and
42300 **
42301 **   2) It finalizes the journal file, so that it is not used for hot
42302 **      rollback at any point in the future.
42303 **
42304 ** Finalization of the journal file (task 2) is only performed if the 
42305 ** rollback is successful.
42306 **
42307 ** In WAL mode, all cache-entries containing data modified within the
42308 ** current transaction are either expelled from the cache or reverted to
42309 ** their pre-transaction state by re-reading data from the database or
42310 ** WAL files. The WAL transaction is then closed.
42311 */
42312 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42313   int rc = SQLITE_OK;                  /* Return code */
42314   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42315
42316   /* PagerRollback() is a no-op if called in READER or OPEN state. If
42317   ** the pager is already in the ERROR state, the rollback is not 
42318   ** attempted here. Instead, the error code is returned to the caller.
42319   */
42320   assert( assert_pager_state(pPager) );
42321   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42322   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42323
42324   if( pagerUseWal(pPager) ){
42325     int rc2;
42326     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42327     rc2 = pager_end_transaction(pPager, pPager->setMaster);
42328     if( rc==SQLITE_OK ) rc = rc2;
42329   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42330     int eState = pPager->eState;
42331     rc = pager_end_transaction(pPager, 0);
42332     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42333       /* This can happen using journal_mode=off. Move the pager to the error 
42334       ** state to indicate that the contents of the cache may not be trusted.
42335       ** Any active readers will get SQLITE_ABORT.
42336       */
42337       pPager->errCode = SQLITE_ABORT;
42338       pPager->eState = PAGER_ERROR;
42339       return rc;
42340     }
42341   }else{
42342     rc = pager_playback(pPager, 0);
42343   }
42344
42345   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42346   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42347
42348   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42349   ** cache. So call pager_error() on the way out to make any error persistent.
42350   */
42351   return pager_error(pPager, rc);
42352 }
42353
42354 /*
42355 ** Return TRUE if the database file is opened read-only.  Return FALSE
42356 ** if the database is (in theory) writable.
42357 */
42358 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42359   return pPager->readOnly;
42360 }
42361
42362 /*
42363 ** Return the number of references to the pager.
42364 */
42365 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42366   return sqlite3PcacheRefCount(pPager->pPCache);
42367 }
42368
42369 /*
42370 ** Return the approximate number of bytes of memory currently
42371 ** used by the pager and its associated cache.
42372 */
42373 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42374   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42375                                      + 5*sizeof(void*);
42376   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42377            + sqlite3MallocSize(pPager)
42378            + pPager->pageSize;
42379 }
42380
42381 /*
42382 ** Return the number of references to the specified page.
42383 */
42384 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42385   return sqlite3PcachePageRefcount(pPage);
42386 }
42387
42388 #ifdef SQLITE_TEST
42389 /*
42390 ** This routine is used for testing and analysis only.
42391 */
42392 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42393   static int a[11];
42394   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42395   a[1] = sqlite3PcachePagecount(pPager->pPCache);
42396   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42397   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42398   a[4] = pPager->eState;
42399   a[5] = pPager->errCode;
42400   a[6] = pPager->nHit;
42401   a[7] = pPager->nMiss;
42402   a[8] = 0;  /* Used to be pPager->nOvfl */
42403   a[9] = pPager->nRead;
42404   a[10] = pPager->nWrite;
42405   return a;
42406 }
42407 #endif
42408
42409 /*
42410 ** Return true if this is an in-memory pager.
42411 */
42412 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42413   return MEMDB;
42414 }
42415
42416 /*
42417 ** Check that there are at least nSavepoint savepoints open. If there are
42418 ** currently less than nSavepoints open, then open one or more savepoints
42419 ** to make up the difference. If the number of savepoints is already
42420 ** equal to nSavepoint, then this function is a no-op.
42421 **
42422 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
42423 ** occurs while opening the sub-journal file, then an IO error code is
42424 ** returned. Otherwise, SQLITE_OK.
42425 */
42426 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42427   int rc = SQLITE_OK;                       /* Return code */
42428   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
42429
42430   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42431   assert( assert_pager_state(pPager) );
42432
42433   if( nSavepoint>nCurrent && pPager->useJournal ){
42434     int ii;                                 /* Iterator variable */
42435     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
42436
42437     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42438     ** if the allocation fails. Otherwise, zero the new portion in case a 
42439     ** malloc failure occurs while populating it in the for(...) loop below.
42440     */
42441     aNew = (PagerSavepoint *)sqlite3Realloc(
42442         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42443     );
42444     if( !aNew ){
42445       return SQLITE_NOMEM;
42446     }
42447     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42448     pPager->aSavepoint = aNew;
42449
42450     /* Populate the PagerSavepoint structures just allocated. */
42451     for(ii=nCurrent; ii<nSavepoint; ii++){
42452       aNew[ii].nOrig = pPager->dbSize;
42453       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42454         aNew[ii].iOffset = pPager->journalOff;
42455       }else{
42456         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42457       }
42458       aNew[ii].iSubRec = pPager->nSubRec;
42459       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42460       if( !aNew[ii].pInSavepoint ){
42461         return SQLITE_NOMEM;
42462       }
42463       if( pagerUseWal(pPager) ){
42464         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42465       }
42466       pPager->nSavepoint = ii+1;
42467     }
42468     assert( pPager->nSavepoint==nSavepoint );
42469     assertTruncateConstraint(pPager);
42470   }
42471
42472   return rc;
42473 }
42474
42475 /*
42476 ** This function is called to rollback or release (commit) a savepoint.
42477 ** The savepoint to release or rollback need not be the most recently 
42478 ** created savepoint.
42479 **
42480 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42481 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42482 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42483 ** that have occurred since the specified savepoint was created.
42484 **
42485 ** The savepoint to rollback or release is identified by parameter 
42486 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
42487 ** (the first created). A value of (Pager.nSavepoint-1) means operate
42488 ** on the most recently created savepoint. If iSavepoint is greater than
42489 ** (Pager.nSavepoint-1), then this function is a no-op.
42490 **
42491 ** If a negative value is passed to this function, then the current
42492 ** transaction is rolled back. This is different to calling 
42493 ** sqlite3PagerRollback() because this function does not terminate
42494 ** the transaction or unlock the database, it just restores the 
42495 ** contents of the database to its original state. 
42496 **
42497 ** In any case, all savepoints with an index greater than iSavepoint 
42498 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42499 ** then savepoint iSavepoint is also destroyed.
42500 **
42501 ** This function may return SQLITE_NOMEM if a memory allocation fails,
42502 ** or an IO error code if an IO error occurs while rolling back a 
42503 ** savepoint. If no errors occur, SQLITE_OK is returned.
42504 */ 
42505 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42506   int rc = pPager->errCode;       /* Return code */
42507
42508   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42509   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42510
42511   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42512     int ii;            /* Iterator variable */
42513     int nNew;          /* Number of remaining savepoints after this op. */
42514
42515     /* Figure out how many savepoints will still be active after this
42516     ** operation. Store this value in nNew. Then free resources associated 
42517     ** with any savepoints that are destroyed by this operation.
42518     */
42519     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42520     for(ii=nNew; ii<pPager->nSavepoint; ii++){
42521       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42522     }
42523     pPager->nSavepoint = nNew;
42524
42525     /* If this is a release of the outermost savepoint, truncate 
42526     ** the sub-journal to zero bytes in size. */
42527     if( op==SAVEPOINT_RELEASE ){
42528       if( nNew==0 && isOpen(pPager->sjfd) ){
42529         /* Only truncate if it is an in-memory sub-journal. */
42530         if( sqlite3IsMemJournal(pPager->sjfd) ){
42531           rc = sqlite3OsTruncate(pPager->sjfd, 0);
42532           assert( rc==SQLITE_OK );
42533         }
42534         pPager->nSubRec = 0;
42535       }
42536     }
42537     /* Else this is a rollback operation, playback the specified savepoint.
42538     ** If this is a temp-file, it is possible that the journal file has
42539     ** not yet been opened. In this case there have been no changes to
42540     ** the database file, so the playback operation can be skipped.
42541     */
42542     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
42543       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
42544       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
42545       assert(rc!=SQLITE_DONE);
42546     }
42547   }
42548
42549   return rc;
42550 }
42551
42552 /*
42553 ** Return the full pathname of the database file.
42554 */
42555 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
42556   return pPager->zFilename;
42557 }
42558
42559 /*
42560 ** Return the VFS structure for the pager.
42561 */
42562 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
42563   return pPager->pVfs;
42564 }
42565
42566 /*
42567 ** Return the file handle for the database file associated
42568 ** with the pager.  This might return NULL if the file has
42569 ** not yet been opened.
42570 */
42571 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
42572   return pPager->fd;
42573 }
42574
42575 /*
42576 ** Return the full pathname of the journal file.
42577 */
42578 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
42579   return pPager->zJournal;
42580 }
42581
42582 /*
42583 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
42584 ** if fsync()s are executed normally.
42585 */
42586 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
42587   return pPager->noSync;
42588 }
42589
42590 #ifdef SQLITE_HAS_CODEC
42591 /*
42592 ** Set or retrieve the codec for this pager
42593 */
42594 SQLITE_PRIVATE void sqlite3PagerSetCodec(
42595   Pager *pPager,
42596   void *(*xCodec)(void*,void*,Pgno,int),
42597   void (*xCodecSizeChng)(void*,int,int),
42598   void (*xCodecFree)(void*),
42599   void *pCodec
42600 ){
42601   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42602   pPager->xCodec = pPager->memDb ? 0 : xCodec;
42603   pPager->xCodecSizeChng = xCodecSizeChng;
42604   pPager->xCodecFree = xCodecFree;
42605   pPager->pCodec = pCodec;
42606   pagerReportSize(pPager);
42607 }
42608 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
42609   return pPager->pCodec;
42610 }
42611 #endif
42612
42613 #ifndef SQLITE_OMIT_AUTOVACUUM
42614 /*
42615 ** Move the page pPg to location pgno in the file.
42616 **
42617 ** There must be no references to the page previously located at
42618 ** pgno (which we call pPgOld) though that page is allowed to be
42619 ** in cache.  If the page previously located at pgno is not already
42620 ** in the rollback journal, it is not put there by by this routine.
42621 **
42622 ** References to the page pPg remain valid. Updating any
42623 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
42624 ** allocated along with the page) is the responsibility of the caller.
42625 **
42626 ** A transaction must be active when this routine is called. It used to be
42627 ** required that a statement transaction was not active, but this restriction
42628 ** has been removed (CREATE INDEX needs to move a page when a statement
42629 ** transaction is active).
42630 **
42631 ** If the fourth argument, isCommit, is non-zero, then this page is being
42632 ** moved as part of a database reorganization just before the transaction 
42633 ** is being committed. In this case, it is guaranteed that the database page 
42634 ** pPg refers to will not be written to again within this transaction.
42635 **
42636 ** This function may return SQLITE_NOMEM or an IO error code if an error
42637 ** occurs. Otherwise, it returns SQLITE_OK.
42638 */
42639 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
42640   PgHdr *pPgOld;               /* The page being overwritten. */
42641   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
42642   int rc;                      /* Return code */
42643   Pgno origPgno;               /* The original page number */
42644
42645   assert( pPg->nRef>0 );
42646   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42647        || pPager->eState==PAGER_WRITER_DBMOD
42648   );
42649   assert( assert_pager_state(pPager) );
42650
42651   /* In order to be able to rollback, an in-memory database must journal
42652   ** the page we are moving from.
42653   */
42654   if( MEMDB ){
42655     rc = sqlite3PagerWrite(pPg);
42656     if( rc ) return rc;
42657   }
42658
42659   /* If the page being moved is dirty and has not been saved by the latest
42660   ** savepoint, then save the current contents of the page into the 
42661   ** sub-journal now. This is required to handle the following scenario:
42662   **
42663   **   BEGIN;
42664   **     <journal page X, then modify it in memory>
42665   **     SAVEPOINT one;
42666   **       <Move page X to location Y>
42667   **     ROLLBACK TO one;
42668   **
42669   ** If page X were not written to the sub-journal here, it would not
42670   ** be possible to restore its contents when the "ROLLBACK TO one"
42671   ** statement were is processed.
42672   **
42673   ** subjournalPage() may need to allocate space to store pPg->pgno into
42674   ** one or more savepoint bitvecs. This is the reason this function
42675   ** may return SQLITE_NOMEM.
42676   */
42677   if( pPg->flags&PGHDR_DIRTY
42678    && subjRequiresPage(pPg)
42679    && SQLITE_OK!=(rc = subjournalPage(pPg))
42680   ){
42681     return rc;
42682   }
42683
42684   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
42685       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
42686   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
42687
42688   /* If the journal needs to be sync()ed before page pPg->pgno can
42689   ** be written to, store pPg->pgno in local variable needSyncPgno.
42690   **
42691   ** If the isCommit flag is set, there is no need to remember that
42692   ** the journal needs to be sync()ed before database page pPg->pgno 
42693   ** can be written to. The caller has already promised not to write to it.
42694   */
42695   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
42696     needSyncPgno = pPg->pgno;
42697     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
42698     assert( pPg->flags&PGHDR_DIRTY );
42699   }
42700
42701   /* If the cache contains a page with page-number pgno, remove it
42702   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
42703   ** page pgno before the 'move' operation, it needs to be retained 
42704   ** for the page moved there.
42705   */
42706   pPg->flags &= ~PGHDR_NEED_SYNC;
42707   pPgOld = pager_lookup(pPager, pgno);
42708   assert( !pPgOld || pPgOld->nRef==1 );
42709   if( pPgOld ){
42710     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
42711     if( MEMDB ){
42712       /* Do not discard pages from an in-memory database since we might
42713       ** need to rollback later.  Just move the page out of the way. */
42714       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
42715     }else{
42716       sqlite3PcacheDrop(pPgOld);
42717     }
42718   }
42719
42720   origPgno = pPg->pgno;
42721   sqlite3PcacheMove(pPg, pgno);
42722   sqlite3PcacheMakeDirty(pPg);
42723
42724   /* For an in-memory database, make sure the original page continues
42725   ** to exist, in case the transaction needs to roll back.  Use pPgOld
42726   ** as the original page since it has already been allocated.
42727   */
42728   if( MEMDB ){
42729     assert( pPgOld );
42730     sqlite3PcacheMove(pPgOld, origPgno);
42731     sqlite3PagerUnref(pPgOld);
42732   }
42733
42734   if( needSyncPgno ){
42735     /* If needSyncPgno is non-zero, then the journal file needs to be 
42736     ** sync()ed before any data is written to database file page needSyncPgno.
42737     ** Currently, no such page exists in the page-cache and the 
42738     ** "is journaled" bitvec flag has been set. This needs to be remedied by
42739     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
42740     ** flag.
42741     **
42742     ** If the attempt to load the page into the page-cache fails, (due
42743     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
42744     ** array. Otherwise, if the page is loaded and written again in
42745     ** this transaction, it may be written to the database file before
42746     ** it is synced into the journal file. This way, it may end up in
42747     ** the journal file twice, but that is not a problem.
42748     */
42749     PgHdr *pPgHdr;
42750     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
42751     if( rc!=SQLITE_OK ){
42752       if( needSyncPgno<=pPager->dbOrigSize ){
42753         assert( pPager->pTmpSpace!=0 );
42754         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
42755       }
42756       return rc;
42757     }
42758     pPgHdr->flags |= PGHDR_NEED_SYNC;
42759     sqlite3PcacheMakeDirty(pPgHdr);
42760     sqlite3PagerUnref(pPgHdr);
42761   }
42762
42763   return SQLITE_OK;
42764 }
42765 #endif
42766
42767 /*
42768 ** Return a pointer to the data for the specified page.
42769 */
42770 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
42771   assert( pPg->nRef>0 || pPg->pPager->memDb );
42772   return pPg->pData;
42773 }
42774
42775 /*
42776 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
42777 ** allocated along with the specified page.
42778 */
42779 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
42780   return pPg->pExtra;
42781 }
42782
42783 /*
42784 ** Get/set the locking-mode for this pager. Parameter eMode must be one
42785 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
42786 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
42787 ** the locking-mode is set to the value specified.
42788 **
42789 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
42790 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
42791 ** locking-mode.
42792 */
42793 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
42794   assert( eMode==PAGER_LOCKINGMODE_QUERY
42795             || eMode==PAGER_LOCKINGMODE_NORMAL
42796             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
42797   assert( PAGER_LOCKINGMODE_QUERY<0 );
42798   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
42799   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
42800   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
42801     pPager->exclusiveMode = (u8)eMode;
42802   }
42803   return (int)pPager->exclusiveMode;
42804 }
42805
42806 /*
42807 ** Set the journal-mode for this pager. Parameter eMode must be one of:
42808 **
42809 **    PAGER_JOURNALMODE_DELETE
42810 **    PAGER_JOURNALMODE_TRUNCATE
42811 **    PAGER_JOURNALMODE_PERSIST
42812 **    PAGER_JOURNALMODE_OFF
42813 **    PAGER_JOURNALMODE_MEMORY
42814 **    PAGER_JOURNALMODE_WAL
42815 **
42816 ** The journalmode is set to the value specified if the change is allowed.
42817 ** The change may be disallowed for the following reasons:
42818 **
42819 **   *  An in-memory database can only have its journal_mode set to _OFF
42820 **      or _MEMORY.
42821 **
42822 **   *  Temporary databases cannot have _WAL journalmode.
42823 **
42824 ** The returned indicate the current (possibly updated) journal-mode.
42825 */
42826 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
42827   u8 eOld = pPager->journalMode;    /* Prior journalmode */
42828
42829 #ifdef SQLITE_DEBUG
42830   /* The print_pager_state() routine is intended to be used by the debugger
42831   ** only.  We invoke it once here to suppress a compiler warning. */
42832   print_pager_state(pPager);
42833 #endif
42834
42835
42836   /* The eMode parameter is always valid */
42837   assert(      eMode==PAGER_JOURNALMODE_DELETE
42838             || eMode==PAGER_JOURNALMODE_TRUNCATE
42839             || eMode==PAGER_JOURNALMODE_PERSIST
42840             || eMode==PAGER_JOURNALMODE_OFF 
42841             || eMode==PAGER_JOURNALMODE_WAL 
42842             || eMode==PAGER_JOURNALMODE_MEMORY );
42843
42844   /* This routine is only called from the OP_JournalMode opcode, and
42845   ** the logic there will never allow a temporary file to be changed
42846   ** to WAL mode.
42847   */
42848   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
42849
42850   /* Do allow the journalmode of an in-memory database to be set to
42851   ** anything other than MEMORY or OFF
42852   */
42853   if( MEMDB ){
42854     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
42855     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
42856       eMode = eOld;
42857     }
42858   }
42859
42860   if( eMode!=eOld ){
42861
42862     /* Change the journal mode. */
42863     assert( pPager->eState!=PAGER_ERROR );
42864     pPager->journalMode = (u8)eMode;
42865
42866     /* When transistioning from TRUNCATE or PERSIST to any other journal
42867     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
42868     ** delete the journal file.
42869     */
42870     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42871     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
42872     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
42873     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
42874     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
42875     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
42876
42877     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
42878     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
42879
42880       /* In this case we would like to delete the journal file. If it is
42881       ** not possible, then that is not a problem. Deleting the journal file
42882       ** here is an optimization only.
42883       **
42884       ** Before deleting the journal file, obtain a RESERVED lock on the
42885       ** database file. This ensures that the journal file is not deleted
42886       ** while it is in use by some other client.
42887       */
42888       sqlite3OsClose(pPager->jfd);
42889       if( pPager->eLock>=RESERVED_LOCK ){
42890         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42891       }else{
42892         int rc = SQLITE_OK;
42893         int state = pPager->eState;
42894         assert( state==PAGER_OPEN || state==PAGER_READER );
42895         if( state==PAGER_OPEN ){
42896           rc = sqlite3PagerSharedLock(pPager);
42897         }
42898         if( pPager->eState==PAGER_READER ){
42899           assert( rc==SQLITE_OK );
42900           rc = pagerLockDb(pPager, RESERVED_LOCK);
42901         }
42902         if( rc==SQLITE_OK ){
42903           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42904         }
42905         if( rc==SQLITE_OK && state==PAGER_READER ){
42906           pagerUnlockDb(pPager, SHARED_LOCK);
42907         }else if( state==PAGER_OPEN ){
42908           pager_unlock(pPager);
42909         }
42910         assert( state==pPager->eState );
42911       }
42912     }
42913   }
42914
42915   /* Return the new journal mode */
42916   return (int)pPager->journalMode;
42917 }
42918
42919 /*
42920 ** Return the current journal mode.
42921 */
42922 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
42923   return (int)pPager->journalMode;
42924 }
42925
42926 /*
42927 ** Return TRUE if the pager is in a state where it is OK to change the
42928 ** journalmode.  Journalmode changes can only happen when the database
42929 ** is unmodified.
42930 */
42931 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
42932   assert( assert_pager_state(pPager) );
42933   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
42934   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
42935   return 1;
42936 }
42937
42938 /*
42939 ** Get/set the size-limit used for persistent journal files.
42940 **
42941 ** Setting the size limit to -1 means no limit is enforced.
42942 ** An attempt to set a limit smaller than -1 is a no-op.
42943 */
42944 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
42945   if( iLimit>=-1 ){
42946     pPager->journalSizeLimit = iLimit;
42947   }
42948   return pPager->journalSizeLimit;
42949 }
42950
42951 /*
42952 ** Return a pointer to the pPager->pBackup variable. The backup module
42953 ** in backup.c maintains the content of this variable. This module
42954 ** uses it opaquely as an argument to sqlite3BackupRestart() and
42955 ** sqlite3BackupUpdate() only.
42956 */
42957 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
42958   return &pPager->pBackup;
42959 }
42960
42961 #ifndef SQLITE_OMIT_WAL
42962 /*
42963 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
42964 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
42965 ** or wal_blocking_checkpoint() API functions.
42966 **
42967 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
42968 */
42969 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
42970   int rc = SQLITE_OK;
42971   if( pPager->pWal ){
42972     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
42973         pPager->xBusyHandler, pPager->pBusyHandlerArg,
42974         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
42975         pnLog, pnCkpt
42976     );
42977   }
42978   return rc;
42979 }
42980
42981 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
42982   return sqlite3WalCallback(pPager->pWal);
42983 }
42984
42985 /*
42986 ** Return true if the underlying VFS for the given pager supports the
42987 ** primitives necessary for write-ahead logging.
42988 */
42989 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
42990   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
42991   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
42992 }
42993
42994 /*
42995 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
42996 ** is obtained instead, immediately release it.
42997 */
42998 static int pagerExclusiveLock(Pager *pPager){
42999   int rc;                         /* Return code */
43000
43001   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43002   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43003   if( rc!=SQLITE_OK ){
43004     /* If the attempt to grab the exclusive lock failed, release the 
43005     ** pending lock that may have been obtained instead.  */
43006     pagerUnlockDb(pPager, SHARED_LOCK);
43007   }
43008
43009   return rc;
43010 }
43011
43012 /*
43013 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
43014 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43015 ** lock on the database file and use heap-memory to store the wal-index
43016 ** in. Otherwise, use the normal shared-memory.
43017 */
43018 static int pagerOpenWal(Pager *pPager){
43019   int rc = SQLITE_OK;
43020
43021   assert( pPager->pWal==0 && pPager->tempFile==0 );
43022   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43023
43024   /* If the pager is already in exclusive-mode, the WAL module will use 
43025   ** heap-memory for the wal-index instead of the VFS shared-memory 
43026   ** implementation. Take the exclusive lock now, before opening the WAL
43027   ** file, to make sure this is safe.
43028   */
43029   if( pPager->exclusiveMode ){
43030     rc = pagerExclusiveLock(pPager);
43031   }
43032
43033   /* Open the connection to the log file. If this operation fails, 
43034   ** (e.g. due to malloc() failure), return an error code.
43035   */
43036   if( rc==SQLITE_OK ){
43037     rc = sqlite3WalOpen(pPager->pVfs, 
43038         pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
43039     );
43040   }
43041
43042   return rc;
43043 }
43044
43045
43046 /*
43047 ** The caller must be holding a SHARED lock on the database file to call
43048 ** this function.
43049 **
43050 ** If the pager passed as the first argument is open on a real database
43051 ** file (not a temp file or an in-memory database), and the WAL file
43052 ** is not already open, make an attempt to open it now. If successful,
43053 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
43054 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43055 ** not modified in either case.
43056 **
43057 ** If the pager is open on a temp-file (or in-memory database), or if
43058 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43059 ** without doing anything.
43060 */
43061 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43062   Pager *pPager,                  /* Pager object */
43063   int *pbOpen                     /* OUT: Set to true if call is a no-op */
43064 ){
43065   int rc = SQLITE_OK;             /* Return code */
43066
43067   assert( assert_pager_state(pPager) );
43068   assert( pPager->eState==PAGER_OPEN   || pbOpen );
43069   assert( pPager->eState==PAGER_READER || !pbOpen );
43070   assert( pbOpen==0 || *pbOpen==0 );
43071   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43072
43073   if( !pPager->tempFile && !pPager->pWal ){
43074     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43075
43076     /* Close any rollback journal previously open */
43077     sqlite3OsClose(pPager->jfd);
43078
43079     rc = pagerOpenWal(pPager);
43080     if( rc==SQLITE_OK ){
43081       pPager->journalMode = PAGER_JOURNALMODE_WAL;
43082       pPager->eState = PAGER_OPEN;
43083     }
43084   }else{
43085     *pbOpen = 1;
43086   }
43087
43088   return rc;
43089 }
43090
43091 /*
43092 ** This function is called to close the connection to the log file prior
43093 ** to switching from WAL to rollback mode.
43094 **
43095 ** Before closing the log file, this function attempts to take an 
43096 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43097 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43098 ** If successful, the EXCLUSIVE lock is not released before returning.
43099 */
43100 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43101   int rc = SQLITE_OK;
43102
43103   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43104
43105   /* If the log file is not already open, but does exist in the file-system,
43106   ** it may need to be checkpointed before the connection can switch to
43107   ** rollback mode. Open it now so this can happen.
43108   */
43109   if( !pPager->pWal ){
43110     int logexists = 0;
43111     rc = pagerLockDb(pPager, SHARED_LOCK);
43112     if( rc==SQLITE_OK ){
43113       rc = sqlite3OsAccess(
43114           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43115       );
43116     }
43117     if( rc==SQLITE_OK && logexists ){
43118       rc = pagerOpenWal(pPager);
43119     }
43120   }
43121     
43122   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43123   ** the database file, the log and log-summary files will be deleted.
43124   */
43125   if( rc==SQLITE_OK && pPager->pWal ){
43126     rc = pagerExclusiveLock(pPager);
43127     if( rc==SQLITE_OK ){
43128       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43129                            pPager->pageSize, (u8*)pPager->pTmpSpace);
43130       pPager->pWal = 0;
43131     }
43132   }
43133   return rc;
43134 }
43135
43136 #ifdef SQLITE_HAS_CODEC
43137 /*
43138 ** This function is called by the wal module when writing page content
43139 ** into the log file.
43140 **
43141 ** This function returns a pointer to a buffer containing the encrypted
43142 ** page content. If a malloc fails, this function may return NULL.
43143 */
43144 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43145   void *aData = 0;
43146   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43147   return aData;
43148 }
43149 #endif /* SQLITE_HAS_CODEC */
43150
43151 #endif /* !SQLITE_OMIT_WAL */
43152
43153 #endif /* SQLITE_OMIT_DISKIO */
43154
43155 /************** End of pager.c ***********************************************/
43156 /************** Begin file wal.c *********************************************/
43157 /*
43158 ** 2010 February 1
43159 **
43160 ** The author disclaims copyright to this source code.  In place of
43161 ** a legal notice, here is a blessing:
43162 **
43163 **    May you do good and not evil.
43164 **    May you find forgiveness for yourself and forgive others.
43165 **    May you share freely, never taking more than you give.
43166 **
43167 *************************************************************************
43168 **
43169 ** This file contains the implementation of a write-ahead log (WAL) used in 
43170 ** "journal_mode=WAL" mode.
43171 **
43172 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43173 **
43174 ** A WAL file consists of a header followed by zero or more "frames".
43175 ** Each frame records the revised content of a single page from the
43176 ** database file.  All changes to the database are recorded by writing
43177 ** frames into the WAL.  Transactions commit when a frame is written that
43178 ** contains a commit marker.  A single WAL can and usually does record 
43179 ** multiple transactions.  Periodically, the content of the WAL is
43180 ** transferred back into the database file in an operation called a
43181 ** "checkpoint".
43182 **
43183 ** A single WAL file can be used multiple times.  In other words, the
43184 ** WAL can fill up with frames and then be checkpointed and then new
43185 ** frames can overwrite the old ones.  A WAL always grows from beginning
43186 ** toward the end.  Checksums and counters attached to each frame are
43187 ** used to determine which frames within the WAL are valid and which
43188 ** are leftovers from prior checkpoints.
43189 **
43190 ** The WAL header is 32 bytes in size and consists of the following eight
43191 ** big-endian 32-bit unsigned integer values:
43192 **
43193 **     0: Magic number.  0x377f0682 or 0x377f0683
43194 **     4: File format version.  Currently 3007000
43195 **     8: Database page size.  Example: 1024
43196 **    12: Checkpoint sequence number
43197 **    16: Salt-1, random integer incremented with each checkpoint
43198 **    20: Salt-2, a different random integer changing with each ckpt
43199 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
43200 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
43201 **
43202 ** Immediately following the wal-header are zero or more frames. Each
43203 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43204 ** of page data. The frame-header is six big-endian 32-bit unsigned 
43205 ** integer values, as follows:
43206 **
43207 **     0: Page number.
43208 **     4: For commit records, the size of the database image in pages 
43209 **        after the commit. For all other records, zero.
43210 **     8: Salt-1 (copied from the header)
43211 **    12: Salt-2 (copied from the header)
43212 **    16: Checksum-1.
43213 **    20: Checksum-2.
43214 **
43215 ** A frame is considered valid if and only if the following conditions are
43216 ** true:
43217 **
43218 **    (1) The salt-1 and salt-2 values in the frame-header match
43219 **        salt values in the wal-header
43220 **
43221 **    (2) The checksum values in the final 8 bytes of the frame-header
43222 **        exactly match the checksum computed consecutively on the
43223 **        WAL header and the first 8 bytes and the content of all frames
43224 **        up to and including the current frame.
43225 **
43226 ** The checksum is computed using 32-bit big-endian integers if the
43227 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43228 ** is computed using little-endian if the magic number is 0x377f0682.
43229 ** The checksum values are always stored in the frame header in a
43230 ** big-endian format regardless of which byte order is used to compute
43231 ** the checksum.  The checksum is computed by interpreting the input as
43232 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
43233 ** algorithm used for the checksum is as follows:
43234 ** 
43235 **   for i from 0 to n-1 step 2:
43236 **     s0 += x[i] + s1;
43237 **     s1 += x[i+1] + s0;
43238 **   endfor
43239 **
43240 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43241 ** in reverse order (the largest fibonacci weight occurs on the first element
43242 ** of the sequence being summed.)  The s1 value spans all 32-bit 
43243 ** terms of the sequence whereas s0 omits the final term.
43244 **
43245 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43246 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43247 ** The VFS.xSync operations serve as write barriers - all writes launched
43248 ** before the xSync must complete before any write that launches after the
43249 ** xSync begins.
43250 **
43251 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43252 ** value is randomized.  This prevents old and new frames in the WAL from
43253 ** being considered valid at the same time and being checkpointing together
43254 ** following a crash.
43255 **
43256 ** READER ALGORITHM
43257 **
43258 ** To read a page from the database (call it page number P), a reader
43259 ** first checks the WAL to see if it contains page P.  If so, then the
43260 ** last valid instance of page P that is a followed by a commit frame
43261 ** or is a commit frame itself becomes the value read.  If the WAL
43262 ** contains no copies of page P that are valid and which are a commit
43263 ** frame or are followed by a commit frame, then page P is read from
43264 ** the database file.
43265 **
43266 ** To start a read transaction, the reader records the index of the last
43267 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
43268 ** for all subsequent read operations.  New transactions can be appended
43269 ** to the WAL, but as long as the reader uses its original mxFrame value
43270 ** and ignores the newly appended content, it will see a consistent snapshot
43271 ** of the database from a single point in time.  This technique allows
43272 ** multiple concurrent readers to view different versions of the database
43273 ** content simultaneously.
43274 **
43275 ** The reader algorithm in the previous paragraphs works correctly, but 
43276 ** because frames for page P can appear anywhere within the WAL, the
43277 ** reader has to scan the entire WAL looking for page P frames.  If the
43278 ** WAL is large (multiple megabytes is typical) that scan can be slow,
43279 ** and read performance suffers.  To overcome this problem, a separate
43280 ** data structure called the wal-index is maintained to expedite the
43281 ** search for frames of a particular page.
43282 ** 
43283 ** WAL-INDEX FORMAT
43284 **
43285 ** Conceptually, the wal-index is shared memory, though VFS implementations
43286 ** might choose to implement the wal-index using a mmapped file.  Because
43287 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
43288 ** on a network filesystem.  All users of the database must be able to
43289 ** share memory.
43290 **
43291 ** The wal-index is transient.  After a crash, the wal-index can (and should
43292 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
43293 ** to either truncate or zero the header of the wal-index when the last
43294 ** connection to it closes.  Because the wal-index is transient, it can
43295 ** use an architecture-specific format; it does not have to be cross-platform.
43296 ** Hence, unlike the database and WAL file formats which store all values
43297 ** as big endian, the wal-index can store multi-byte values in the native
43298 ** byte order of the host computer.
43299 **
43300 ** The purpose of the wal-index is to answer this question quickly:  Given
43301 ** a page number P, return the index of the last frame for page P in the WAL,
43302 ** or return NULL if there are no frames for page P in the WAL.
43303 **
43304 ** The wal-index consists of a header region, followed by an one or
43305 ** more index blocks.  
43306 **
43307 ** The wal-index header contains the total number of frames within the WAL
43308 ** in the the mxFrame field.  
43309 **
43310 ** Each index block except for the first contains information on 
43311 ** HASHTABLE_NPAGE frames. The first index block contains information on
43312 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
43313 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
43314 ** first index block are the same size as all other index blocks in the
43315 ** wal-index.
43316 **
43317 ** Each index block contains two sections, a page-mapping that contains the
43318 ** database page number associated with each wal frame, and a hash-table 
43319 ** that allows readers to query an index block for a specific page number.
43320 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43321 ** for the first index block) 32-bit page numbers. The first entry in the 
43322 ** first index-block contains the database page number corresponding to the
43323 ** first frame in the WAL file. The first entry in the second index block
43324 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43325 ** the log, and so on.
43326 **
43327 ** The last index block in a wal-index usually contains less than the full
43328 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43329 ** depending on the contents of the WAL file. This does not change the
43330 ** allocated size of the page-mapping array - the page-mapping array merely
43331 ** contains unused entries.
43332 **
43333 ** Even without using the hash table, the last frame for page P
43334 ** can be found by scanning the page-mapping sections of each index block
43335 ** starting with the last index block and moving toward the first, and
43336 ** within each index block, starting at the end and moving toward the
43337 ** beginning.  The first entry that equals P corresponds to the frame
43338 ** holding the content for that page.
43339 **
43340 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43341 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43342 ** hash table for each page number in the mapping section, so the hash 
43343 ** table is never more than half full.  The expected number of collisions 
43344 ** prior to finding a match is 1.  Each entry of the hash table is an
43345 ** 1-based index of an entry in the mapping section of the same
43346 ** index block.   Let K be the 1-based index of the largest entry in
43347 ** the mapping section.  (For index blocks other than the last, K will
43348 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43349 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
43350 ** contain a value of 0.
43351 **
43352 ** To look for page P in the hash table, first compute a hash iKey on
43353 ** P as follows:
43354 **
43355 **      iKey = (P * 383) % HASHTABLE_NSLOT
43356 **
43357 ** Then start scanning entries of the hash table, starting with iKey
43358 ** (wrapping around to the beginning when the end of the hash table is
43359 ** reached) until an unused hash slot is found. Let the first unused slot
43360 ** be at index iUnused.  (iUnused might be less than iKey if there was
43361 ** wrap-around.) Because the hash table is never more than half full,
43362 ** the search is guaranteed to eventually hit an unused entry.  Let 
43363 ** iMax be the value between iKey and iUnused, closest to iUnused,
43364 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
43365 ** no hash slot such that aHash[i]==p) then page P is not in the
43366 ** current index block.  Otherwise the iMax-th mapping entry of the
43367 ** current index block corresponds to the last entry that references 
43368 ** page P.
43369 **
43370 ** A hash search begins with the last index block and moves toward the
43371 ** first index block, looking for entries corresponding to page P.  On
43372 ** average, only two or three slots in each index block need to be
43373 ** examined in order to either find the last entry for page P, or to
43374 ** establish that no such entry exists in the block.  Each index block
43375 ** holds over 4000 entries.  So two or three index blocks are sufficient
43376 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
43377 ** comparisons (on average) suffice to either locate a frame in the
43378 ** WAL or to establish that the frame does not exist in the WAL.  This
43379 ** is much faster than scanning the entire 10MB WAL.
43380 **
43381 ** Note that entries are added in order of increasing K.  Hence, one
43382 ** reader might be using some value K0 and a second reader that started
43383 ** at a later time (after additional transactions were added to the WAL
43384 ** and to the wal-index) might be using a different value K1, where K1>K0.
43385 ** Both readers can use the same hash table and mapping section to get
43386 ** the correct result.  There may be entries in the hash table with
43387 ** K>K0 but to the first reader, those entries will appear to be unused
43388 ** slots in the hash table and so the first reader will get an answer as
43389 ** if no values greater than K0 had ever been inserted into the hash table
43390 ** in the first place - which is what reader one wants.  Meanwhile, the
43391 ** second reader using K1 will see additional values that were inserted
43392 ** later, which is exactly what reader two wants.  
43393 **
43394 ** When a rollback occurs, the value of K is decreased. Hash table entries
43395 ** that correspond to frames greater than the new K value are removed
43396 ** from the hash table at this point.
43397 */
43398 #ifndef SQLITE_OMIT_WAL
43399
43400
43401 /*
43402 ** Trace output macros
43403 */
43404 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43405 SQLITE_PRIVATE int sqlite3WalTrace = 0;
43406 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
43407 #else
43408 # define WALTRACE(X)
43409 #endif
43410
43411 /*
43412 ** The maximum (and only) versions of the wal and wal-index formats
43413 ** that may be interpreted by this version of SQLite.
43414 **
43415 ** If a client begins recovering a WAL file and finds that (a) the checksum
43416 ** values in the wal-header are correct and (b) the version field is not
43417 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43418 **
43419 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
43420 ** checksum test is successful) and finds that the version field is not
43421 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43422 ** returns SQLITE_CANTOPEN.
43423 */
43424 #define WAL_MAX_VERSION      3007000
43425 #define WALINDEX_MAX_VERSION 3007000
43426
43427 /*
43428 ** Indices of various locking bytes.   WAL_NREADER is the number
43429 ** of available reader locks and should be at least 3.
43430 */
43431 #define WAL_WRITE_LOCK         0
43432 #define WAL_ALL_BUT_WRITE      1
43433 #define WAL_CKPT_LOCK          1
43434 #define WAL_RECOVER_LOCK       2
43435 #define WAL_READ_LOCK(I)       (3+(I))
43436 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
43437
43438
43439 /* Object declarations */
43440 typedef struct WalIndexHdr WalIndexHdr;
43441 typedef struct WalIterator WalIterator;
43442 typedef struct WalCkptInfo WalCkptInfo;
43443
43444
43445 /*
43446 ** The following object holds a copy of the wal-index header content.
43447 **
43448 ** The actual header in the wal-index consists of two copies of this
43449 ** object.
43450 **
43451 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43452 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
43453 ** added in 3.7.1 when support for 64K pages was added.  
43454 */
43455 struct WalIndexHdr {
43456   u32 iVersion;                   /* Wal-index version */
43457   u32 unused;                     /* Unused (padding) field */
43458   u32 iChange;                    /* Counter incremented each transaction */
43459   u8 isInit;                      /* 1 when initialized */
43460   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
43461   u16 szPage;                     /* Database page size in bytes. 1==64K */
43462   u32 mxFrame;                    /* Index of last valid frame in the WAL */
43463   u32 nPage;                      /* Size of database in pages */
43464   u32 aFrameCksum[2];             /* Checksum of last frame in log */
43465   u32 aSalt[2];                   /* Two salt values copied from WAL header */
43466   u32 aCksum[2];                  /* Checksum over all prior fields */
43467 };
43468
43469 /*
43470 ** A copy of the following object occurs in the wal-index immediately
43471 ** following the second copy of the WalIndexHdr.  This object stores
43472 ** information used by checkpoint.
43473 **
43474 ** nBackfill is the number of frames in the WAL that have been written
43475 ** back into the database. (We call the act of moving content from WAL to
43476 ** database "backfilling".)  The nBackfill number is never greater than
43477 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
43478 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43479 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43480 ** mxFrame back to zero when the WAL is reset.
43481 **
43482 ** There is one entry in aReadMark[] for each reader lock.  If a reader
43483 ** holds read-lock K, then the value in aReadMark[K] is no greater than
43484 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
43485 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
43486 ** a special case; its value is never used and it exists as a place-holder
43487 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
43488 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43489 ** directly from the database.
43490 **
43491 ** The value of aReadMark[K] may only be changed by a thread that
43492 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
43493 ** aReadMark[K] cannot changed while there is a reader is using that mark
43494 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43495 **
43496 ** The checkpointer may only transfer frames from WAL to database where
43497 ** the frame numbers are less than or equal to every aReadMark[] that is
43498 ** in use (that is, every aReadMark[j] for which there is a corresponding
43499 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
43500 ** largest value and will increase an unused aReadMark[] to mxFrame if there
43501 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
43502 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
43503 ** in the WAL has been backfilled into the database) then new readers
43504 ** will choose aReadMark[0] which has value 0 and hence such reader will
43505 ** get all their all content directly from the database file and ignore 
43506 ** the WAL.
43507 **
43508 ** Writers normally append new frames to the end of the WAL.  However,
43509 ** if nBackfill equals mxFrame (meaning that all WAL content has been
43510 ** written back into the database) and if no readers are using the WAL
43511 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43512 ** the writer will first "reset" the WAL back to the beginning and start
43513 ** writing new content beginning at frame 1.
43514 **
43515 ** We assume that 32-bit loads are atomic and so no locks are needed in
43516 ** order to read from any aReadMark[] entries.
43517 */
43518 struct WalCkptInfo {
43519   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
43520   u32 aReadMark[WAL_NREADER];     /* Reader marks */
43521 };
43522 #define READMARK_NOT_USED  0xffffffff
43523
43524
43525 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43526 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43527 ** only support mandatory file-locks, we do not read or write data
43528 ** from the region of the file on which locks are applied.
43529 */
43530 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43531 #define WALINDEX_LOCK_RESERVED 16
43532 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
43533
43534 /* Size of header before each frame in wal */
43535 #define WAL_FRAME_HDRSIZE 24
43536
43537 /* Size of write ahead log header, including checksum. */
43538 /* #define WAL_HDRSIZE 24 */
43539 #define WAL_HDRSIZE 32
43540
43541 /* WAL magic value. Either this value, or the same value with the least
43542 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
43543 ** big-endian format in the first 4 bytes of a WAL file.
43544 **
43545 ** If the LSB is set, then the checksums for each frame within the WAL
43546 ** file are calculated by treating all data as an array of 32-bit 
43547 ** big-endian words. Otherwise, they are calculated by interpreting 
43548 ** all data as 32-bit little-endian words.
43549 */
43550 #define WAL_MAGIC 0x377f0682
43551
43552 /*
43553 ** Return the offset of frame iFrame in the write-ahead log file, 
43554 ** assuming a database page size of szPage bytes. The offset returned
43555 ** is to the start of the write-ahead log frame-header.
43556 */
43557 #define walFrameOffset(iFrame, szPage) (                               \
43558   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
43559 )
43560
43561 /*
43562 ** An open write-ahead log file is represented by an instance of the
43563 ** following object.
43564 */
43565 struct Wal {
43566   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
43567   sqlite3_file *pDbFd;       /* File handle for the database file */
43568   sqlite3_file *pWalFd;      /* File handle for WAL file */
43569   u32 iCallback;             /* Value to pass to log callback (or 0) */
43570   int nWiData;               /* Size of array apWiData */
43571   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
43572   u32 szPage;                /* Database page size */
43573   i16 readLock;              /* Which read lock is being held.  -1 for none */
43574   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
43575   u8 writeLock;              /* True if in a write transaction */
43576   u8 ckptLock;               /* True if holding a checkpoint lock */
43577   u8 readOnly;               /* True if the WAL file is open read-only */
43578   WalIndexHdr hdr;           /* Wal-index header for current transaction */
43579   const char *zWalName;      /* Name of WAL file */
43580   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
43581 #ifdef SQLITE_DEBUG
43582   u8 lockError;              /* True if a locking error has occurred */
43583 #endif
43584 };
43585
43586 /*
43587 ** Candidate values for Wal.exclusiveMode.
43588 */
43589 #define WAL_NORMAL_MODE     0
43590 #define WAL_EXCLUSIVE_MODE  1     
43591 #define WAL_HEAPMEMORY_MODE 2
43592
43593 /*
43594 ** Each page of the wal-index mapping contains a hash-table made up of
43595 ** an array of HASHTABLE_NSLOT elements of the following type.
43596 */
43597 typedef u16 ht_slot;
43598
43599 /*
43600 ** This structure is used to implement an iterator that loops through
43601 ** all frames in the WAL in database page order. Where two or more frames
43602 ** correspond to the same database page, the iterator visits only the 
43603 ** frame most recently written to the WAL (in other words, the frame with
43604 ** the largest index).
43605 **
43606 ** The internals of this structure are only accessed by:
43607 **
43608 **   walIteratorInit() - Create a new iterator,
43609 **   walIteratorNext() - Step an iterator,
43610 **   walIteratorFree() - Free an iterator.
43611 **
43612 ** This functionality is used by the checkpoint code (see walCheckpoint()).
43613 */
43614 struct WalIterator {
43615   int iPrior;                     /* Last result returned from the iterator */
43616   int nSegment;                   /* Number of entries in aSegment[] */
43617   struct WalSegment {
43618     int iNext;                    /* Next slot in aIndex[] not yet returned */
43619     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
43620     u32 *aPgno;                   /* Array of page numbers. */
43621     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
43622     int iZero;                    /* Frame number associated with aPgno[0] */
43623   } aSegment[1];                  /* One for every 32KB page in the wal-index */
43624 };
43625
43626 /*
43627 ** Define the parameters of the hash tables in the wal-index file. There
43628 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
43629 ** wal-index.
43630 **
43631 ** Changing any of these constants will alter the wal-index format and
43632 ** create incompatibilities.
43633 */
43634 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
43635 #define HASHTABLE_HASH_1     383                  /* Should be prime */
43636 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
43637
43638 /* 
43639 ** The block of page numbers associated with the first hash-table in a
43640 ** wal-index is smaller than usual. This is so that there is a complete
43641 ** hash-table on each aligned 32KB page of the wal-index.
43642 */
43643 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
43644
43645 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
43646 #define WALINDEX_PGSZ   (                                         \
43647     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
43648 )
43649
43650 /*
43651 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
43652 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
43653 ** numbered from zero.
43654 **
43655 ** If this call is successful, *ppPage is set to point to the wal-index
43656 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
43657 ** then an SQLite error code is returned and *ppPage is set to 0.
43658 */
43659 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
43660   int rc = SQLITE_OK;
43661
43662   /* Enlarge the pWal->apWiData[] array if required */
43663   if( pWal->nWiData<=iPage ){
43664     int nByte = sizeof(u32*)*(iPage+1);
43665     volatile u32 **apNew;
43666     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
43667     if( !apNew ){
43668       *ppPage = 0;
43669       return SQLITE_NOMEM;
43670     }
43671     memset((void*)&apNew[pWal->nWiData], 0,
43672            sizeof(u32*)*(iPage+1-pWal->nWiData));
43673     pWal->apWiData = apNew;
43674     pWal->nWiData = iPage+1;
43675   }
43676
43677   /* Request a pointer to the required page from the VFS */
43678   if( pWal->apWiData[iPage]==0 ){
43679     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
43680       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
43681       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
43682     }else{
43683       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
43684           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
43685       );
43686     }
43687   }
43688
43689   *ppPage = pWal->apWiData[iPage];
43690   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
43691   return rc;
43692 }
43693
43694 /*
43695 ** Return a pointer to the WalCkptInfo structure in the wal-index.
43696 */
43697 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
43698   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43699   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
43700 }
43701
43702 /*
43703 ** Return a pointer to the WalIndexHdr structure in the wal-index.
43704 */
43705 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
43706   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43707   return (volatile WalIndexHdr*)pWal->apWiData[0];
43708 }
43709
43710 /*
43711 ** The argument to this macro must be of type u32. On a little-endian
43712 ** architecture, it returns the u32 value that results from interpreting
43713 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
43714 ** returns the value that would be produced by intepreting the 4 bytes
43715 ** of the input value as a little-endian integer.
43716 */
43717 #define BYTESWAP32(x) ( \
43718     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
43719   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
43720 )
43721
43722 /*
43723 ** Generate or extend an 8 byte checksum based on the data in 
43724 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
43725 ** initial values of 0 and 0 if aIn==NULL).
43726 **
43727 ** The checksum is written back into aOut[] before returning.
43728 **
43729 ** nByte must be a positive multiple of 8.
43730 */
43731 static void walChecksumBytes(
43732   int nativeCksum, /* True for native byte-order, false for non-native */
43733   u8 *a,           /* Content to be checksummed */
43734   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
43735   const u32 *aIn,  /* Initial checksum value input */
43736   u32 *aOut        /* OUT: Final checksum value output */
43737 ){
43738   u32 s1, s2;
43739   u32 *aData = (u32 *)a;
43740   u32 *aEnd = (u32 *)&a[nByte];
43741
43742   if( aIn ){
43743     s1 = aIn[0];
43744     s2 = aIn[1];
43745   }else{
43746     s1 = s2 = 0;
43747   }
43748
43749   assert( nByte>=8 );
43750   assert( (nByte&0x00000007)==0 );
43751
43752   if( nativeCksum ){
43753     do {
43754       s1 += *aData++ + s2;
43755       s2 += *aData++ + s1;
43756     }while( aData<aEnd );
43757   }else{
43758     do {
43759       s1 += BYTESWAP32(aData[0]) + s2;
43760       s2 += BYTESWAP32(aData[1]) + s1;
43761       aData += 2;
43762     }while( aData<aEnd );
43763   }
43764
43765   aOut[0] = s1;
43766   aOut[1] = s2;
43767 }
43768
43769 static void walShmBarrier(Wal *pWal){
43770   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
43771     sqlite3OsShmBarrier(pWal->pDbFd);
43772   }
43773 }
43774
43775 /*
43776 ** Write the header information in pWal->hdr into the wal-index.
43777 **
43778 ** The checksum on pWal->hdr is updated before it is written.
43779 */
43780 static void walIndexWriteHdr(Wal *pWal){
43781   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
43782   const int nCksum = offsetof(WalIndexHdr, aCksum);
43783
43784   assert( pWal->writeLock );
43785   pWal->hdr.isInit = 1;
43786   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
43787   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
43788   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43789   walShmBarrier(pWal);
43790   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
43791 }
43792
43793 /*
43794 ** This function encodes a single frame header and writes it to a buffer
43795 ** supplied by the caller. A frame-header is made up of a series of 
43796 ** 4-byte big-endian integers, as follows:
43797 **
43798 **     0: Page number.
43799 **     4: For commit records, the size of the database image in pages 
43800 **        after the commit. For all other records, zero.
43801 **     8: Salt-1 (copied from the wal-header)
43802 **    12: Salt-2 (copied from the wal-header)
43803 **    16: Checksum-1.
43804 **    20: Checksum-2.
43805 */
43806 static void walEncodeFrame(
43807   Wal *pWal,                      /* The write-ahead log */
43808   u32 iPage,                      /* Database page number for frame */
43809   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
43810   u8 *aData,                      /* Pointer to page data */
43811   u8 *aFrame                      /* OUT: Write encoded frame here */
43812 ){
43813   int nativeCksum;                /* True for native byte-order checksums */
43814   u32 *aCksum = pWal->hdr.aFrameCksum;
43815   assert( WAL_FRAME_HDRSIZE==24 );
43816   sqlite3Put4byte(&aFrame[0], iPage);
43817   sqlite3Put4byte(&aFrame[4], nTruncate);
43818   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
43819
43820   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43821   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43822   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43823
43824   sqlite3Put4byte(&aFrame[16], aCksum[0]);
43825   sqlite3Put4byte(&aFrame[20], aCksum[1]);
43826 }
43827
43828 /*
43829 ** Check to see if the frame with header in aFrame[] and content
43830 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
43831 ** *pnTruncate and return true.  Return if the frame is not valid.
43832 */
43833 static int walDecodeFrame(
43834   Wal *pWal,                      /* The write-ahead log */
43835   u32 *piPage,                    /* OUT: Database page number for frame */
43836   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
43837   u8 *aData,                      /* Pointer to page data (for checksum) */
43838   u8 *aFrame                      /* Frame data */
43839 ){
43840   int nativeCksum;                /* True for native byte-order checksums */
43841   u32 *aCksum = pWal->hdr.aFrameCksum;
43842   u32 pgno;                       /* Page number of the frame */
43843   assert( WAL_FRAME_HDRSIZE==24 );
43844
43845   /* A frame is only valid if the salt values in the frame-header
43846   ** match the salt values in the wal-header. 
43847   */
43848   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
43849     return 0;
43850   }
43851
43852   /* A frame is only valid if the page number is creater than zero.
43853   */
43854   pgno = sqlite3Get4byte(&aFrame[0]);
43855   if( pgno==0 ){
43856     return 0;
43857   }
43858
43859   /* A frame is only valid if a checksum of the WAL header,
43860   ** all prior frams, the first 16 bytes of this frame-header, 
43861   ** and the frame-data matches the checksum in the last 8 
43862   ** bytes of this frame-header.
43863   */
43864   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
43865   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
43866   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
43867   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
43868    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
43869   ){
43870     /* Checksum failed. */
43871     return 0;
43872   }
43873
43874   /* If we reach this point, the frame is valid.  Return the page number
43875   ** and the new database size.
43876   */
43877   *piPage = pgno;
43878   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
43879   return 1;
43880 }
43881
43882
43883 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43884 /*
43885 ** Names of locks.  This routine is used to provide debugging output and is not
43886 ** a part of an ordinary build.
43887 */
43888 static const char *walLockName(int lockIdx){
43889   if( lockIdx==WAL_WRITE_LOCK ){
43890     return "WRITE-LOCK";
43891   }else if( lockIdx==WAL_CKPT_LOCK ){
43892     return "CKPT-LOCK";
43893   }else if( lockIdx==WAL_RECOVER_LOCK ){
43894     return "RECOVER-LOCK";
43895   }else{
43896     static char zName[15];
43897     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
43898                      lockIdx-WAL_READ_LOCK(0));
43899     return zName;
43900   }
43901 }
43902 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
43903     
43904
43905 /*
43906 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
43907 ** A lock cannot be moved directly between shared and exclusive - it must go
43908 ** through the unlocked state first.
43909 **
43910 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
43911 */
43912 static int walLockShared(Wal *pWal, int lockIdx){
43913   int rc;
43914   if( pWal->exclusiveMode ) return SQLITE_OK;
43915   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
43916                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
43917   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
43918             walLockName(lockIdx), rc ? "failed" : "ok"));
43919   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
43920   return rc;
43921 }
43922 static void walUnlockShared(Wal *pWal, int lockIdx){
43923   if( pWal->exclusiveMode ) return;
43924   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
43925                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
43926   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
43927 }
43928 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
43929   int rc;
43930   if( pWal->exclusiveMode ) return SQLITE_OK;
43931   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
43932                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
43933   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
43934             walLockName(lockIdx), n, rc ? "failed" : "ok"));
43935   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
43936   return rc;
43937 }
43938 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
43939   if( pWal->exclusiveMode ) return;
43940   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
43941                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
43942   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
43943              walLockName(lockIdx), n));
43944 }
43945
43946 /*
43947 ** Compute a hash on a page number.  The resulting hash value must land
43948 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
43949 ** the hash to the next value in the event of a collision.
43950 */
43951 static int walHash(u32 iPage){
43952   assert( iPage>0 );
43953   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
43954   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
43955 }
43956 static int walNextHash(int iPriorHash){
43957   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
43958 }
43959
43960 /* 
43961 ** Return pointers to the hash table and page number array stored on
43962 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
43963 ** numbered starting from 0.
43964 **
43965 ** Set output variable *paHash to point to the start of the hash table
43966 ** in the wal-index file. Set *piZero to one less than the frame 
43967 ** number of the first frame indexed by this hash table. If a
43968 ** slot in the hash table is set to N, it refers to frame number 
43969 ** (*piZero+N) in the log.
43970 **
43971 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
43972 ** first frame indexed by the hash table, frame (*piZero+1).
43973 */
43974 static int walHashGet(
43975   Wal *pWal,                      /* WAL handle */
43976   int iHash,                      /* Find the iHash'th table */
43977   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
43978   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
43979   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
43980 ){
43981   int rc;                         /* Return code */
43982   volatile u32 *aPgno;
43983
43984   rc = walIndexPage(pWal, iHash, &aPgno);
43985   assert( rc==SQLITE_OK || iHash>0 );
43986
43987   if( rc==SQLITE_OK ){
43988     u32 iZero;
43989     volatile ht_slot *aHash;
43990
43991     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
43992     if( iHash==0 ){
43993       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
43994       iZero = 0;
43995     }else{
43996       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
43997     }
43998   
43999     *paPgno = &aPgno[-1];
44000     *paHash = aHash;
44001     *piZero = iZero;
44002   }
44003   return rc;
44004 }
44005
44006 /*
44007 ** Return the number of the wal-index page that contains the hash-table
44008 ** and page-number array that contain entries corresponding to WAL frame
44009 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
44010 ** are numbered starting from 0.
44011 */
44012 static int walFramePage(u32 iFrame){
44013   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44014   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44015        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44016        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44017        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44018        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44019   );
44020   return iHash;
44021 }
44022
44023 /*
44024 ** Return the page number associated with frame iFrame in this WAL.
44025 */
44026 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44027   int iHash = walFramePage(iFrame);
44028   if( iHash==0 ){
44029     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44030   }
44031   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44032 }
44033
44034 /*
44035 ** Remove entries from the hash table that point to WAL slots greater
44036 ** than pWal->hdr.mxFrame.
44037 **
44038 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44039 ** to a rollback or savepoint.
44040 **
44041 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44042 ** updated.  Any later hash tables will be automatically cleared when
44043 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44044 ** actually needed.
44045 */
44046 static void walCleanupHash(Wal *pWal){
44047   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
44048   volatile u32 *aPgno = 0;        /* Page number array for hash table */
44049   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
44050   int iLimit = 0;                 /* Zero values greater than this */
44051   int nByte;                      /* Number of bytes to zero in aPgno[] */
44052   int i;                          /* Used to iterate through aHash[] */
44053
44054   assert( pWal->writeLock );
44055   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44056   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44057   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44058
44059   if( pWal->hdr.mxFrame==0 ) return;
44060
44061   /* Obtain pointers to the hash-table and page-number array containing 
44062   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44063   ** that the page said hash-table and array reside on is already mapped.
44064   */
44065   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44066   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44067   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44068
44069   /* Zero all hash-table entries that correspond to frame numbers greater
44070   ** than pWal->hdr.mxFrame.
44071   */
44072   iLimit = pWal->hdr.mxFrame - iZero;
44073   assert( iLimit>0 );
44074   for(i=0; i<HASHTABLE_NSLOT; i++){
44075     if( aHash[i]>iLimit ){
44076       aHash[i] = 0;
44077     }
44078   }
44079   
44080   /* Zero the entries in the aPgno array that correspond to frames with
44081   ** frame numbers greater than pWal->hdr.mxFrame. 
44082   */
44083   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44084   memset((void *)&aPgno[iLimit+1], 0, nByte);
44085
44086 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44087   /* Verify that the every entry in the mapping region is still reachable
44088   ** via the hash table even after the cleanup.
44089   */
44090   if( iLimit ){
44091     int i;           /* Loop counter */
44092     int iKey;        /* Hash key */
44093     for(i=1; i<=iLimit; i++){
44094       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44095         if( aHash[iKey]==i ) break;
44096       }
44097       assert( aHash[iKey]==i );
44098     }
44099   }
44100 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44101 }
44102
44103
44104 /*
44105 ** Set an entry in the wal-index that will map database page number
44106 ** pPage into WAL frame iFrame.
44107 */
44108 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44109   int rc;                         /* Return code */
44110   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
44111   volatile u32 *aPgno = 0;        /* Page number array */
44112   volatile ht_slot *aHash = 0;    /* Hash table */
44113
44114   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44115
44116   /* Assuming the wal-index file was successfully mapped, populate the
44117   ** page number array and hash table entry.
44118   */
44119   if( rc==SQLITE_OK ){
44120     int iKey;                     /* Hash table key */
44121     int idx;                      /* Value to write to hash-table slot */
44122     int nCollide;                 /* Number of hash collisions */
44123
44124     idx = iFrame - iZero;
44125     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44126     
44127     /* If this is the first entry to be added to this hash-table, zero the
44128     ** entire hash table and aPgno[] array before proceding. 
44129     */
44130     if( idx==1 ){
44131       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44132       memset((void*)&aPgno[1], 0, nByte);
44133     }
44134
44135     /* If the entry in aPgno[] is already set, then the previous writer
44136     ** must have exited unexpectedly in the middle of a transaction (after
44137     ** writing one or more dirty pages to the WAL to free up memory). 
44138     ** Remove the remnants of that writers uncommitted transaction from 
44139     ** the hash-table before writing any new entries.
44140     */
44141     if( aPgno[idx] ){
44142       walCleanupHash(pWal);
44143       assert( !aPgno[idx] );
44144     }
44145
44146     /* Write the aPgno[] array entry and the hash-table slot. */
44147     nCollide = idx;
44148     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44149       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44150     }
44151     aPgno[idx] = iPage;
44152     aHash[iKey] = (ht_slot)idx;
44153
44154 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44155     /* Verify that the number of entries in the hash table exactly equals
44156     ** the number of entries in the mapping region.
44157     */
44158     {
44159       int i;           /* Loop counter */
44160       int nEntry = 0;  /* Number of entries in the hash table */
44161       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44162       assert( nEntry==idx );
44163     }
44164
44165     /* Verify that the every entry in the mapping region is reachable
44166     ** via the hash table.  This turns out to be a really, really expensive
44167     ** thing to check, so only do this occasionally - not on every
44168     ** iteration.
44169     */
44170     if( (idx&0x3ff)==0 ){
44171       int i;           /* Loop counter */
44172       for(i=1; i<=idx; i++){
44173         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44174           if( aHash[iKey]==i ) break;
44175         }
44176         assert( aHash[iKey]==i );
44177       }
44178     }
44179 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44180   }
44181
44182
44183   return rc;
44184 }
44185
44186
44187 /*
44188 ** Recover the wal-index by reading the write-ahead log file. 
44189 **
44190 ** This routine first tries to establish an exclusive lock on the
44191 ** wal-index to prevent other threads/processes from doing anything
44192 ** with the WAL or wal-index while recovery is running.  The
44193 ** WAL_RECOVER_LOCK is also held so that other threads will know
44194 ** that this thread is running recovery.  If unable to establish
44195 ** the necessary locks, this routine returns SQLITE_BUSY.
44196 */
44197 static int walIndexRecover(Wal *pWal){
44198   int rc;                         /* Return Code */
44199   i64 nSize;                      /* Size of log file */
44200   u32 aFrameCksum[2] = {0, 0};
44201   int iLock;                      /* Lock offset to lock for checkpoint */
44202   int nLock;                      /* Number of locks to hold */
44203
44204   /* Obtain an exclusive lock on all byte in the locking range not already
44205   ** locked by the caller. The caller is guaranteed to have locked the
44206   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44207   ** If successful, the same bytes that are locked here are unlocked before
44208   ** this function returns.
44209   */
44210   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44211   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44212   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44213   assert( pWal->writeLock );
44214   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44215   nLock = SQLITE_SHM_NLOCK - iLock;
44216   rc = walLockExclusive(pWal, iLock, nLock);
44217   if( rc ){
44218     return rc;
44219   }
44220   WALTRACE(("WAL%p: recovery begin...\n", pWal));
44221
44222   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44223
44224   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44225   if( rc!=SQLITE_OK ){
44226     goto recovery_error;
44227   }
44228
44229   if( nSize>WAL_HDRSIZE ){
44230     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
44231     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
44232     int szFrame;                  /* Number of bytes in buffer aFrame[] */
44233     u8 *aData;                    /* Pointer to data part of aFrame buffer */
44234     int iFrame;                   /* Index of last frame read */
44235     i64 iOffset;                  /* Next offset to read from log file */
44236     int szPage;                   /* Page size according to the log */
44237     u32 magic;                    /* Magic value read from WAL header */
44238     u32 version;                  /* Magic value read from WAL header */
44239
44240     /* Read in the WAL header. */
44241     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44242     if( rc!=SQLITE_OK ){
44243       goto recovery_error;
44244     }
44245
44246     /* If the database page size is not a power of two, or is greater than
44247     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
44248     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44249     ** WAL file.
44250     */
44251     magic = sqlite3Get4byte(&aBuf[0]);
44252     szPage = sqlite3Get4byte(&aBuf[8]);
44253     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
44254      || szPage&(szPage-1) 
44255      || szPage>SQLITE_MAX_PAGE_SIZE 
44256      || szPage<512 
44257     ){
44258       goto finished;
44259     }
44260     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44261     pWal->szPage = szPage;
44262     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44263     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44264
44265     /* Verify that the WAL header checksum is correct */
44266     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
44267         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44268     );
44269     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44270      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44271     ){
44272       goto finished;
44273     }
44274
44275     /* Verify that the version number on the WAL format is one that
44276     ** are able to understand */
44277     version = sqlite3Get4byte(&aBuf[4]);
44278     if( version!=WAL_MAX_VERSION ){
44279       rc = SQLITE_CANTOPEN_BKPT;
44280       goto finished;
44281     }
44282
44283     /* Malloc a buffer to read frames into. */
44284     szFrame = szPage + WAL_FRAME_HDRSIZE;
44285     aFrame = (u8 *)sqlite3_malloc(szFrame);
44286     if( !aFrame ){
44287       rc = SQLITE_NOMEM;
44288       goto recovery_error;
44289     }
44290     aData = &aFrame[WAL_FRAME_HDRSIZE];
44291
44292     /* Read all frames from the log file. */
44293     iFrame = 0;
44294     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44295       u32 pgno;                   /* Database page number for frame */
44296       u32 nTruncate;              /* dbsize field from frame header */
44297       int isValid;                /* True if this frame is valid */
44298
44299       /* Read and decode the next log frame. */
44300       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44301       if( rc!=SQLITE_OK ) break;
44302       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44303       if( !isValid ) break;
44304       rc = walIndexAppend(pWal, ++iFrame, pgno);
44305       if( rc!=SQLITE_OK ) break;
44306
44307       /* If nTruncate is non-zero, this is a commit record. */
44308       if( nTruncate ){
44309         pWal->hdr.mxFrame = iFrame;
44310         pWal->hdr.nPage = nTruncate;
44311         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44312         testcase( szPage<=32768 );
44313         testcase( szPage>=65536 );
44314         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44315         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44316       }
44317     }
44318
44319     sqlite3_free(aFrame);
44320   }
44321
44322 finished:
44323   if( rc==SQLITE_OK ){
44324     volatile WalCkptInfo *pInfo;
44325     int i;
44326     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44327     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44328     walIndexWriteHdr(pWal);
44329
44330     /* Reset the checkpoint-header. This is safe because this thread is 
44331     ** currently holding locks that exclude all other readers, writers and
44332     ** checkpointers.
44333     */
44334     pInfo = walCkptInfo(pWal);
44335     pInfo->nBackfill = 0;
44336     pInfo->aReadMark[0] = 0;
44337     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44338
44339     /* If more than one frame was recovered from the log file, report an
44340     ** event via sqlite3_log(). This is to help with identifying performance
44341     ** problems caused by applications routinely shutting down without
44342     ** checkpointing the log file.
44343     */
44344     if( pWal->hdr.nPage ){
44345       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44346           pWal->hdr.nPage, pWal->zWalName
44347       );
44348     }
44349   }
44350
44351 recovery_error:
44352   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44353   walUnlockExclusive(pWal, iLock, nLock);
44354   return rc;
44355 }
44356
44357 /*
44358 ** Close an open wal-index.
44359 */
44360 static void walIndexClose(Wal *pWal, int isDelete){
44361   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44362     int i;
44363     for(i=0; i<pWal->nWiData; i++){
44364       sqlite3_free((void *)pWal->apWiData[i]);
44365       pWal->apWiData[i] = 0;
44366     }
44367   }else{
44368     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44369   }
44370 }
44371
44372 /* 
44373 ** Open a connection to the WAL file zWalName. The database file must 
44374 ** already be opened on connection pDbFd. The buffer that zWalName points
44375 ** to must remain valid for the lifetime of the returned Wal* handle.
44376 **
44377 ** A SHARED lock should be held on the database file when this function
44378 ** is called. The purpose of this SHARED lock is to prevent any other
44379 ** client from unlinking the WAL or wal-index file. If another process
44380 ** were to do this just after this client opened one of these files, the
44381 ** system would be badly broken.
44382 **
44383 ** If the log file is successfully opened, SQLITE_OK is returned and 
44384 ** *ppWal is set to point to a new WAL handle. If an error occurs,
44385 ** an SQLite error code is returned and *ppWal is left unmodified.
44386 */
44387 SQLITE_PRIVATE int sqlite3WalOpen(
44388   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
44389   sqlite3_file *pDbFd,            /* The open database file */
44390   const char *zWalName,           /* Name of the WAL file */
44391   int bNoShm,                     /* True to run in heap-memory mode */
44392   Wal **ppWal                     /* OUT: Allocated Wal handle */
44393 ){
44394   int rc;                         /* Return Code */
44395   Wal *pRet;                      /* Object to allocate and return */
44396   int flags;                      /* Flags passed to OsOpen() */
44397
44398   assert( zWalName && zWalName[0] );
44399   assert( pDbFd );
44400
44401   /* In the amalgamation, the os_unix.c and os_win.c source files come before
44402   ** this source file.  Verify that the #defines of the locking byte offsets
44403   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44404   */
44405 #ifdef WIN_SHM_BASE
44406   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44407 #endif
44408 #ifdef UNIX_SHM_BASE
44409   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44410 #endif
44411
44412
44413   /* Allocate an instance of struct Wal to return. */
44414   *ppWal = 0;
44415   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44416   if( !pRet ){
44417     return SQLITE_NOMEM;
44418   }
44419
44420   pRet->pVfs = pVfs;
44421   pRet->pWalFd = (sqlite3_file *)&pRet[1];
44422   pRet->pDbFd = pDbFd;
44423   pRet->readLock = -1;
44424   pRet->zWalName = zWalName;
44425   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44426
44427   /* Open file handle on the write-ahead log file. */
44428   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44429   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44430   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44431     pRet->readOnly = 1;
44432   }
44433
44434   if( rc!=SQLITE_OK ){
44435     walIndexClose(pRet, 0);
44436     sqlite3OsClose(pRet->pWalFd);
44437     sqlite3_free(pRet);
44438   }else{
44439     *ppWal = pRet;
44440     WALTRACE(("WAL%d: opened\n", pRet));
44441   }
44442   return rc;
44443 }
44444
44445 /*
44446 ** Find the smallest page number out of all pages held in the WAL that
44447 ** has not been returned by any prior invocation of this method on the
44448 ** same WalIterator object.   Write into *piFrame the frame index where
44449 ** that page was last written into the WAL.  Write into *piPage the page
44450 ** number.
44451 **
44452 ** Return 0 on success.  If there are no pages in the WAL with a page
44453 ** number larger than *piPage, then return 1.
44454 */
44455 static int walIteratorNext(
44456   WalIterator *p,               /* Iterator */
44457   u32 *piPage,                  /* OUT: The page number of the next page */
44458   u32 *piFrame                  /* OUT: Wal frame index of next page */
44459 ){
44460   u32 iMin;                     /* Result pgno must be greater than iMin */
44461   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
44462   int i;                        /* For looping through segments */
44463
44464   iMin = p->iPrior;
44465   assert( iMin<0xffffffff );
44466   for(i=p->nSegment-1; i>=0; i--){
44467     struct WalSegment *pSegment = &p->aSegment[i];
44468     while( pSegment->iNext<pSegment->nEntry ){
44469       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44470       if( iPg>iMin ){
44471         if( iPg<iRet ){
44472           iRet = iPg;
44473           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44474         }
44475         break;
44476       }
44477       pSegment->iNext++;
44478     }
44479   }
44480
44481   *piPage = p->iPrior = iRet;
44482   return (iRet==0xFFFFFFFF);
44483 }
44484
44485 /*
44486 ** This function merges two sorted lists into a single sorted list.
44487 **
44488 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
44489 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
44490 ** is guaranteed for all J<K:
44491 **
44492 **        aContent[aLeft[J]] < aContent[aLeft[K]]
44493 **        aContent[aRight[J]] < aContent[aRight[K]]
44494 **
44495 ** This routine overwrites aRight[] with a new (probably longer) sequence
44496 ** of indices such that the aRight[] contains every index that appears in
44497 ** either aLeft[] or the old aRight[] and such that the second condition
44498 ** above is still met.
44499 **
44500 ** The aContent[aLeft[X]] values will be unique for all X.  And the
44501 ** aContent[aRight[X]] values will be unique too.  But there might be
44502 ** one or more combinations of X and Y such that
44503 **
44504 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
44505 **
44506 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44507 */
44508 static void walMerge(
44509   const u32 *aContent,            /* Pages in wal - keys for the sort */
44510   ht_slot *aLeft,                 /* IN: Left hand input list */
44511   int nLeft,                      /* IN: Elements in array *paLeft */
44512   ht_slot **paRight,              /* IN/OUT: Right hand input list */
44513   int *pnRight,                   /* IN/OUT: Elements in *paRight */
44514   ht_slot *aTmp                   /* Temporary buffer */
44515 ){
44516   int iLeft = 0;                  /* Current index in aLeft */
44517   int iRight = 0;                 /* Current index in aRight */
44518   int iOut = 0;                   /* Current index in output buffer */
44519   int nRight = *pnRight;
44520   ht_slot *aRight = *paRight;
44521
44522   assert( nLeft>0 && nRight>0 );
44523   while( iRight<nRight || iLeft<nLeft ){
44524     ht_slot logpage;
44525     Pgno dbpage;
44526
44527     if( (iLeft<nLeft) 
44528      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
44529     ){
44530       logpage = aLeft[iLeft++];
44531     }else{
44532       logpage = aRight[iRight++];
44533     }
44534     dbpage = aContent[logpage];
44535
44536     aTmp[iOut++] = logpage;
44537     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
44538
44539     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
44540     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
44541   }
44542
44543   *paRight = aLeft;
44544   *pnRight = iOut;
44545   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
44546 }
44547
44548 /*
44549 ** Sort the elements in list aList using aContent[] as the sort key.
44550 ** Remove elements with duplicate keys, preferring to keep the
44551 ** larger aList[] values.
44552 **
44553 ** The aList[] entries are indices into aContent[].  The values in
44554 ** aList[] are to be sorted so that for all J<K:
44555 **
44556 **      aContent[aList[J]] < aContent[aList[K]]
44557 **
44558 ** For any X and Y such that
44559 **
44560 **      aContent[aList[X]] == aContent[aList[Y]]
44561 **
44562 ** Keep the larger of the two values aList[X] and aList[Y] and discard
44563 ** the smaller.
44564 */
44565 static void walMergesort(
44566   const u32 *aContent,            /* Pages in wal */
44567   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
44568   ht_slot *aList,                 /* IN/OUT: List to sort */
44569   int *pnList                     /* IN/OUT: Number of elements in aList[] */
44570 ){
44571   struct Sublist {
44572     int nList;                    /* Number of elements in aList */
44573     ht_slot *aList;               /* Pointer to sub-list content */
44574   };
44575
44576   const int nList = *pnList;      /* Size of input list */
44577   int nMerge = 0;                 /* Number of elements in list aMerge */
44578   ht_slot *aMerge = 0;            /* List to be merged */
44579   int iList;                      /* Index into input list */
44580   int iSub = 0;                   /* Index into aSub array */
44581   struct Sublist aSub[13];        /* Array of sub-lists */
44582
44583   memset(aSub, 0, sizeof(aSub));
44584   assert( nList<=HASHTABLE_NPAGE && nList>0 );
44585   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
44586
44587   for(iList=0; iList<nList; iList++){
44588     nMerge = 1;
44589     aMerge = &aList[iList];
44590     for(iSub=0; iList & (1<<iSub); iSub++){
44591       struct Sublist *p = &aSub[iSub];
44592       assert( p->aList && p->nList<=(1<<iSub) );
44593       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
44594       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44595     }
44596     aSub[iSub].aList = aMerge;
44597     aSub[iSub].nList = nMerge;
44598   }
44599
44600   for(iSub++; iSub<ArraySize(aSub); iSub++){
44601     if( nList & (1<<iSub) ){
44602       struct Sublist *p = &aSub[iSub];
44603       assert( p->nList<=(1<<iSub) );
44604       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
44605       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44606     }
44607   }
44608   assert( aMerge==aList );
44609   *pnList = nMerge;
44610
44611 #ifdef SQLITE_DEBUG
44612   {
44613     int i;
44614     for(i=1; i<*pnList; i++){
44615       assert( aContent[aList[i]] > aContent[aList[i-1]] );
44616     }
44617   }
44618 #endif
44619 }
44620
44621 /* 
44622 ** Free an iterator allocated by walIteratorInit().
44623 */
44624 static void walIteratorFree(WalIterator *p){
44625   sqlite3ScratchFree(p);
44626 }
44627
44628 /*
44629 ** Construct a WalInterator object that can be used to loop over all 
44630 ** pages in the WAL in ascending order. The caller must hold the checkpoint
44631 ** lock.
44632 **
44633 ** On success, make *pp point to the newly allocated WalInterator object
44634 ** return SQLITE_OK. Otherwise, return an error code. If this routine
44635 ** returns an error, the value of *pp is undefined.
44636 **
44637 ** The calling routine should invoke walIteratorFree() to destroy the
44638 ** WalIterator object when it has finished with it.
44639 */
44640 static int walIteratorInit(Wal *pWal, WalIterator **pp){
44641   WalIterator *p;                 /* Return value */
44642   int nSegment;                   /* Number of segments to merge */
44643   u32 iLast;                      /* Last frame in log */
44644   int nByte;                      /* Number of bytes to allocate */
44645   int i;                          /* Iterator variable */
44646   ht_slot *aTmp;                  /* Temp space used by merge-sort */
44647   int rc = SQLITE_OK;             /* Return Code */
44648
44649   /* This routine only runs while holding the checkpoint lock. And
44650   ** it only runs if there is actually content in the log (mxFrame>0).
44651   */
44652   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
44653   iLast = pWal->hdr.mxFrame;
44654
44655   /* Allocate space for the WalIterator object. */
44656   nSegment = walFramePage(iLast) + 1;
44657   nByte = sizeof(WalIterator) 
44658         + (nSegment-1)*sizeof(struct WalSegment)
44659         + iLast*sizeof(ht_slot);
44660   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
44661   if( !p ){
44662     return SQLITE_NOMEM;
44663   }
44664   memset(p, 0, nByte);
44665   p->nSegment = nSegment;
44666
44667   /* Allocate temporary space used by the merge-sort routine. This block
44668   ** of memory will be freed before this function returns.
44669   */
44670   aTmp = (ht_slot *)sqlite3ScratchMalloc(
44671       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
44672   );
44673   if( !aTmp ){
44674     rc = SQLITE_NOMEM;
44675   }
44676
44677   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
44678     volatile ht_slot *aHash;
44679     u32 iZero;
44680     volatile u32 *aPgno;
44681
44682     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
44683     if( rc==SQLITE_OK ){
44684       int j;                      /* Counter variable */
44685       int nEntry;                 /* Number of entries in this segment */
44686       ht_slot *aIndex;            /* Sorted index for this segment */
44687
44688       aPgno++;
44689       if( (i+1)==nSegment ){
44690         nEntry = (int)(iLast - iZero);
44691       }else{
44692         nEntry = (int)((u32*)aHash - (u32*)aPgno);
44693       }
44694       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
44695       iZero++;
44696   
44697       for(j=0; j<nEntry; j++){
44698         aIndex[j] = (ht_slot)j;
44699       }
44700       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
44701       p->aSegment[i].iZero = iZero;
44702       p->aSegment[i].nEntry = nEntry;
44703       p->aSegment[i].aIndex = aIndex;
44704       p->aSegment[i].aPgno = (u32 *)aPgno;
44705     }
44706   }
44707   sqlite3ScratchFree(aTmp);
44708
44709   if( rc!=SQLITE_OK ){
44710     walIteratorFree(p);
44711   }
44712   *pp = p;
44713   return rc;
44714 }
44715
44716 /*
44717 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
44718 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
44719 ** busy-handler function. Invoke it and retry the lock until either the
44720 ** lock is successfully obtained or the busy-handler returns 0.
44721 */
44722 static int walBusyLock(
44723   Wal *pWal,                      /* WAL connection */
44724   int (*xBusy)(void*),            /* Function to call when busy */
44725   void *pBusyArg,                 /* Context argument for xBusyHandler */
44726   int lockIdx,                    /* Offset of first byte to lock */
44727   int n                           /* Number of bytes to lock */
44728 ){
44729   int rc;
44730   do {
44731     rc = walLockExclusive(pWal, lockIdx, n);
44732   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
44733   return rc;
44734 }
44735
44736 /*
44737 ** The cache of the wal-index header must be valid to call this function.
44738 ** Return the page-size in bytes used by the database.
44739 */
44740 static int walPagesize(Wal *pWal){
44741   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
44742 }
44743
44744 /*
44745 ** Copy as much content as we can from the WAL back into the database file
44746 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
44747 **
44748 ** The amount of information copies from WAL to database might be limited
44749 ** by active readers.  This routine will never overwrite a database page
44750 ** that a concurrent reader might be using.
44751 **
44752 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
44753 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
44754 ** checkpoints are always run by a background thread or background 
44755 ** process, foreground threads will never block on a lengthy fsync call.
44756 **
44757 ** Fsync is called on the WAL before writing content out of the WAL and
44758 ** into the database.  This ensures that if the new content is persistent
44759 ** in the WAL and can be recovered following a power-loss or hard reset.
44760 **
44761 ** Fsync is also called on the database file if (and only if) the entire
44762 ** WAL content is copied into the database file.  This second fsync makes
44763 ** it safe to delete the WAL since the new content will persist in the
44764 ** database file.
44765 **
44766 ** This routine uses and updates the nBackfill field of the wal-index header.
44767 ** This is the only routine tha will increase the value of nBackfill.  
44768 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
44769 ** its value.)
44770 **
44771 ** The caller must be holding sufficient locks to ensure that no other
44772 ** checkpoint is running (in any other thread or process) at the same
44773 ** time.
44774 */
44775 static int walCheckpoint(
44776   Wal *pWal,                      /* Wal connection */
44777   int eMode,                      /* One of PASSIVE, FULL or RESTART */
44778   int (*xBusyCall)(void*),        /* Function to call when busy */
44779   void *pBusyArg,                 /* Context argument for xBusyHandler */
44780   int sync_flags,                 /* Flags for OsSync() (or 0) */
44781   u8 *zBuf                        /* Temporary buffer to use */
44782 ){
44783   int rc;                         /* Return code */
44784   int szPage;                     /* Database page-size */
44785   WalIterator *pIter = 0;         /* Wal iterator context */
44786   u32 iDbpage = 0;                /* Next database page to write */
44787   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
44788   u32 mxSafeFrame;                /* Max frame that can be backfilled */
44789   u32 mxPage;                     /* Max database page to write */
44790   int i;                          /* Loop counter */
44791   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
44792   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
44793
44794   szPage = walPagesize(pWal);
44795   testcase( szPage<=32768 );
44796   testcase( szPage>=65536 );
44797   pInfo = walCkptInfo(pWal);
44798   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
44799
44800   /* Allocate the iterator */
44801   rc = walIteratorInit(pWal, &pIter);
44802   if( rc!=SQLITE_OK ){
44803     return rc;
44804   }
44805   assert( pIter );
44806
44807   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
44808
44809   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
44810   ** safe to write into the database.  Frames beyond mxSafeFrame might
44811   ** overwrite database pages that are in use by active readers and thus
44812   ** cannot be backfilled from the WAL.
44813   */
44814   mxSafeFrame = pWal->hdr.mxFrame;
44815   mxPage = pWal->hdr.nPage;
44816   for(i=1; i<WAL_NREADER; i++){
44817     u32 y = pInfo->aReadMark[i];
44818     if( mxSafeFrame>y ){
44819       assert( y<=pWal->hdr.mxFrame );
44820       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
44821       if( rc==SQLITE_OK ){
44822         pInfo->aReadMark[i] = READMARK_NOT_USED;
44823         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
44824       }else if( rc==SQLITE_BUSY ){
44825         mxSafeFrame = y;
44826         xBusy = 0;
44827       }else{
44828         goto walcheckpoint_out;
44829       }
44830     }
44831   }
44832
44833   if( pInfo->nBackfill<mxSafeFrame
44834    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
44835   ){
44836     i64 nSize;                    /* Current size of database file */
44837     u32 nBackfill = pInfo->nBackfill;
44838
44839     /* Sync the WAL to disk */
44840     if( sync_flags ){
44841       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
44842     }
44843
44844     /* If the database file may grow as a result of this checkpoint, hint
44845     ** about the eventual size of the db file to the VFS layer. 
44846     */
44847     if( rc==SQLITE_OK ){
44848       i64 nReq = ((i64)mxPage * szPage);
44849       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
44850       if( rc==SQLITE_OK && nSize<nReq ){
44851         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
44852       }
44853     }
44854
44855     /* Iterate through the contents of the WAL, copying data to the db file. */
44856     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
44857       i64 iOffset;
44858       assert( walFramePgno(pWal, iFrame)==iDbpage );
44859       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
44860       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
44861       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
44862       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
44863       if( rc!=SQLITE_OK ) break;
44864       iOffset = (iDbpage-1)*(i64)szPage;
44865       testcase( IS_BIG_INT(iOffset) );
44866       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
44867       if( rc!=SQLITE_OK ) break;
44868     }
44869
44870     /* If work was actually accomplished... */
44871     if( rc==SQLITE_OK ){
44872       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
44873         i64 szDb = pWal->hdr.nPage*(i64)szPage;
44874         testcase( IS_BIG_INT(szDb) );
44875         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
44876         if( rc==SQLITE_OK && sync_flags ){
44877           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
44878         }
44879       }
44880       if( rc==SQLITE_OK ){
44881         pInfo->nBackfill = mxSafeFrame;
44882       }
44883     }
44884
44885     /* Release the reader lock held while backfilling */
44886     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
44887   }
44888
44889   if( rc==SQLITE_BUSY ){
44890     /* Reset the return code so as not to report a checkpoint failure
44891     ** just because there are active readers.  */
44892     rc = SQLITE_OK;
44893   }
44894
44895   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
44896   ** file has been copied into the database file, then block until all
44897   ** readers have finished using the wal file. This ensures that the next
44898   ** process to write to the database restarts the wal file.
44899   */
44900   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
44901     assert( pWal->writeLock );
44902     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
44903       rc = SQLITE_BUSY;
44904     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
44905       assert( mxSafeFrame==pWal->hdr.mxFrame );
44906       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
44907       if( rc==SQLITE_OK ){
44908         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
44909       }
44910     }
44911   }
44912
44913  walcheckpoint_out:
44914   walIteratorFree(pIter);
44915   return rc;
44916 }
44917
44918 /*
44919 ** Close a connection to a log file.
44920 */
44921 SQLITE_PRIVATE int sqlite3WalClose(
44922   Wal *pWal,                      /* Wal to close */
44923   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
44924   int nBuf,
44925   u8 *zBuf                        /* Buffer of at least nBuf bytes */
44926 ){
44927   int rc = SQLITE_OK;
44928   if( pWal ){
44929     int isDelete = 0;             /* True to unlink wal and wal-index files */
44930
44931     /* If an EXCLUSIVE lock can be obtained on the database file (using the
44932     ** ordinary, rollback-mode locking methods, this guarantees that the
44933     ** connection associated with this log file is the only connection to
44934     ** the database. In this case checkpoint the database and unlink both
44935     ** the wal and wal-index files.
44936     **
44937     ** The EXCLUSIVE lock is not released before returning.
44938     */
44939     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
44940     if( rc==SQLITE_OK ){
44941       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
44942         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
44943       }
44944       rc = sqlite3WalCheckpoint(
44945           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
44946       );
44947       if( rc==SQLITE_OK ){
44948         isDelete = 1;
44949       }
44950     }
44951
44952     walIndexClose(pWal, isDelete);
44953     sqlite3OsClose(pWal->pWalFd);
44954     if( isDelete ){
44955       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
44956     }
44957     WALTRACE(("WAL%p: closed\n", pWal));
44958     sqlite3_free((void *)pWal->apWiData);
44959     sqlite3_free(pWal);
44960   }
44961   return rc;
44962 }
44963
44964 /*
44965 ** Try to read the wal-index header.  Return 0 on success and 1 if
44966 ** there is a problem.
44967 **
44968 ** The wal-index is in shared memory.  Another thread or process might
44969 ** be writing the header at the same time this procedure is trying to
44970 ** read it, which might result in inconsistency.  A dirty read is detected
44971 ** by verifying that both copies of the header are the same and also by
44972 ** a checksum on the header.
44973 **
44974 ** If and only if the read is consistent and the header is different from
44975 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
44976 ** and *pChanged is set to 1.
44977 **
44978 ** If the checksum cannot be verified return non-zero. If the header
44979 ** is read successfully and the checksum verified, return zero.
44980 */
44981 static int walIndexTryHdr(Wal *pWal, int *pChanged){
44982   u32 aCksum[2];                  /* Checksum on the header content */
44983   WalIndexHdr h1, h2;             /* Two copies of the header content */
44984   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
44985
44986   /* The first page of the wal-index must be mapped at this point. */
44987   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44988
44989   /* Read the header. This might happen concurrently with a write to the
44990   ** same area of shared memory on a different CPU in a SMP,
44991   ** meaning it is possible that an inconsistent snapshot is read
44992   ** from the file. If this happens, return non-zero.
44993   **
44994   ** There are two copies of the header at the beginning of the wal-index.
44995   ** When reading, read [0] first then [1].  Writes are in the reverse order.
44996   ** Memory barriers are used to prevent the compiler or the hardware from
44997   ** reordering the reads and writes.
44998   */
44999   aHdr = walIndexHdr(pWal);
45000   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45001   walShmBarrier(pWal);
45002   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45003
45004   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45005     return 1;   /* Dirty read */
45006   }  
45007   if( h1.isInit==0 ){
45008     return 1;   /* Malformed header - probably all zeros */
45009   }
45010   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45011   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45012     return 1;   /* Checksum does not match */
45013   }
45014
45015   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45016     *pChanged = 1;
45017     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45018     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45019     testcase( pWal->szPage<=32768 );
45020     testcase( pWal->szPage>=65536 );
45021   }
45022
45023   /* The header was successfully read. Return zero. */
45024   return 0;
45025 }
45026
45027 /*
45028 ** Read the wal-index header from the wal-index and into pWal->hdr.
45029 ** If the wal-header appears to be corrupt, try to reconstruct the
45030 ** wal-index from the WAL before returning.
45031 **
45032 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45033 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
45034 ** to 0.
45035 **
45036 ** If the wal-index header is successfully read, return SQLITE_OK. 
45037 ** Otherwise an SQLite error code.
45038 */
45039 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45040   int rc;                         /* Return code */
45041   int badHdr;                     /* True if a header read failed */
45042   volatile u32 *page0;            /* Chunk of wal-index containing header */
45043
45044   /* Ensure that page 0 of the wal-index (the page that contains the 
45045   ** wal-index header) is mapped. Return early if an error occurs here.
45046   */
45047   assert( pChanged );
45048   rc = walIndexPage(pWal, 0, &page0);
45049   if( rc!=SQLITE_OK ){
45050     return rc;
45051   };
45052   assert( page0 || pWal->writeLock==0 );
45053
45054   /* If the first page of the wal-index has been mapped, try to read the
45055   ** wal-index header immediately, without holding any lock. This usually
45056   ** works, but may fail if the wal-index header is corrupt or currently 
45057   ** being modified by another thread or process.
45058   */
45059   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45060
45061   /* If the first attempt failed, it might have been due to a race
45062   ** with a writer.  So get a WRITE lock and try again.
45063   */
45064   assert( badHdr==0 || pWal->writeLock==0 );
45065   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45066     pWal->writeLock = 1;
45067     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45068       badHdr = walIndexTryHdr(pWal, pChanged);
45069       if( badHdr ){
45070         /* If the wal-index header is still malformed even while holding
45071         ** a WRITE lock, it can only mean that the header is corrupted and
45072         ** needs to be reconstructed.  So run recovery to do exactly that.
45073         */
45074         rc = walIndexRecover(pWal);
45075         *pChanged = 1;
45076       }
45077     }
45078     pWal->writeLock = 0;
45079     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45080   }
45081
45082   /* If the header is read successfully, check the version number to make
45083   ** sure the wal-index was not constructed with some future format that
45084   ** this version of SQLite cannot understand.
45085   */
45086   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45087     rc = SQLITE_CANTOPEN_BKPT;
45088   }
45089
45090   return rc;
45091 }
45092
45093 /*
45094 ** This is the value that walTryBeginRead returns when it needs to
45095 ** be retried.
45096 */
45097 #define WAL_RETRY  (-1)
45098
45099 /*
45100 ** Attempt to start a read transaction.  This might fail due to a race or
45101 ** other transient condition.  When that happens, it returns WAL_RETRY to
45102 ** indicate to the caller that it is safe to retry immediately.
45103 **
45104 ** On success return SQLITE_OK.  On a permanent failure (such an
45105 ** I/O error or an SQLITE_BUSY because another process is running
45106 ** recovery) return a positive error code.
45107 **
45108 ** The useWal parameter is true to force the use of the WAL and disable
45109 ** the case where the WAL is bypassed because it has been completely
45110 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
45111 ** to make a copy of the wal-index header into pWal->hdr.  If the 
45112 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
45113 ** to the caller that the local paget cache is obsolete and needs to be 
45114 ** flushed.)  When useWal==1, the wal-index header is assumed to already
45115 ** be loaded and the pChanged parameter is unused.
45116 **
45117 ** The caller must set the cnt parameter to the number of prior calls to
45118 ** this routine during the current read attempt that returned WAL_RETRY.
45119 ** This routine will start taking more aggressive measures to clear the
45120 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45121 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
45122 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45123 ** and is not honoring the locking protocol.  There is a vanishingly small
45124 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45125 ** bad luck when there is lots of contention for the wal-index, but that
45126 ** possibility is so small that it can be safely neglected, we believe.
45127 **
45128 ** On success, this routine obtains a read lock on 
45129 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
45130 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
45131 ** that means the Wal does not hold any read lock.  The reader must not
45132 ** access any database page that is modified by a WAL frame up to and
45133 ** including frame number aReadMark[pWal->readLock].  The reader will
45134 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45135 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45136 ** completely and get all content directly from the database file.
45137 ** If the useWal parameter is 1 then the WAL will never be ignored and
45138 ** this routine will always set pWal->readLock>0 on success.
45139 ** When the read transaction is completed, the caller must release the
45140 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45141 **
45142 ** This routine uses the nBackfill and aReadMark[] fields of the header
45143 ** to select a particular WAL_READ_LOCK() that strives to let the
45144 ** checkpoint process do as much work as possible.  This routine might
45145 ** update values of the aReadMark[] array in the header, but if it does
45146 ** so it takes care to hold an exclusive lock on the corresponding
45147 ** WAL_READ_LOCK() while changing values.
45148 */
45149 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45150   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
45151   u32 mxReadMark;                 /* Largest aReadMark[] value */
45152   int mxI;                        /* Index of largest aReadMark[] value */
45153   int i;                          /* Loop counter */
45154   int rc = SQLITE_OK;             /* Return code  */
45155
45156   assert( pWal->readLock<0 );     /* Not currently locked */
45157
45158   /* Take steps to avoid spinning forever if there is a protocol error.
45159   **
45160   ** Circumstances that cause a RETRY should only last for the briefest
45161   ** instances of time.  No I/O or other system calls are done while the
45162   ** locks are held, so the locks should not be held for very long. But 
45163   ** if we are unlucky, another process that is holding a lock might get
45164   ** paged out or take a page-fault that is time-consuming to resolve, 
45165   ** during the few nanoseconds that it is holding the lock.  In that case,
45166   ** it might take longer than normal for the lock to free.
45167   **
45168   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
45169   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
45170   ** is more of a scheduler yield than an actual delay.  But on the 10th
45171   ** an subsequent retries, the delays start becoming longer and longer, 
45172   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45173   ** The total delay time before giving up is less than 1 second.
45174   */
45175   if( cnt>5 ){
45176     int nDelay = 1;                      /* Pause time in microseconds */
45177     if( cnt>100 ){
45178       VVA_ONLY( pWal->lockError = 1; )
45179       return SQLITE_PROTOCOL;
45180     }
45181     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
45182     sqlite3OsSleep(pWal->pVfs, nDelay);
45183   }
45184
45185   if( !useWal ){
45186     rc = walIndexReadHdr(pWal, pChanged);
45187     if( rc==SQLITE_BUSY ){
45188       /* If there is not a recovery running in another thread or process
45189       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
45190       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
45191       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45192       ** would be technically correct.  But the race is benign since with
45193       ** WAL_RETRY this routine will be called again and will probably be
45194       ** right on the second iteration.
45195       */
45196       if( pWal->apWiData[0]==0 ){
45197         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45198         ** We assume this is a transient condition, so return WAL_RETRY. The
45199         ** xShmMap() implementation used by the default unix and win32 VFS 
45200         ** modules may return SQLITE_BUSY due to a race condition in the 
45201         ** code that determines whether or not the shared-memory region 
45202         ** must be zeroed before the requested page is returned.
45203         */
45204         rc = WAL_RETRY;
45205       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45206         walUnlockShared(pWal, WAL_RECOVER_LOCK);
45207         rc = WAL_RETRY;
45208       }else if( rc==SQLITE_BUSY ){
45209         rc = SQLITE_BUSY_RECOVERY;
45210       }
45211     }
45212     if( rc!=SQLITE_OK ){
45213       return rc;
45214     }
45215   }
45216
45217   pInfo = walCkptInfo(pWal);
45218   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45219     /* The WAL has been completely backfilled (or it is empty).
45220     ** and can be safely ignored.
45221     */
45222     rc = walLockShared(pWal, WAL_READ_LOCK(0));
45223     walShmBarrier(pWal);
45224     if( rc==SQLITE_OK ){
45225       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45226         /* It is not safe to allow the reader to continue here if frames
45227         ** may have been appended to the log before READ_LOCK(0) was obtained.
45228         ** When holding READ_LOCK(0), the reader ignores the entire log file,
45229         ** which implies that the database file contains a trustworthy
45230         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45231         ** happening, this is usually correct.
45232         **
45233         ** However, if frames have been appended to the log (or if the log 
45234         ** is wrapped and written for that matter) before the READ_LOCK(0)
45235         ** is obtained, that is not necessarily true. A checkpointer may
45236         ** have started to backfill the appended frames but crashed before
45237         ** it finished. Leaving a corrupt image in the database file.
45238         */
45239         walUnlockShared(pWal, WAL_READ_LOCK(0));
45240         return WAL_RETRY;
45241       }
45242       pWal->readLock = 0;
45243       return SQLITE_OK;
45244     }else if( rc!=SQLITE_BUSY ){
45245       return rc;
45246     }
45247   }
45248
45249   /* If we get this far, it means that the reader will want to use
45250   ** the WAL to get at content from recent commits.  The job now is
45251   ** to select one of the aReadMark[] entries that is closest to
45252   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45253   */
45254   mxReadMark = 0;
45255   mxI = 0;
45256   for(i=1; i<WAL_NREADER; i++){
45257     u32 thisMark = pInfo->aReadMark[i];
45258     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45259       assert( thisMark!=READMARK_NOT_USED );
45260       mxReadMark = thisMark;
45261       mxI = i;
45262     }
45263   }
45264   /* There was once an "if" here. The extra "{" is to preserve indentation. */
45265   {
45266     if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
45267       for(i=1; i<WAL_NREADER; i++){
45268         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45269         if( rc==SQLITE_OK ){
45270           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45271           mxI = i;
45272           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45273           break;
45274         }else if( rc!=SQLITE_BUSY ){
45275           return rc;
45276         }
45277       }
45278     }
45279     if( mxI==0 ){
45280       assert( rc==SQLITE_BUSY );
45281       return WAL_RETRY;
45282     }
45283
45284     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45285     if( rc ){
45286       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45287     }
45288     /* Now that the read-lock has been obtained, check that neither the
45289     ** value in the aReadMark[] array or the contents of the wal-index
45290     ** header have changed.
45291     **
45292     ** It is necessary to check that the wal-index header did not change
45293     ** between the time it was read and when the shared-lock was obtained
45294     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45295     ** that the log file may have been wrapped by a writer, or that frames
45296     ** that occur later in the log than pWal->hdr.mxFrame may have been
45297     ** copied into the database by a checkpointer. If either of these things
45298     ** happened, then reading the database with the current value of
45299     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45300     ** instead.
45301     **
45302     ** This does not guarantee that the copy of the wal-index header is up to
45303     ** date before proceeding. That would not be possible without somehow
45304     ** blocking writers. It only guarantees that a dangerous checkpoint or 
45305     ** log-wrap (either of which would require an exclusive lock on
45306     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45307     */
45308     walShmBarrier(pWal);
45309     if( pInfo->aReadMark[mxI]!=mxReadMark
45310      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45311     ){
45312       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45313       return WAL_RETRY;
45314     }else{
45315       assert( mxReadMark<=pWal->hdr.mxFrame );
45316       pWal->readLock = (i16)mxI;
45317     }
45318   }
45319   return rc;
45320 }
45321
45322 /*
45323 ** Begin a read transaction on the database.
45324 **
45325 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45326 ** it takes a snapshot of the state of the WAL and wal-index for the current
45327 ** instant in time.  The current thread will continue to use this snapshot.
45328 ** Other threads might append new content to the WAL and wal-index but
45329 ** that extra content is ignored by the current thread.
45330 **
45331 ** If the database contents have changes since the previous read
45332 ** transaction, then *pChanged is set to 1 before returning.  The
45333 ** Pager layer will use this to know that is cache is stale and
45334 ** needs to be flushed.
45335 */
45336 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45337   int rc;                         /* Return code */
45338   int cnt = 0;                    /* Number of TryBeginRead attempts */
45339
45340   do{
45341     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45342   }while( rc==WAL_RETRY );
45343   testcase( (rc&0xff)==SQLITE_BUSY );
45344   testcase( (rc&0xff)==SQLITE_IOERR );
45345   testcase( rc==SQLITE_PROTOCOL );
45346   testcase( rc==SQLITE_OK );
45347   return rc;
45348 }
45349
45350 /*
45351 ** Finish with a read transaction.  All this does is release the
45352 ** read-lock.
45353 */
45354 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45355   sqlite3WalEndWriteTransaction(pWal);
45356   if( pWal->readLock>=0 ){
45357     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45358     pWal->readLock = -1;
45359   }
45360 }
45361
45362 /*
45363 ** Read a page from the WAL, if it is present in the WAL and if the 
45364 ** current read transaction is configured to use the WAL.  
45365 **
45366 ** The *pInWal is set to 1 if the requested page is in the WAL and
45367 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
45368 ** the WAL and needs to be read out of the database.
45369 */
45370 SQLITE_PRIVATE int sqlite3WalRead(
45371   Wal *pWal,                      /* WAL handle */
45372   Pgno pgno,                      /* Database page number to read data for */
45373   int *pInWal,                    /* OUT: True if data is read from WAL */
45374   int nOut,                       /* Size of buffer pOut in bytes */
45375   u8 *pOut                        /* Buffer to write page data to */
45376 ){
45377   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
45378   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
45379   int iHash;                      /* Used to loop through N hash tables */
45380
45381   /* This routine is only be called from within a read transaction. */
45382   assert( pWal->readLock>=0 || pWal->lockError );
45383
45384   /* If the "last page" field of the wal-index header snapshot is 0, then
45385   ** no data will be read from the wal under any circumstances. Return early
45386   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
45387   ** then the WAL is ignored by the reader so return early, as if the 
45388   ** WAL were empty.
45389   */
45390   if( iLast==0 || pWal->readLock==0 ){
45391     *pInWal = 0;
45392     return SQLITE_OK;
45393   }
45394
45395   /* Search the hash table or tables for an entry matching page number
45396   ** pgno. Each iteration of the following for() loop searches one
45397   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45398   **
45399   ** This code might run concurrently to the code in walIndexAppend()
45400   ** that adds entries to the wal-index (and possibly to this hash 
45401   ** table). This means the value just read from the hash 
45402   ** slot (aHash[iKey]) may have been added before or after the 
45403   ** current read transaction was opened. Values added after the
45404   ** read transaction was opened may have been written incorrectly -
45405   ** i.e. these slots may contain garbage data. However, we assume
45406   ** that any slots written before the current read transaction was
45407   ** opened remain unmodified.
45408   **
45409   ** For the reasons above, the if(...) condition featured in the inner
45410   ** loop of the following block is more stringent that would be required 
45411   ** if we had exclusive access to the hash-table:
45412   **
45413   **   (aPgno[iFrame]==pgno): 
45414   **     This condition filters out normal hash-table collisions.
45415   **
45416   **   (iFrame<=iLast): 
45417   **     This condition filters out entries that were added to the hash
45418   **     table after the current read-transaction had started.
45419   */
45420   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45421     volatile ht_slot *aHash;      /* Pointer to hash table */
45422     volatile u32 *aPgno;          /* Pointer to array of page numbers */
45423     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
45424     int iKey;                     /* Hash slot index */
45425     int nCollide;                 /* Number of hash collisions remaining */
45426     int rc;                       /* Error code */
45427
45428     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45429     if( rc!=SQLITE_OK ){
45430       return rc;
45431     }
45432     nCollide = HASHTABLE_NSLOT;
45433     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45434       u32 iFrame = aHash[iKey] + iZero;
45435       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45436         assert( iFrame>iRead );
45437         iRead = iFrame;
45438       }
45439       if( (nCollide--)==0 ){
45440         return SQLITE_CORRUPT_BKPT;
45441       }
45442     }
45443   }
45444
45445 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45446   /* If expensive assert() statements are available, do a linear search
45447   ** of the wal-index file content. Make sure the results agree with the
45448   ** result obtained using the hash indexes above.  */
45449   {
45450     u32 iRead2 = 0;
45451     u32 iTest;
45452     for(iTest=iLast; iTest>0; iTest--){
45453       if( walFramePgno(pWal, iTest)==pgno ){
45454         iRead2 = iTest;
45455         break;
45456       }
45457     }
45458     assert( iRead==iRead2 );
45459   }
45460 #endif
45461
45462   /* If iRead is non-zero, then it is the log frame number that contains the
45463   ** required page. Read and return data from the log file.
45464   */
45465   if( iRead ){
45466     int sz;
45467     i64 iOffset;
45468     sz = pWal->hdr.szPage;
45469     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45470     testcase( sz<=32768 );
45471     testcase( sz>=65536 );
45472     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45473     *pInWal = 1;
45474     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45475     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45476   }
45477
45478   *pInWal = 0;
45479   return SQLITE_OK;
45480 }
45481
45482
45483 /* 
45484 ** Return the size of the database in pages (or zero, if unknown).
45485 */
45486 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45487   if( pWal && ALWAYS(pWal->readLock>=0) ){
45488     return pWal->hdr.nPage;
45489   }
45490   return 0;
45491 }
45492
45493
45494 /* 
45495 ** This function starts a write transaction on the WAL.
45496 **
45497 ** A read transaction must have already been started by a prior call
45498 ** to sqlite3WalBeginReadTransaction().
45499 **
45500 ** If another thread or process has written into the database since
45501 ** the read transaction was started, then it is not possible for this
45502 ** thread to write as doing so would cause a fork.  So this routine
45503 ** returns SQLITE_BUSY in that case and no write transaction is started.
45504 **
45505 ** There can only be a single writer active at a time.
45506 */
45507 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
45508   int rc;
45509
45510   /* Cannot start a write transaction without first holding a read
45511   ** transaction. */
45512   assert( pWal->readLock>=0 );
45513
45514   if( pWal->readOnly ){
45515     return SQLITE_READONLY;
45516   }
45517
45518   /* Only one writer allowed at a time.  Get the write lock.  Return
45519   ** SQLITE_BUSY if unable.
45520   */
45521   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
45522   if( rc ){
45523     return rc;
45524   }
45525   pWal->writeLock = 1;
45526
45527   /* If another connection has written to the database file since the
45528   ** time the read transaction on this connection was started, then
45529   ** the write is disallowed.
45530   */
45531   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
45532     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45533     pWal->writeLock = 0;
45534     rc = SQLITE_BUSY;
45535   }
45536
45537   return rc;
45538 }
45539
45540 /*
45541 ** End a write transaction.  The commit has already been done.  This
45542 ** routine merely releases the lock.
45543 */
45544 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
45545   if( pWal->writeLock ){
45546     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45547     pWal->writeLock = 0;
45548   }
45549   return SQLITE_OK;
45550 }
45551
45552 /*
45553 ** If any data has been written (but not committed) to the log file, this
45554 ** function moves the write-pointer back to the start of the transaction.
45555 **
45556 ** Additionally, the callback function is invoked for each frame written
45557 ** to the WAL since the start of the transaction. If the callback returns
45558 ** other than SQLITE_OK, it is not invoked again and the error code is
45559 ** returned to the caller.
45560 **
45561 ** Otherwise, if the callback function does not return an error, this
45562 ** function returns SQLITE_OK.
45563 */
45564 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
45565   int rc = SQLITE_OK;
45566   if( ALWAYS(pWal->writeLock) ){
45567     Pgno iMax = pWal->hdr.mxFrame;
45568     Pgno iFrame;
45569   
45570     /* Restore the clients cache of the wal-index header to the state it
45571     ** was in before the client began writing to the database. 
45572     */
45573     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
45574
45575     for(iFrame=pWal->hdr.mxFrame+1; 
45576         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
45577         iFrame++
45578     ){
45579       /* This call cannot fail. Unless the page for which the page number
45580       ** is passed as the second argument is (a) in the cache and 
45581       ** (b) has an outstanding reference, then xUndo is either a no-op
45582       ** (if (a) is false) or simply expels the page from the cache (if (b)
45583       ** is false).
45584       **
45585       ** If the upper layer is doing a rollback, it is guaranteed that there
45586       ** are no outstanding references to any page other than page 1. And
45587       ** page 1 is never written to the log until the transaction is
45588       ** committed. As a result, the call to xUndo may not fail.
45589       */
45590       assert( walFramePgno(pWal, iFrame)!=1 );
45591       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
45592     }
45593     walCleanupHash(pWal);
45594   }
45595   assert( rc==SQLITE_OK );
45596   return rc;
45597 }
45598
45599 /* 
45600 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
45601 ** values. This function populates the array with values required to 
45602 ** "rollback" the write position of the WAL handle back to the current 
45603 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
45604 */
45605 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
45606   assert( pWal->writeLock );
45607   aWalData[0] = pWal->hdr.mxFrame;
45608   aWalData[1] = pWal->hdr.aFrameCksum[0];
45609   aWalData[2] = pWal->hdr.aFrameCksum[1];
45610   aWalData[3] = pWal->nCkpt;
45611 }
45612
45613 /* 
45614 ** Move the write position of the WAL back to the point identified by
45615 ** the values in the aWalData[] array. aWalData must point to an array
45616 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
45617 ** by a call to WalSavepoint().
45618 */
45619 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
45620   int rc = SQLITE_OK;
45621
45622   assert( pWal->writeLock );
45623   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
45624
45625   if( aWalData[3]!=pWal->nCkpt ){
45626     /* This savepoint was opened immediately after the write-transaction
45627     ** was started. Right after that, the writer decided to wrap around
45628     ** to the start of the log. Update the savepoint values to match.
45629     */
45630     aWalData[0] = 0;
45631     aWalData[3] = pWal->nCkpt;
45632   }
45633
45634   if( aWalData[0]<pWal->hdr.mxFrame ){
45635     pWal->hdr.mxFrame = aWalData[0];
45636     pWal->hdr.aFrameCksum[0] = aWalData[1];
45637     pWal->hdr.aFrameCksum[1] = aWalData[2];
45638     walCleanupHash(pWal);
45639   }
45640
45641   return rc;
45642 }
45643
45644 /*
45645 ** This function is called just before writing a set of frames to the log
45646 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
45647 ** to the current log file, it is possible to overwrite the start of the
45648 ** existing log file with the new frames (i.e. "reset" the log). If so,
45649 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
45650 ** unchanged.
45651 **
45652 ** SQLITE_OK is returned if no error is encountered (regardless of whether
45653 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
45654 ** if an error occurs.
45655 */
45656 static int walRestartLog(Wal *pWal){
45657   int rc = SQLITE_OK;
45658   int cnt;
45659
45660   if( pWal->readLock==0 ){
45661     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
45662     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
45663     if( pInfo->nBackfill>0 ){
45664       u32 salt1;
45665       sqlite3_randomness(4, &salt1);
45666       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45667       if( rc==SQLITE_OK ){
45668         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
45669         ** readers are currently using the WAL), then the transactions
45670         ** frames will overwrite the start of the existing log. Update the
45671         ** wal-index header to reflect this.
45672         **
45673         ** In theory it would be Ok to update the cache of the header only
45674         ** at this point. But updating the actual wal-index header is also
45675         ** safe and means there is no special case for sqlite3WalUndo()
45676         ** to handle if this transaction is rolled back.
45677         */
45678         int i;                    /* Loop counter */
45679         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
45680         pWal->nCkpt++;
45681         pWal->hdr.mxFrame = 0;
45682         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
45683         aSalt[1] = salt1;
45684         walIndexWriteHdr(pWal);
45685         pInfo->nBackfill = 0;
45686         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45687         assert( pInfo->aReadMark[0]==0 );
45688         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45689       }else if( rc!=SQLITE_BUSY ){
45690         return rc;
45691       }
45692     }
45693     walUnlockShared(pWal, WAL_READ_LOCK(0));
45694     pWal->readLock = -1;
45695     cnt = 0;
45696     do{
45697       int notUsed;
45698       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
45699     }while( rc==WAL_RETRY );
45700     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
45701     testcase( (rc&0xff)==SQLITE_IOERR );
45702     testcase( rc==SQLITE_PROTOCOL );
45703     testcase( rc==SQLITE_OK );
45704   }
45705   return rc;
45706 }
45707
45708 /* 
45709 ** Write a set of frames to the log. The caller must hold the write-lock
45710 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
45711 */
45712 SQLITE_PRIVATE int sqlite3WalFrames(
45713   Wal *pWal,                      /* Wal handle to write to */
45714   int szPage,                     /* Database page-size in bytes */
45715   PgHdr *pList,                   /* List of dirty pages to write */
45716   Pgno nTruncate,                 /* Database size after this commit */
45717   int isCommit,                   /* True if this is a commit */
45718   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
45719 ){
45720   int rc;                         /* Used to catch return codes */
45721   u32 iFrame;                     /* Next frame address */
45722   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
45723   PgHdr *p;                       /* Iterator to run through pList with. */
45724   PgHdr *pLast = 0;               /* Last frame in list */
45725   int nLast = 0;                  /* Number of extra copies of last page */
45726
45727   assert( pList );
45728   assert( pWal->writeLock );
45729
45730 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45731   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
45732     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
45733               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
45734   }
45735 #endif
45736
45737   /* See if it is possible to write these frames into the start of the
45738   ** log file, instead of appending to it at pWal->hdr.mxFrame.
45739   */
45740   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
45741     return rc;
45742   }
45743
45744   /* If this is the first frame written into the log, write the WAL
45745   ** header to the start of the WAL file. See comments at the top of
45746   ** this source file for a description of the WAL header format.
45747   */
45748   iFrame = pWal->hdr.mxFrame;
45749   if( iFrame==0 ){
45750     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
45751     u32 aCksum[2];                /* Checksum for wal-header */
45752
45753     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
45754     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
45755     sqlite3Put4byte(&aWalHdr[8], szPage);
45756     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
45757     sqlite3_randomness(8, pWal->hdr.aSalt);
45758     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
45759     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
45760     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
45761     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
45762     
45763     pWal->szPage = szPage;
45764     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
45765     pWal->hdr.aFrameCksum[0] = aCksum[0];
45766     pWal->hdr.aFrameCksum[1] = aCksum[1];
45767
45768     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
45769     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
45770     if( rc!=SQLITE_OK ){
45771       return rc;
45772     }
45773   }
45774   assert( (int)pWal->szPage==szPage );
45775
45776   /* Write the log file. */
45777   for(p=pList; p; p=p->pDirty){
45778     u32 nDbsize;                  /* Db-size field for frame header */
45779     i64 iOffset;                  /* Write offset in log file */
45780     void *pData;
45781    
45782     iOffset = walFrameOffset(++iFrame, szPage);
45783     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45784     
45785     /* Populate and write the frame header */
45786     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
45787 #if defined(SQLITE_HAS_CODEC)
45788     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
45789 #else
45790     pData = p->pData;
45791 #endif
45792     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
45793     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45794     if( rc!=SQLITE_OK ){
45795       return rc;
45796     }
45797
45798     /* Write the page data */
45799     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
45800     if( rc!=SQLITE_OK ){
45801       return rc;
45802     }
45803     pLast = p;
45804   }
45805
45806   /* Sync the log file if the 'isSync' flag was specified. */
45807   if( sync_flags ){
45808     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
45809     i64 iOffset = walFrameOffset(iFrame+1, szPage);
45810
45811     assert( isCommit );
45812     assert( iSegment>0 );
45813
45814     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
45815     while( iOffset<iSegment ){
45816       void *pData;
45817 #if defined(SQLITE_HAS_CODEC)
45818       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
45819 #else
45820       pData = pLast->pData;
45821 #endif
45822       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
45823       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45824       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
45825       if( rc!=SQLITE_OK ){
45826         return rc;
45827       }
45828       iOffset += WAL_FRAME_HDRSIZE;
45829       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
45830       if( rc!=SQLITE_OK ){
45831         return rc;
45832       }
45833       nLast++;
45834       iOffset += szPage;
45835     }
45836
45837     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45838   }
45839
45840   /* Append data to the wal-index. It is not necessary to lock the 
45841   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
45842   ** guarantees that there are no other writers, and no data that may
45843   ** be in use by existing readers is being overwritten.
45844   */
45845   iFrame = pWal->hdr.mxFrame;
45846   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
45847     iFrame++;
45848     rc = walIndexAppend(pWal, iFrame, p->pgno);
45849   }
45850   while( nLast>0 && rc==SQLITE_OK ){
45851     iFrame++;
45852     nLast--;
45853     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
45854   }
45855
45856   if( rc==SQLITE_OK ){
45857     /* Update the private copy of the header. */
45858     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45859     testcase( szPage<=32768 );
45860     testcase( szPage>=65536 );
45861     pWal->hdr.mxFrame = iFrame;
45862     if( isCommit ){
45863       pWal->hdr.iChange++;
45864       pWal->hdr.nPage = nTruncate;
45865     }
45866     /* If this is a commit, update the wal-index header too. */
45867     if( isCommit ){
45868       walIndexWriteHdr(pWal);
45869       pWal->iCallback = iFrame;
45870     }
45871   }
45872
45873   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
45874   return rc;
45875 }
45876
45877 /* 
45878 ** This routine is called to implement sqlite3_wal_checkpoint() and
45879 ** related interfaces.
45880 **
45881 ** Obtain a CHECKPOINT lock and then backfill as much information as
45882 ** we can from WAL into the database.
45883 **
45884 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
45885 ** callback. In this case this function runs a blocking checkpoint.
45886 */
45887 SQLITE_PRIVATE int sqlite3WalCheckpoint(
45888   Wal *pWal,                      /* Wal connection */
45889   int eMode,                      /* PASSIVE, FULL or RESTART */
45890   int (*xBusy)(void*),            /* Function to call when busy */
45891   void *pBusyArg,                 /* Context argument for xBusyHandler */
45892   int sync_flags,                 /* Flags to sync db file with (or 0) */
45893   int nBuf,                       /* Size of temporary buffer */
45894   u8 *zBuf,                       /* Temporary buffer to use */
45895   int *pnLog,                     /* OUT: Number of frames in WAL */
45896   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
45897 ){
45898   int rc;                         /* Return code */
45899   int isChanged = 0;              /* True if a new wal-index header is loaded */
45900   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
45901
45902   assert( pWal->ckptLock==0 );
45903   assert( pWal->writeLock==0 );
45904
45905   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
45906   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
45907   if( rc ){
45908     /* Usually this is SQLITE_BUSY meaning that another thread or process
45909     ** is already running a checkpoint, or maybe a recovery.  But it might
45910     ** also be SQLITE_IOERR. */
45911     return rc;
45912   }
45913   pWal->ckptLock = 1;
45914
45915   /* If this is a blocking-checkpoint, then obtain the write-lock as well
45916   ** to prevent any writers from running while the checkpoint is underway.
45917   ** This has to be done before the call to walIndexReadHdr() below.
45918   **
45919   ** If the writer lock cannot be obtained, then a passive checkpoint is
45920   ** run instead. Since the checkpointer is not holding the writer lock,
45921   ** there is no point in blocking waiting for any readers. Assuming no 
45922   ** other error occurs, this function will return SQLITE_BUSY to the caller.
45923   */
45924   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45925     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
45926     if( rc==SQLITE_OK ){
45927       pWal->writeLock = 1;
45928     }else if( rc==SQLITE_BUSY ){
45929       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
45930       rc = SQLITE_OK;
45931     }
45932   }
45933
45934   /* Read the wal-index header. */
45935   if( rc==SQLITE_OK ){
45936     rc = walIndexReadHdr(pWal, &isChanged);
45937   }
45938
45939   /* Copy data from the log to the database file. */
45940   if( rc==SQLITE_OK ){
45941     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
45942       rc = SQLITE_CORRUPT_BKPT;
45943     }else{
45944       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
45945     }
45946
45947     /* If no error occurred, set the output variables. */
45948     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
45949       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
45950       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
45951     }
45952   }
45953
45954   if( isChanged ){
45955     /* If a new wal-index header was loaded before the checkpoint was 
45956     ** performed, then the pager-cache associated with pWal is now
45957     ** out of date. So zero the cached wal-index header to ensure that
45958     ** next time the pager opens a snapshot on this database it knows that
45959     ** the cache needs to be reset.
45960     */
45961     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45962   }
45963
45964   /* Release the locks. */
45965   sqlite3WalEndWriteTransaction(pWal);
45966   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
45967   pWal->ckptLock = 0;
45968   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
45969   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
45970 }
45971
45972 /* Return the value to pass to a sqlite3_wal_hook callback, the
45973 ** number of frames in the WAL at the point of the last commit since
45974 ** sqlite3WalCallback() was called.  If no commits have occurred since
45975 ** the last call, then return 0.
45976 */
45977 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
45978   u32 ret = 0;
45979   if( pWal ){
45980     ret = pWal->iCallback;
45981     pWal->iCallback = 0;
45982   }
45983   return (int)ret;
45984 }
45985
45986 /*
45987 ** This function is called to change the WAL subsystem into or out
45988 ** of locking_mode=EXCLUSIVE.
45989 **
45990 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
45991 ** into locking_mode=NORMAL.  This means that we must acquire a lock
45992 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
45993 ** or if the acquisition of the lock fails, then return 0.  If the
45994 ** transition out of exclusive-mode is successful, return 1.  This
45995 ** operation must occur while the pager is still holding the exclusive
45996 ** lock on the main database file.
45997 **
45998 ** If op is one, then change from locking_mode=NORMAL into 
45999 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
46000 ** be released.  Return 1 if the transition is made and 0 if the
46001 ** WAL is already in exclusive-locking mode - meaning that this
46002 ** routine is a no-op.  The pager must already hold the exclusive lock
46003 ** on the main database file before invoking this operation.
46004 **
46005 ** If op is negative, then do a dry-run of the op==1 case but do
46006 ** not actually change anything. The pager uses this to see if it
46007 ** should acquire the database exclusive lock prior to invoking
46008 ** the op==1 case.
46009 */
46010 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46011   int rc;
46012   assert( pWal->writeLock==0 );
46013   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46014
46015   /* pWal->readLock is usually set, but might be -1 if there was a 
46016   ** prior error while attempting to acquire are read-lock. This cannot 
46017   ** happen if the connection is actually in exclusive mode (as no xShmLock
46018   ** locks are taken in this case). Nor should the pager attempt to
46019   ** upgrade to exclusive-mode following such an error.
46020   */
46021   assert( pWal->readLock>=0 || pWal->lockError );
46022   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46023
46024   if( op==0 ){
46025     if( pWal->exclusiveMode ){
46026       pWal->exclusiveMode = 0;
46027       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46028         pWal->exclusiveMode = 1;
46029       }
46030       rc = pWal->exclusiveMode==0;
46031     }else{
46032       /* Already in locking_mode=NORMAL */
46033       rc = 0;
46034     }
46035   }else if( op>0 ){
46036     assert( pWal->exclusiveMode==0 );
46037     assert( pWal->readLock>=0 );
46038     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46039     pWal->exclusiveMode = 1;
46040     rc = 1;
46041   }else{
46042     rc = pWal->exclusiveMode==0;
46043   }
46044   return rc;
46045 }
46046
46047 /* 
46048 ** Return true if the argument is non-NULL and the WAL module is using
46049 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46050 ** WAL module is using shared-memory, return false. 
46051 */
46052 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46053   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46054 }
46055
46056 #endif /* #ifndef SQLITE_OMIT_WAL */
46057
46058 /************** End of wal.c *************************************************/
46059 /************** Begin file btmutex.c *****************************************/
46060 /*
46061 ** 2007 August 27
46062 **
46063 ** The author disclaims copyright to this source code.  In place of
46064 ** a legal notice, here is a blessing:
46065 **
46066 **    May you do good and not evil.
46067 **    May you find forgiveness for yourself and forgive others.
46068 **    May you share freely, never taking more than you give.
46069 **
46070 *************************************************************************
46071 **
46072 ** This file contains code used to implement mutexes on Btree objects.
46073 ** This code really belongs in btree.c.  But btree.c is getting too
46074 ** big and we want to break it down some.  This packaged seemed like
46075 ** a good breakout.
46076 */
46077 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46078 /************** Begin file btreeInt.h ****************************************/
46079 /*
46080 ** 2004 April 6
46081 **
46082 ** The author disclaims copyright to this source code.  In place of
46083 ** a legal notice, here is a blessing:
46084 **
46085 **    May you do good and not evil.
46086 **    May you find forgiveness for yourself and forgive others.
46087 **    May you share freely, never taking more than you give.
46088 **
46089 *************************************************************************
46090 ** This file implements a external (disk-based) database using BTrees.
46091 ** For a detailed discussion of BTrees, refer to
46092 **
46093 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46094 **     "Sorting And Searching", pages 473-480. Addison-Wesley
46095 **     Publishing Company, Reading, Massachusetts.
46096 **
46097 ** The basic idea is that each page of the file contains N database
46098 ** entries and N+1 pointers to subpages.
46099 **
46100 **   ----------------------------------------------------------------
46101 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46102 **   ----------------------------------------------------------------
46103 **
46104 ** All of the keys on the page that Ptr(0) points to have values less
46105 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
46106 ** values greater than Key(0) and less than Key(1).  All of the keys
46107 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
46108 ** so forth.
46109 **
46110 ** Finding a particular key requires reading O(log(M)) pages from the 
46111 ** disk where M is the number of entries in the tree.
46112 **
46113 ** In this implementation, a single file can hold one or more separate 
46114 ** BTrees.  Each BTree is identified by the index of its root page.  The
46115 ** key and data for any entry are combined to form the "payload".  A
46116 ** fixed amount of payload can be carried directly on the database
46117 ** page.  If the payload is larger than the preset amount then surplus
46118 ** bytes are stored on overflow pages.  The payload for an entry
46119 ** and the preceding pointer are combined to form a "Cell".  Each 
46120 ** page has a small header which contains the Ptr(N) pointer and other
46121 ** information such as the size of key and data.
46122 **
46123 ** FORMAT DETAILS
46124 **
46125 ** The file is divided into pages.  The first page is called page 1,
46126 ** the second is page 2, and so forth.  A page number of zero indicates
46127 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
46128 ** Each page can be either a btree page, a freelist page, an overflow
46129 ** page, or a pointer-map page.
46130 **
46131 ** The first page is always a btree page.  The first 100 bytes of the first
46132 ** page contain a special header (the "file header") that describes the file.
46133 ** The format of the file header is as follows:
46134 **
46135 **   OFFSET   SIZE    DESCRIPTION
46136 **      0      16     Header string: "SQLite format 3\000"
46137 **     16       2     Page size in bytes.  
46138 **     18       1     File format write version
46139 **     19       1     File format read version
46140 **     20       1     Bytes of unused space at the end of each page
46141 **     21       1     Max embedded payload fraction
46142 **     22       1     Min embedded payload fraction
46143 **     23       1     Min leaf payload fraction
46144 **     24       4     File change counter
46145 **     28       4     Reserved for future use
46146 **     32       4     First freelist page
46147 **     36       4     Number of freelist pages in the file
46148 **     40      60     15 4-byte meta values passed to higher layers
46149 **
46150 **     40       4     Schema cookie
46151 **     44       4     File format of schema layer
46152 **     48       4     Size of page cache
46153 **     52       4     Largest root-page (auto/incr_vacuum)
46154 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
46155 **     60       4     User version
46156 **     64       4     Incremental vacuum mode
46157 **     68       4     unused
46158 **     72       4     unused
46159 **     76       4     unused
46160 **
46161 ** All of the integer values are big-endian (most significant byte first).
46162 **
46163 ** The file change counter is incremented when the database is changed
46164 ** This counter allows other processes to know when the file has changed
46165 ** and thus when they need to flush their cache.
46166 **
46167 ** The max embedded payload fraction is the amount of the total usable
46168 ** space in a page that can be consumed by a single cell for standard
46169 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
46170 ** is to limit the maximum cell size so that at least 4 cells will fit
46171 ** on one page.  Thus the default max embedded payload fraction is 64.
46172 **
46173 ** If the payload for a cell is larger than the max payload, then extra
46174 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
46175 ** as many bytes as possible are moved into the overflow pages without letting
46176 ** the cell size drop below the min embedded payload fraction.
46177 **
46178 ** The min leaf payload fraction is like the min embedded payload fraction
46179 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
46180 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46181 ** not specified in the header.
46182 **
46183 ** Each btree pages is divided into three sections:  The header, the
46184 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
46185 ** file header that occurs before the page header.
46186 **
46187 **      |----------------|
46188 **      | file header    |   100 bytes.  Page 1 only.
46189 **      |----------------|
46190 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
46191 **      |----------------|
46192 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
46193 **      | array          |   |  Grows downward
46194 **      |                |   v
46195 **      |----------------|
46196 **      | unallocated    |
46197 **      | space          |
46198 **      |----------------|   ^  Grows upwards
46199 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
46200 **      | area           |   |  and free space fragments.
46201 **      |----------------|
46202 **
46203 ** The page headers looks like this:
46204 **
46205 **   OFFSET   SIZE     DESCRIPTION
46206 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46207 **      1       2      byte offset to the first freeblock
46208 **      3       2      number of cells on this page
46209 **      5       2      first byte of the cell content area
46210 **      7       1      number of fragmented free bytes
46211 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
46212 **
46213 ** The flags define the format of this btree page.  The leaf flag means that
46214 ** this page has no children.  The zerodata flag means that this page carries
46215 ** only keys and no data.  The intkey flag means that the key is a integer
46216 ** which is stored in the key size entry of the cell header rather than in
46217 ** the payload area.
46218 **
46219 ** The cell pointer array begins on the first byte after the page header.
46220 ** The cell pointer array contains zero or more 2-byte numbers which are
46221 ** offsets from the beginning of the page to the cell content in the cell
46222 ** content area.  The cell pointers occur in sorted order.  The system strives
46223 ** to keep free space after the last cell pointer so that new cells can
46224 ** be easily added without having to defragment the page.
46225 **
46226 ** Cell content is stored at the very end of the page and grows toward the
46227 ** beginning of the page.
46228 **
46229 ** Unused space within the cell content area is collected into a linked list of
46230 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
46231 ** to the first freeblock is given in the header.  Freeblocks occur in
46232 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
46233 ** any group of 3 or fewer unused bytes in the cell content area cannot
46234 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
46235 ** a fragment.  The total number of bytes in all fragments is recorded.
46236 ** in the page header at offset 7.
46237 **
46238 **    SIZE    DESCRIPTION
46239 **      2     Byte offset of the next freeblock
46240 **      2     Bytes in this freeblock
46241 **
46242 ** Cells are of variable length.  Cells are stored in the cell content area at
46243 ** the end of the page.  Pointers to the cells are in the cell pointer array
46244 ** that immediately follows the page header.  Cells is not necessarily
46245 ** contiguous or in order, but cell pointers are contiguous and in order.
46246 **
46247 ** Cell content makes use of variable length integers.  A variable
46248 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
46249 ** byte are used.  The integer consists of all bytes that have bit 8 set and
46250 ** the first byte with bit 8 clear.  The most significant byte of the integer
46251 ** appears first.  A variable-length integer may not be more than 9 bytes long.
46252 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
46253 ** allows a 64-bit integer to be encoded in 9 bytes.
46254 **
46255 **    0x00                      becomes  0x00000000
46256 **    0x7f                      becomes  0x0000007f
46257 **    0x81 0x00                 becomes  0x00000080
46258 **    0x82 0x00                 becomes  0x00000100
46259 **    0x80 0x7f                 becomes  0x0000007f
46260 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
46261 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
46262 **
46263 ** Variable length integers are used for rowids and to hold the number of
46264 ** bytes of key and data in a btree cell.
46265 **
46266 ** The content of a cell looks like this:
46267 **
46268 **    SIZE    DESCRIPTION
46269 **      4     Page number of the left child. Omitted if leaf flag is set.
46270 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
46271 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
46272 **      *     Payload
46273 **      4     First page of the overflow chain.  Omitted if no overflow
46274 **
46275 ** Overflow pages form a linked list.  Each page except the last is completely
46276 ** filled with data (pagesize - 4 bytes).  The last page can have as little
46277 ** as 1 byte of data.
46278 **
46279 **    SIZE    DESCRIPTION
46280 **      4     Page number of next overflow page
46281 **      *     Data
46282 **
46283 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
46284 ** file header points to the first in a linked list of trunk page.  Each trunk
46285 ** page points to multiple leaf pages.  The content of a leaf page is
46286 ** unspecified.  A trunk page looks like this:
46287 **
46288 **    SIZE    DESCRIPTION
46289 **      4     Page number of next trunk page
46290 **      4     Number of leaf pointers on this page
46291 **      *     zero or more pages numbers of leaves
46292 */
46293
46294
46295 /* The following value is the maximum cell size assuming a maximum page
46296 ** size give above.
46297 */
46298 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
46299
46300 /* The maximum number of cells on a single page of the database.  This
46301 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
46302 ** plus 2 bytes for the index to the cell in the page header).  Such
46303 ** small cells will be rare, but they are possible.
46304 */
46305 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46306
46307 /* Forward declarations */
46308 typedef struct MemPage MemPage;
46309 typedef struct BtLock BtLock;
46310
46311 /*
46312 ** This is a magic string that appears at the beginning of every
46313 ** SQLite database in order to identify the file as a real database.
46314 **
46315 ** You can change this value at compile-time by specifying a
46316 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
46317 ** header must be exactly 16 bytes including the zero-terminator so
46318 ** the string itself should be 15 characters long.  If you change
46319 ** the header, then your custom library will not be able to read 
46320 ** databases generated by the standard tools and the standard tools
46321 ** will not be able to read databases created by your custom library.
46322 */
46323 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46324 #  define SQLITE_FILE_HEADER "SQLite format 3"
46325 #endif
46326
46327 /*
46328 ** Page type flags.  An ORed combination of these flags appear as the
46329 ** first byte of on-disk image of every BTree page.
46330 */
46331 #define PTF_INTKEY    0x01
46332 #define PTF_ZERODATA  0x02
46333 #define PTF_LEAFDATA  0x04
46334 #define PTF_LEAF      0x08
46335
46336 /*
46337 ** As each page of the file is loaded into memory, an instance of the following
46338 ** structure is appended and initialized to zero.  This structure stores
46339 ** information about the page that is decoded from the raw file page.
46340 **
46341 ** The pParent field points back to the parent page.  This allows us to
46342 ** walk up the BTree from any leaf to the root.  Care must be taken to
46343 ** unref() the parent page pointer when this page is no longer referenced.
46344 ** The pageDestructor() routine handles that chore.
46345 **
46346 ** Access to all fields of this structure is controlled by the mutex
46347 ** stored in MemPage.pBt->mutex.
46348 */
46349 struct MemPage {
46350   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
46351   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
46352   u8 intKey;           /* True if intkey flag is set */
46353   u8 leaf;             /* True if leaf flag is set */
46354   u8 hasData;          /* True if this page stores data */
46355   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
46356   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
46357   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46358   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
46359   u16 cellOffset;      /* Index in aData of first cell pointer */
46360   u16 nFree;           /* Number of free bytes on the page */
46361   u16 nCell;           /* Number of cells on this page, local and ovfl */
46362   u16 maskPage;        /* Mask for page offset */
46363   struct _OvflCell {   /* Cells that will not fit on aData[] */
46364     u8 *pCell;          /* Pointers to the body of the overflow cell */
46365     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
46366   } aOvfl[5];
46367   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
46368   u8 *aData;           /* Pointer to disk image of the page data */
46369   DbPage *pDbPage;     /* Pager page handle */
46370   Pgno pgno;           /* Page number for this page */
46371 };
46372
46373 /*
46374 ** The in-memory image of a disk page has the auxiliary information appended
46375 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
46376 ** that extra information.
46377 */
46378 #define EXTRA_SIZE sizeof(MemPage)
46379
46380 /*
46381 ** A linked list of the following structures is stored at BtShared.pLock.
46382 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
46383 ** is opened on the table with root page BtShared.iTable. Locks are removed
46384 ** from this list when a transaction is committed or rolled back, or when
46385 ** a btree handle is closed.
46386 */
46387 struct BtLock {
46388   Btree *pBtree;        /* Btree handle holding this lock */
46389   Pgno iTable;          /* Root page of table */
46390   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
46391   BtLock *pNext;        /* Next in BtShared.pLock list */
46392 };
46393
46394 /* Candidate values for BtLock.eLock */
46395 #define READ_LOCK     1
46396 #define WRITE_LOCK    2
46397
46398 /* A Btree handle
46399 **
46400 ** A database connection contains a pointer to an instance of
46401 ** this object for every database file that it has open.  This structure
46402 ** is opaque to the database connection.  The database connection cannot
46403 ** see the internals of this structure and only deals with pointers to
46404 ** this structure.
46405 **
46406 ** For some database files, the same underlying database cache might be 
46407 ** shared between multiple connections.  In that case, each connection
46408 ** has it own instance of this object.  But each instance of this object
46409 ** points to the same BtShared object.  The database cache and the
46410 ** schema associated with the database file are all contained within
46411 ** the BtShared object.
46412 **
46413 ** All fields in this structure are accessed under sqlite3.mutex.
46414 ** The pBt pointer itself may not be changed while there exists cursors 
46415 ** in the referenced BtShared that point back to this Btree since those
46416 ** cursors have to go through this Btree to find their BtShared and
46417 ** they often do so without holding sqlite3.mutex.
46418 */
46419 struct Btree {
46420   sqlite3 *db;       /* The database connection holding this btree */
46421   BtShared *pBt;     /* Sharable content of this btree */
46422   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46423   u8 sharable;       /* True if we can share pBt with another db */
46424   u8 locked;         /* True if db currently has pBt locked */
46425   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
46426   int nBackup;       /* Number of backup operations reading this btree */
46427   Btree *pNext;      /* List of other sharable Btrees from the same db */
46428   Btree *pPrev;      /* Back pointer of the same list */
46429 #ifndef SQLITE_OMIT_SHARED_CACHE
46430   BtLock lock;       /* Object used to lock page 1 */
46431 #endif
46432 };
46433
46434 /*
46435 ** Btree.inTrans may take one of the following values.
46436 **
46437 ** If the shared-data extension is enabled, there may be multiple users
46438 ** of the Btree structure. At most one of these may open a write transaction,
46439 ** but any number may have active read transactions.
46440 */
46441 #define TRANS_NONE  0
46442 #define TRANS_READ  1
46443 #define TRANS_WRITE 2
46444
46445 /*
46446 ** An instance of this object represents a single database file.
46447 ** 
46448 ** A single database file can be in use as the same time by two
46449 ** or more database connections.  When two or more connections are
46450 ** sharing the same database file, each connection has it own
46451 ** private Btree object for the file and each of those Btrees points
46452 ** to this one BtShared object.  BtShared.nRef is the number of
46453 ** connections currently sharing this database file.
46454 **
46455 ** Fields in this structure are accessed under the BtShared.mutex
46456 ** mutex, except for nRef and pNext which are accessed under the
46457 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
46458 ** may not be modified once it is initially set as long as nRef>0.
46459 ** The pSchema field may be set once under BtShared.mutex and
46460 ** thereafter is unchanged as long as nRef>0.
46461 **
46462 ** isPending:
46463 **
46464 **   If a BtShared client fails to obtain a write-lock on a database
46465 **   table (because there exists one or more read-locks on the table),
46466 **   the shared-cache enters 'pending-lock' state and isPending is
46467 **   set to true.
46468 **
46469 **   The shared-cache leaves the 'pending lock' state when either of
46470 **   the following occur:
46471 **
46472 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
46473 **     2) The number of locks held by other connections drops to zero.
46474 **
46475 **   while in the 'pending-lock' state, no connection may start a new
46476 **   transaction.
46477 **
46478 **   This feature is included to help prevent writer-starvation.
46479 */
46480 struct BtShared {
46481   Pager *pPager;        /* The page cache */
46482   sqlite3 *db;          /* Database connection currently using this Btree */
46483   BtCursor *pCursor;    /* A list of all open cursors */
46484   MemPage *pPage1;      /* First page of the database */
46485   u8 readOnly;          /* True if the underlying file is readonly */
46486   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
46487   u8 secureDelete;      /* True if secure_delete is enabled */
46488   u8 initiallyEmpty;    /* Database is empty at start of transaction */
46489   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
46490 #ifndef SQLITE_OMIT_AUTOVACUUM
46491   u8 autoVacuum;        /* True if auto-vacuum is enabled */
46492   u8 incrVacuum;        /* True if incr-vacuum is enabled */
46493 #endif
46494   u8 inTransaction;     /* Transaction state */
46495   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
46496   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
46497   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
46498   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
46499   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
46500   u32 pageSize;         /* Total number of bytes on a page */
46501   u32 usableSize;       /* Number of usable bytes on each page */
46502   int nTransaction;     /* Number of open transactions (read + write) */
46503   u32 nPage;            /* Number of pages in the database */
46504   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
46505   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
46506   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
46507   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
46508 #ifndef SQLITE_OMIT_SHARED_CACHE
46509   int nRef;             /* Number of references to this structure */
46510   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
46511   BtLock *pLock;        /* List of locks held on this shared-btree struct */
46512   Btree *pWriter;       /* Btree with currently open write transaction */
46513   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
46514   u8 isPending;         /* If waiting for read-locks to clear */
46515 #endif
46516   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
46517 };
46518
46519 /*
46520 ** An instance of the following structure is used to hold information
46521 ** about a cell.  The parseCellPtr() function fills in this structure
46522 ** based on information extract from the raw disk page.
46523 */
46524 typedef struct CellInfo CellInfo;
46525 struct CellInfo {
46526   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
46527   u8 *pCell;     /* Pointer to the start of cell content */
46528   u32 nData;     /* Number of bytes of data */
46529   u32 nPayload;  /* Total amount of payload */
46530   u16 nHeader;   /* Size of the cell content header in bytes */
46531   u16 nLocal;    /* Amount of payload held locally */
46532   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
46533   u16 nSize;     /* Size of the cell content on the main b-tree page */
46534 };
46535
46536 /*
46537 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
46538 ** this will be declared corrupt. This value is calculated based on a
46539 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
46540 ** root-node and 3 for all other internal nodes.
46541 **
46542 ** If a tree that appears to be taller than this is encountered, it is
46543 ** assumed that the database is corrupt.
46544 */
46545 #define BTCURSOR_MAX_DEPTH 20
46546
46547 /*
46548 ** A cursor is a pointer to a particular entry within a particular
46549 ** b-tree within a database file.
46550 **
46551 ** The entry is identified by its MemPage and the index in
46552 ** MemPage.aCell[] of the entry.
46553 **
46554 ** A single database file can shared by two more database connections,
46555 ** but cursors cannot be shared.  Each cursor is associated with a
46556 ** particular database connection identified BtCursor.pBtree.db.
46557 **
46558 ** Fields in this structure are accessed under the BtShared.mutex
46559 ** found at self->pBt->mutex. 
46560 */
46561 struct BtCursor {
46562   Btree *pBtree;            /* The Btree to which this cursor belongs */
46563   BtShared *pBt;            /* The BtShared this cursor points to */
46564   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
46565   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
46566   Pgno pgnoRoot;            /* The root page of this tree */
46567   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
46568   CellInfo info;            /* A parse of the cell we are pointing at */
46569   i64 nKey;        /* Size of pKey, or last integer key */
46570   void *pKey;      /* Saved key that was cursor's last known position */
46571   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
46572   u8 wrFlag;                /* True if writable */
46573   u8 atLast;                /* Cursor pointing to the last entry */
46574   u8 validNKey;             /* True if info.nKey is valid */
46575   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
46576 #ifndef SQLITE_OMIT_INCRBLOB
46577   Pgno *aOverflow;          /* Cache of overflow page locations */
46578   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
46579 #endif
46580   i16 iPage;                            /* Index of current page in apPage */
46581   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
46582   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
46583 };
46584
46585 /*
46586 ** Potential values for BtCursor.eState.
46587 **
46588 ** CURSOR_VALID:
46589 **   Cursor points to a valid entry. getPayload() etc. may be called.
46590 **
46591 ** CURSOR_INVALID:
46592 **   Cursor does not point to a valid entry. This can happen (for example) 
46593 **   because the table is empty or because BtreeCursorFirst() has not been
46594 **   called.
46595 **
46596 ** CURSOR_REQUIRESEEK:
46597 **   The table that this cursor was opened on still exists, but has been 
46598 **   modified since the cursor was last used. The cursor position is saved
46599 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
46600 **   this state, restoreCursorPosition() can be called to attempt to
46601 **   seek the cursor to the saved position.
46602 **
46603 ** CURSOR_FAULT:
46604 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
46605 **   on a different connection that shares the BtShared cache with this
46606 **   cursor.  The error has left the cache in an inconsistent state.
46607 **   Do nothing else with this cursor.  Any attempt to use the cursor
46608 **   should return the error code stored in BtCursor.skip
46609 */
46610 #define CURSOR_INVALID           0
46611 #define CURSOR_VALID             1
46612 #define CURSOR_REQUIRESEEK       2
46613 #define CURSOR_FAULT             3
46614
46615 /* 
46616 ** The database page the PENDING_BYTE occupies. This page is never used.
46617 */
46618 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
46619
46620 /*
46621 ** These macros define the location of the pointer-map entry for a 
46622 ** database page. The first argument to each is the number of usable
46623 ** bytes on each page of the database (often 1024). The second is the
46624 ** page number to look up in the pointer map.
46625 **
46626 ** PTRMAP_PAGENO returns the database page number of the pointer-map
46627 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
46628 ** the offset of the requested map entry.
46629 **
46630 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
46631 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
46632 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
46633 ** this test.
46634 */
46635 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
46636 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
46637 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
46638
46639 /*
46640 ** The pointer map is a lookup table that identifies the parent page for
46641 ** each child page in the database file.  The parent page is the page that
46642 ** contains a pointer to the child.  Every page in the database contains
46643 ** 0 or 1 parent pages.  (In this context 'database page' refers
46644 ** to any page that is not part of the pointer map itself.)  Each pointer map
46645 ** entry consists of a single byte 'type' and a 4 byte parent page number.
46646 ** The PTRMAP_XXX identifiers below are the valid types.
46647 **
46648 ** The purpose of the pointer map is to facility moving pages from one
46649 ** position in the file to another as part of autovacuum.  When a page
46650 ** is moved, the pointer in its parent must be updated to point to the
46651 ** new location.  The pointer map is used to locate the parent page quickly.
46652 **
46653 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
46654 **                  used in this case.
46655 **
46656 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
46657 **                  is not used in this case.
46658 **
46659 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
46660 **                   overflow pages. The page number identifies the page that
46661 **                   contains the cell with a pointer to this overflow page.
46662 **
46663 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
46664 **                   overflow pages. The page-number identifies the previous
46665 **                   page in the overflow page list.
46666 **
46667 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
46668 **               identifies the parent page in the btree.
46669 */
46670 #define PTRMAP_ROOTPAGE 1
46671 #define PTRMAP_FREEPAGE 2
46672 #define PTRMAP_OVERFLOW1 3
46673 #define PTRMAP_OVERFLOW2 4
46674 #define PTRMAP_BTREE 5
46675
46676 /* A bunch of assert() statements to check the transaction state variables
46677 ** of handle p (type Btree*) are internally consistent.
46678 */
46679 #define btreeIntegrity(p) \
46680   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
46681   assert( p->pBt->inTransaction>=p->inTrans ); 
46682
46683
46684 /*
46685 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
46686 ** if the database supports auto-vacuum or not. Because it is used
46687 ** within an expression that is an argument to another macro 
46688 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
46689 ** So, this macro is defined instead.
46690 */
46691 #ifndef SQLITE_OMIT_AUTOVACUUM
46692 #define ISAUTOVACUUM (pBt->autoVacuum)
46693 #else
46694 #define ISAUTOVACUUM 0
46695 #endif
46696
46697
46698 /*
46699 ** This structure is passed around through all the sanity checking routines
46700 ** in order to keep track of some global state information.
46701 */
46702 typedef struct IntegrityCk IntegrityCk;
46703 struct IntegrityCk {
46704   BtShared *pBt;    /* The tree being checked out */
46705   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
46706   Pgno nPage;       /* Number of pages in the database */
46707   int *anRef;       /* Number of times each page is referenced */
46708   int mxErr;        /* Stop accumulating errors when this reaches zero */
46709   int nErr;         /* Number of messages written to zErrMsg so far */
46710   int mallocFailed; /* A memory allocation error has occurred */
46711   StrAccum errMsg;  /* Accumulate the error message text here */
46712 };
46713
46714 /*
46715 ** Read or write a two- and four-byte big-endian integer values.
46716 */
46717 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
46718 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
46719 #define get4byte sqlite3Get4byte
46720 #define put4byte sqlite3Put4byte
46721
46722 /************** End of btreeInt.h ********************************************/
46723 /************** Continuing where we left off in btmutex.c ********************/
46724 #ifndef SQLITE_OMIT_SHARED_CACHE
46725 #if SQLITE_THREADSAFE
46726
46727 /*
46728 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
46729 ** set BtShared.db to the database handle associated with p and the
46730 ** p->locked boolean to true.
46731 */
46732 static void lockBtreeMutex(Btree *p){
46733   assert( p->locked==0 );
46734   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
46735   assert( sqlite3_mutex_held(p->db->mutex) );
46736
46737   sqlite3_mutex_enter(p->pBt->mutex);
46738   p->pBt->db = p->db;
46739   p->locked = 1;
46740 }
46741
46742 /*
46743 ** Release the BtShared mutex associated with B-Tree handle p and
46744 ** clear the p->locked boolean.
46745 */
46746 static void unlockBtreeMutex(Btree *p){
46747   BtShared *pBt = p->pBt;
46748   assert( p->locked==1 );
46749   assert( sqlite3_mutex_held(pBt->mutex) );
46750   assert( sqlite3_mutex_held(p->db->mutex) );
46751   assert( p->db==pBt->db );
46752
46753   sqlite3_mutex_leave(pBt->mutex);
46754   p->locked = 0;
46755 }
46756
46757 /*
46758 ** Enter a mutex on the given BTree object.
46759 **
46760 ** If the object is not sharable, then no mutex is ever required
46761 ** and this routine is a no-op.  The underlying mutex is non-recursive.
46762 ** But we keep a reference count in Btree.wantToLock so the behavior
46763 ** of this interface is recursive.
46764 **
46765 ** To avoid deadlocks, multiple Btrees are locked in the same order
46766 ** by all database connections.  The p->pNext is a list of other
46767 ** Btrees belonging to the same database connection as the p Btree
46768 ** which need to be locked after p.  If we cannot get a lock on
46769 ** p, then first unlock all of the others on p->pNext, then wait
46770 ** for the lock to become available on p, then relock all of the
46771 ** subsequent Btrees that desire a lock.
46772 */
46773 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
46774   Btree *pLater;
46775
46776   /* Some basic sanity checking on the Btree.  The list of Btrees
46777   ** connected by pNext and pPrev should be in sorted order by
46778   ** Btree.pBt value. All elements of the list should belong to
46779   ** the same connection. Only shared Btrees are on the list. */
46780   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
46781   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
46782   assert( p->pNext==0 || p->pNext->db==p->db );
46783   assert( p->pPrev==0 || p->pPrev->db==p->db );
46784   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
46785
46786   /* Check for locking consistency */
46787   assert( !p->locked || p->wantToLock>0 );
46788   assert( p->sharable || p->wantToLock==0 );
46789
46790   /* We should already hold a lock on the database connection */
46791   assert( sqlite3_mutex_held(p->db->mutex) );
46792
46793   /* Unless the database is sharable and unlocked, then BtShared.db
46794   ** should already be set correctly. */
46795   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
46796
46797   if( !p->sharable ) return;
46798   p->wantToLock++;
46799   if( p->locked ) return;
46800
46801   /* In most cases, we should be able to acquire the lock we
46802   ** want without having to go throught the ascending lock
46803   ** procedure that follows.  Just be sure not to block.
46804   */
46805   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
46806     p->pBt->db = p->db;
46807     p->locked = 1;
46808     return;
46809   }
46810
46811   /* To avoid deadlock, first release all locks with a larger
46812   ** BtShared address.  Then acquire our lock.  Then reacquire
46813   ** the other BtShared locks that we used to hold in ascending
46814   ** order.
46815   */
46816   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46817     assert( pLater->sharable );
46818     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
46819     assert( !pLater->locked || pLater->wantToLock>0 );
46820     if( pLater->locked ){
46821       unlockBtreeMutex(pLater);
46822     }
46823   }
46824   lockBtreeMutex(p);
46825   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
46826     if( pLater->wantToLock ){
46827       lockBtreeMutex(pLater);
46828     }
46829   }
46830 }
46831
46832 /*
46833 ** Exit the recursive mutex on a Btree.
46834 */
46835 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
46836   if( p->sharable ){
46837     assert( p->wantToLock>0 );
46838     p->wantToLock--;
46839     if( p->wantToLock==0 ){
46840       unlockBtreeMutex(p);
46841     }
46842   }
46843 }
46844
46845 #ifndef NDEBUG
46846 /*
46847 ** Return true if the BtShared mutex is held on the btree, or if the
46848 ** B-Tree is not marked as sharable.
46849 **
46850 ** This routine is used only from within assert() statements.
46851 */
46852 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
46853   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
46854   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
46855   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
46856   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
46857
46858   return (p->sharable==0 || p->locked);
46859 }
46860 #endif
46861
46862
46863 #ifndef SQLITE_OMIT_INCRBLOB
46864 /*
46865 ** Enter and leave a mutex on a Btree given a cursor owned by that
46866 ** Btree.  These entry points are used by incremental I/O and can be
46867 ** omitted if that module is not used.
46868 */
46869 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
46870   sqlite3BtreeEnter(pCur->pBtree);
46871 }
46872 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
46873   sqlite3BtreeLeave(pCur->pBtree);
46874 }
46875 #endif /* SQLITE_OMIT_INCRBLOB */
46876
46877
46878 /*
46879 ** Enter the mutex on every Btree associated with a database
46880 ** connection.  This is needed (for example) prior to parsing
46881 ** a statement since we will be comparing table and column names
46882 ** against all schemas and we do not want those schemas being
46883 ** reset out from under us.
46884 **
46885 ** There is a corresponding leave-all procedures.
46886 **
46887 ** Enter the mutexes in accending order by BtShared pointer address
46888 ** to avoid the possibility of deadlock when two threads with
46889 ** two or more btrees in common both try to lock all their btrees
46890 ** at the same instant.
46891 */
46892 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
46893   int i;
46894   Btree *p;
46895   assert( sqlite3_mutex_held(db->mutex) );
46896   for(i=0; i<db->nDb; i++){
46897     p = db->aDb[i].pBt;
46898     if( p ) sqlite3BtreeEnter(p);
46899   }
46900 }
46901 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
46902   int i;
46903   Btree *p;
46904   assert( sqlite3_mutex_held(db->mutex) );
46905   for(i=0; i<db->nDb; i++){
46906     p = db->aDb[i].pBt;
46907     if( p ) sqlite3BtreeLeave(p);
46908   }
46909 }
46910
46911 /*
46912 ** Return true if a particular Btree requires a lock.  Return FALSE if
46913 ** no lock is ever required since it is not sharable.
46914 */
46915 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
46916   return p->sharable;
46917 }
46918
46919 #ifndef NDEBUG
46920 /*
46921 ** Return true if the current thread holds the database connection
46922 ** mutex and all required BtShared mutexes.
46923 **
46924 ** This routine is used inside assert() statements only.
46925 */
46926 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
46927   int i;
46928   if( !sqlite3_mutex_held(db->mutex) ){
46929     return 0;
46930   }
46931   for(i=0; i<db->nDb; i++){
46932     Btree *p;
46933     p = db->aDb[i].pBt;
46934     if( p && p->sharable &&
46935          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
46936       return 0;
46937     }
46938   }
46939   return 1;
46940 }
46941 #endif /* NDEBUG */
46942
46943 #ifndef NDEBUG
46944 /*
46945 ** Return true if the correct mutexes are held for accessing the
46946 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
46947 ** access are:
46948 **
46949 **   (1) The mutex on db
46950 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
46951 **
46952 ** If pSchema is not NULL, then iDb is computed from pSchema and
46953 ** db using sqlite3SchemaToIndex().
46954 */
46955 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
46956   Btree *p;
46957   assert( db!=0 );
46958   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
46959   assert( iDb>=0 && iDb<db->nDb );
46960   if( !sqlite3_mutex_held(db->mutex) ) return 0;
46961   if( iDb==1 ) return 1;
46962   p = db->aDb[iDb].pBt;
46963   assert( p!=0 );
46964   return p->sharable==0 || p->locked==1;
46965 }
46966 #endif /* NDEBUG */
46967
46968 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
46969 /*
46970 ** The following are special cases for mutex enter routines for use
46971 ** in single threaded applications that use shared cache.  Except for
46972 ** these two routines, all mutex operations are no-ops in that case and
46973 ** are null #defines in btree.h.
46974 **
46975 ** If shared cache is disabled, then all btree mutex routines, including
46976 ** the ones below, are no-ops and are null #defines in btree.h.
46977 */
46978
46979 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
46980   p->pBt->db = p->db;
46981 }
46982 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
46983   int i;
46984   for(i=0; i<db->nDb; i++){
46985     Btree *p = db->aDb[i].pBt;
46986     if( p ){
46987       p->pBt->db = p->db;
46988     }
46989   }
46990 }
46991 #endif /* if SQLITE_THREADSAFE */
46992 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
46993
46994 /************** End of btmutex.c *********************************************/
46995 /************** Begin file btree.c *******************************************/
46996 /*
46997 ** 2004 April 6
46998 **
46999 ** The author disclaims copyright to this source code.  In place of
47000 ** a legal notice, here is a blessing:
47001 **
47002 **    May you do good and not evil.
47003 **    May you find forgiveness for yourself and forgive others.
47004 **    May you share freely, never taking more than you give.
47005 **
47006 *************************************************************************
47007 ** This file implements a external (disk-based) database using BTrees.
47008 ** See the header comment on "btreeInt.h" for additional information.
47009 ** Including a description of file format and an overview of operation.
47010 */
47011
47012 /*
47013 ** The header string that appears at the beginning of every
47014 ** SQLite database.
47015 */
47016 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47017
47018 /*
47019 ** Set this global variable to 1 to enable tracing using the TRACE
47020 ** macro.
47021 */
47022 #if 0
47023 int sqlite3BtreeTrace=1;  /* True to enable tracing */
47024 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47025 #else
47026 # define TRACE(X)
47027 #endif
47028
47029 /*
47030 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47031 ** But if the value is zero, make it 65536.
47032 **
47033 ** This routine is used to extract the "offset to cell content area" value
47034 ** from the header of a btree page.  If the page size is 65536 and the page
47035 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47036 ** This routine makes the necessary adjustment to 65536.
47037 */
47038 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
47039
47040 #ifndef SQLITE_OMIT_SHARED_CACHE
47041 /*
47042 ** A list of BtShared objects that are eligible for participation
47043 ** in shared cache.  This variable has file scope during normal builds,
47044 ** but the test harness needs to access it so we make it global for 
47045 ** test builds.
47046 **
47047 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47048 */
47049 #ifdef SQLITE_TEST
47050 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47051 #else
47052 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47053 #endif
47054 #endif /* SQLITE_OMIT_SHARED_CACHE */
47055
47056 #ifndef SQLITE_OMIT_SHARED_CACHE
47057 /*
47058 ** Enable or disable the shared pager and schema features.
47059 **
47060 ** This routine has no effect on existing database connections.
47061 ** The shared cache setting effects only future calls to
47062 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47063 */
47064 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47065   sqlite3GlobalConfig.sharedCacheEnabled = enable;
47066   return SQLITE_OK;
47067 }
47068 #endif
47069
47070
47071
47072 #ifdef SQLITE_OMIT_SHARED_CACHE
47073   /*
47074   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47075   ** and clearAllSharedCacheTableLocks()
47076   ** manipulate entries in the BtShared.pLock linked list used to store
47077   ** shared-cache table level locks. If the library is compiled with the
47078   ** shared-cache feature disabled, then there is only ever one user
47079   ** of each BtShared structure and so this locking is not necessary. 
47080   ** So define the lock related functions as no-ops.
47081   */
47082   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47083   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47084   #define clearAllSharedCacheTableLocks(a)
47085   #define downgradeAllSharedCacheTableLocks(a)
47086   #define hasSharedCacheTableLock(a,b,c,d) 1
47087   #define hasReadConflicts(a, b) 0
47088 #endif
47089
47090 #ifndef SQLITE_OMIT_SHARED_CACHE
47091
47092 #ifdef SQLITE_DEBUG
47093 /*
47094 **** This function is only used as part of an assert() statement. ***
47095 **
47096 ** Check to see if pBtree holds the required locks to read or write to the 
47097 ** table with root page iRoot.   Return 1 if it does and 0 if not.
47098 **
47099 ** For example, when writing to a table with root-page iRoot via 
47100 ** Btree connection pBtree:
47101 **
47102 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47103 **
47104 ** When writing to an index that resides in a sharable database, the 
47105 ** caller should have first obtained a lock specifying the root page of
47106 ** the corresponding table. This makes things a bit more complicated,
47107 ** as this module treats each table as a separate structure. To determine
47108 ** the table corresponding to the index being written, this
47109 ** function has to search through the database schema.
47110 **
47111 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
47112 ** hold a write-lock on the schema table (root page 1). This is also
47113 ** acceptable.
47114 */
47115 static int hasSharedCacheTableLock(
47116   Btree *pBtree,         /* Handle that must hold lock */
47117   Pgno iRoot,            /* Root page of b-tree */
47118   int isIndex,           /* True if iRoot is the root of an index b-tree */
47119   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
47120 ){
47121   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47122   Pgno iTab = 0;
47123   BtLock *pLock;
47124
47125   /* If this database is not shareable, or if the client is reading
47126   ** and has the read-uncommitted flag set, then no lock is required. 
47127   ** Return true immediately.
47128   */
47129   if( (pBtree->sharable==0)
47130    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47131   ){
47132     return 1;
47133   }
47134
47135   /* If the client is reading  or writing an index and the schema is
47136   ** not loaded, then it is too difficult to actually check to see if
47137   ** the correct locks are held.  So do not bother - just return true.
47138   ** This case does not come up very often anyhow.
47139   */
47140   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47141     return 1;
47142   }
47143
47144   /* Figure out the root-page that the lock should be held on. For table
47145   ** b-trees, this is just the root page of the b-tree being read or
47146   ** written. For index b-trees, it is the root page of the associated
47147   ** table.  */
47148   if( isIndex ){
47149     HashElem *p;
47150     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47151       Index *pIdx = (Index *)sqliteHashData(p);
47152       if( pIdx->tnum==(int)iRoot ){
47153         iTab = pIdx->pTable->tnum;
47154       }
47155     }
47156   }else{
47157     iTab = iRoot;
47158   }
47159
47160   /* Search for the required lock. Either a write-lock on root-page iTab, a 
47161   ** write-lock on the schema table, or (if the client is reading) a
47162   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
47163   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47164     if( pLock->pBtree==pBtree 
47165      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47166      && pLock->eLock>=eLockType 
47167     ){
47168       return 1;
47169     }
47170   }
47171
47172   /* Failed to find the required lock. */
47173   return 0;
47174 }
47175 #endif /* SQLITE_DEBUG */
47176
47177 #ifdef SQLITE_DEBUG
47178 /*
47179 **** This function may be used as part of assert() statements only. ****
47180 **
47181 ** Return true if it would be illegal for pBtree to write into the
47182 ** table or index rooted at iRoot because other shared connections are
47183 ** simultaneously reading that same table or index.
47184 **
47185 ** It is illegal for pBtree to write if some other Btree object that
47186 ** shares the same BtShared object is currently reading or writing
47187 ** the iRoot table.  Except, if the other Btree object has the
47188 ** read-uncommitted flag set, then it is OK for the other object to
47189 ** have a read cursor.
47190 **
47191 ** For example, before writing to any part of the table or index
47192 ** rooted at page iRoot, one should call:
47193 **
47194 **    assert( !hasReadConflicts(pBtree, iRoot) );
47195 */
47196 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47197   BtCursor *p;
47198   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47199     if( p->pgnoRoot==iRoot 
47200      && p->pBtree!=pBtree
47201      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47202     ){
47203       return 1;
47204     }
47205   }
47206   return 0;
47207 }
47208 #endif    /* #ifdef SQLITE_DEBUG */
47209
47210 /*
47211 ** Query to see if Btree handle p may obtain a lock of type eLock 
47212 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47213 ** SQLITE_OK if the lock may be obtained (by calling
47214 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47215 */
47216 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47217   BtShared *pBt = p->pBt;
47218   BtLock *pIter;
47219
47220   assert( sqlite3BtreeHoldsMutex(p) );
47221   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47222   assert( p->db!=0 );
47223   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47224   
47225   /* If requesting a write-lock, then the Btree must have an open write
47226   ** transaction on this file. And, obviously, for this to be so there 
47227   ** must be an open write transaction on the file itself.
47228   */
47229   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47230   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47231   
47232   /* This routine is a no-op if the shared-cache is not enabled */
47233   if( !p->sharable ){
47234     return SQLITE_OK;
47235   }
47236
47237   /* If some other connection is holding an exclusive lock, the
47238   ** requested lock may not be obtained.
47239   */
47240   if( pBt->pWriter!=p && pBt->isExclusive ){
47241     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47242     return SQLITE_LOCKED_SHAREDCACHE;
47243   }
47244
47245   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47246     /* The condition (pIter->eLock!=eLock) in the following if(...) 
47247     ** statement is a simplification of:
47248     **
47249     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47250     **
47251     ** since we know that if eLock==WRITE_LOCK, then no other connection
47252     ** may hold a WRITE_LOCK on any table in this file (since there can
47253     ** only be a single writer).
47254     */
47255     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47256     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47257     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47258       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47259       if( eLock==WRITE_LOCK ){
47260         assert( p==pBt->pWriter );
47261         pBt->isPending = 1;
47262       }
47263       return SQLITE_LOCKED_SHAREDCACHE;
47264     }
47265   }
47266   return SQLITE_OK;
47267 }
47268 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47269
47270 #ifndef SQLITE_OMIT_SHARED_CACHE
47271 /*
47272 ** Add a lock on the table with root-page iTable to the shared-btree used
47273 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
47274 ** WRITE_LOCK.
47275 **
47276 ** This function assumes the following:
47277 **
47278 **   (a) The specified Btree object p is connected to a sharable
47279 **       database (one with the BtShared.sharable flag set), and
47280 **
47281 **   (b) No other Btree objects hold a lock that conflicts
47282 **       with the requested lock (i.e. querySharedCacheTableLock() has
47283 **       already been called and returned SQLITE_OK).
47284 **
47285 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
47286 ** is returned if a malloc attempt fails.
47287 */
47288 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47289   BtShared *pBt = p->pBt;
47290   BtLock *pLock = 0;
47291   BtLock *pIter;
47292
47293   assert( sqlite3BtreeHoldsMutex(p) );
47294   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47295   assert( p->db!=0 );
47296
47297   /* A connection with the read-uncommitted flag set will never try to
47298   ** obtain a read-lock using this function. The only read-lock obtained
47299   ** by a connection in read-uncommitted mode is on the sqlite_master 
47300   ** table, and that lock is obtained in BtreeBeginTrans().  */
47301   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47302
47303   /* This function should only be called on a sharable b-tree after it 
47304   ** has been determined that no other b-tree holds a conflicting lock.  */
47305   assert( p->sharable );
47306   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47307
47308   /* First search the list for an existing lock on this table. */
47309   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47310     if( pIter->iTable==iTable && pIter->pBtree==p ){
47311       pLock = pIter;
47312       break;
47313     }
47314   }
47315
47316   /* If the above search did not find a BtLock struct associating Btree p
47317   ** with table iTable, allocate one and link it into the list.
47318   */
47319   if( !pLock ){
47320     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47321     if( !pLock ){
47322       return SQLITE_NOMEM;
47323     }
47324     pLock->iTable = iTable;
47325     pLock->pBtree = p;
47326     pLock->pNext = pBt->pLock;
47327     pBt->pLock = pLock;
47328   }
47329
47330   /* Set the BtLock.eLock variable to the maximum of the current lock
47331   ** and the requested lock. This means if a write-lock was already held
47332   ** and a read-lock requested, we don't incorrectly downgrade the lock.
47333   */
47334   assert( WRITE_LOCK>READ_LOCK );
47335   if( eLock>pLock->eLock ){
47336     pLock->eLock = eLock;
47337   }
47338
47339   return SQLITE_OK;
47340 }
47341 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47342
47343 #ifndef SQLITE_OMIT_SHARED_CACHE
47344 /*
47345 ** Release all the table locks (locks obtained via calls to
47346 ** the setSharedCacheTableLock() procedure) held by Btree object p.
47347 **
47348 ** This function assumes that Btree p has an open read or write 
47349 ** transaction. If it does not, then the BtShared.isPending variable
47350 ** may be incorrectly cleared.
47351 */
47352 static void clearAllSharedCacheTableLocks(Btree *p){
47353   BtShared *pBt = p->pBt;
47354   BtLock **ppIter = &pBt->pLock;
47355
47356   assert( sqlite3BtreeHoldsMutex(p) );
47357   assert( p->sharable || 0==*ppIter );
47358   assert( p->inTrans>0 );
47359
47360   while( *ppIter ){
47361     BtLock *pLock = *ppIter;
47362     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47363     assert( pLock->pBtree->inTrans>=pLock->eLock );
47364     if( pLock->pBtree==p ){
47365       *ppIter = pLock->pNext;
47366       assert( pLock->iTable!=1 || pLock==&p->lock );
47367       if( pLock->iTable!=1 ){
47368         sqlite3_free(pLock);
47369       }
47370     }else{
47371       ppIter = &pLock->pNext;
47372     }
47373   }
47374
47375   assert( pBt->isPending==0 || pBt->pWriter );
47376   if( pBt->pWriter==p ){
47377     pBt->pWriter = 0;
47378     pBt->isExclusive = 0;
47379     pBt->isPending = 0;
47380   }else if( pBt->nTransaction==2 ){
47381     /* This function is called when Btree p is concluding its 
47382     ** transaction. If there currently exists a writer, and p is not
47383     ** that writer, then the number of locks held by connections other
47384     ** than the writer must be about to drop to zero. In this case
47385     ** set the isPending flag to 0.
47386     **
47387     ** If there is not currently a writer, then BtShared.isPending must
47388     ** be zero already. So this next line is harmless in that case.
47389     */
47390     pBt->isPending = 0;
47391   }
47392 }
47393
47394 /*
47395 ** This function changes all write-locks held by Btree p into read-locks.
47396 */
47397 static void downgradeAllSharedCacheTableLocks(Btree *p){
47398   BtShared *pBt = p->pBt;
47399   if( pBt->pWriter==p ){
47400     BtLock *pLock;
47401     pBt->pWriter = 0;
47402     pBt->isExclusive = 0;
47403     pBt->isPending = 0;
47404     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47405       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47406       pLock->eLock = READ_LOCK;
47407     }
47408   }
47409 }
47410
47411 #endif /* SQLITE_OMIT_SHARED_CACHE */
47412
47413 static void releasePage(MemPage *pPage);  /* Forward reference */
47414
47415 /*
47416 ***** This routine is used inside of assert() only ****
47417 **
47418 ** Verify that the cursor holds the mutex on its BtShared
47419 */
47420 #ifdef SQLITE_DEBUG
47421 static int cursorHoldsMutex(BtCursor *p){
47422   return sqlite3_mutex_held(p->pBt->mutex);
47423 }
47424 #endif
47425
47426
47427 #ifndef SQLITE_OMIT_INCRBLOB
47428 /*
47429 ** Invalidate the overflow page-list cache for cursor pCur, if any.
47430 */
47431 static void invalidateOverflowCache(BtCursor *pCur){
47432   assert( cursorHoldsMutex(pCur) );
47433   sqlite3_free(pCur->aOverflow);
47434   pCur->aOverflow = 0;
47435 }
47436
47437 /*
47438 ** Invalidate the overflow page-list cache for all cursors opened
47439 ** on the shared btree structure pBt.
47440 */
47441 static void invalidateAllOverflowCache(BtShared *pBt){
47442   BtCursor *p;
47443   assert( sqlite3_mutex_held(pBt->mutex) );
47444   for(p=pBt->pCursor; p; p=p->pNext){
47445     invalidateOverflowCache(p);
47446   }
47447 }
47448
47449 /*
47450 ** This function is called before modifying the contents of a table
47451 ** to invalidate any incrblob cursors that are open on the
47452 ** row or one of the rows being modified.
47453 **
47454 ** If argument isClearTable is true, then the entire contents of the
47455 ** table is about to be deleted. In this case invalidate all incrblob
47456 ** cursors open on any row within the table with root-page pgnoRoot.
47457 **
47458 ** Otherwise, if argument isClearTable is false, then the row with
47459 ** rowid iRow is being replaced or deleted. In this case invalidate
47460 ** only those incrblob cursors open on that specific row.
47461 */
47462 static void invalidateIncrblobCursors(
47463   Btree *pBtree,          /* The database file to check */
47464   i64 iRow,               /* The rowid that might be changing */
47465   int isClearTable        /* True if all rows are being deleted */
47466 ){
47467   BtCursor *p;
47468   BtShared *pBt = pBtree->pBt;
47469   assert( sqlite3BtreeHoldsMutex(pBtree) );
47470   for(p=pBt->pCursor; p; p=p->pNext){
47471     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47472       p->eState = CURSOR_INVALID;
47473     }
47474   }
47475 }
47476
47477 #else
47478   /* Stub functions when INCRBLOB is omitted */
47479   #define invalidateOverflowCache(x)
47480   #define invalidateAllOverflowCache(x)
47481   #define invalidateIncrblobCursors(x,y,z)
47482 #endif /* SQLITE_OMIT_INCRBLOB */
47483
47484 /*
47485 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
47486 ** when a page that previously contained data becomes a free-list leaf 
47487 ** page.
47488 **
47489 ** The BtShared.pHasContent bitvec exists to work around an obscure
47490 ** bug caused by the interaction of two useful IO optimizations surrounding
47491 ** free-list leaf pages:
47492 **
47493 **   1) When all data is deleted from a page and the page becomes
47494 **      a free-list leaf page, the page is not written to the database
47495 **      (as free-list leaf pages contain no meaningful data). Sometimes
47496 **      such a page is not even journalled (as it will not be modified,
47497 **      why bother journalling it?).
47498 **
47499 **   2) When a free-list leaf page is reused, its content is not read
47500 **      from the database or written to the journal file (why should it
47501 **      be, if it is not at all meaningful?).
47502 **
47503 ** By themselves, these optimizations work fine and provide a handy
47504 ** performance boost to bulk delete or insert operations. However, if
47505 ** a page is moved to the free-list and then reused within the same
47506 ** transaction, a problem comes up. If the page is not journalled when
47507 ** it is moved to the free-list and it is also not journalled when it
47508 ** is extracted from the free-list and reused, then the original data
47509 ** may be lost. In the event of a rollback, it may not be possible
47510 ** to restore the database to its original configuration.
47511 **
47512 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
47513 ** moved to become a free-list leaf page, the corresponding bit is
47514 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
47515 ** optimization 2 above is omitted if the corresponding bit is already
47516 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
47517 ** at the end of every transaction.
47518 */
47519 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
47520   int rc = SQLITE_OK;
47521   if( !pBt->pHasContent ){
47522     assert( pgno<=pBt->nPage );
47523     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
47524     if( !pBt->pHasContent ){
47525       rc = SQLITE_NOMEM;
47526     }
47527   }
47528   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
47529     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
47530   }
47531   return rc;
47532 }
47533
47534 /*
47535 ** Query the BtShared.pHasContent vector.
47536 **
47537 ** This function is called when a free-list leaf page is removed from the
47538 ** free-list for reuse. It returns false if it is safe to retrieve the
47539 ** page from the pager layer with the 'no-content' flag set. True otherwise.
47540 */
47541 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
47542   Bitvec *p = pBt->pHasContent;
47543   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
47544 }
47545
47546 /*
47547 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
47548 ** invoked at the conclusion of each write-transaction.
47549 */
47550 static void btreeClearHasContent(BtShared *pBt){
47551   sqlite3BitvecDestroy(pBt->pHasContent);
47552   pBt->pHasContent = 0;
47553 }
47554
47555 /*
47556 ** Save the current cursor position in the variables BtCursor.nKey 
47557 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
47558 **
47559 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
47560 ** prior to calling this routine.  
47561 */
47562 static int saveCursorPosition(BtCursor *pCur){
47563   int rc;
47564
47565   assert( CURSOR_VALID==pCur->eState );
47566   assert( 0==pCur->pKey );
47567   assert( cursorHoldsMutex(pCur) );
47568
47569   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
47570   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
47571
47572   /* If this is an intKey table, then the above call to BtreeKeySize()
47573   ** stores the integer key in pCur->nKey. In this case this value is
47574   ** all that is required. Otherwise, if pCur is not open on an intKey
47575   ** table, then malloc space for and store the pCur->nKey bytes of key 
47576   ** data.
47577   */
47578   if( 0==pCur->apPage[0]->intKey ){
47579     void *pKey = sqlite3Malloc( (int)pCur->nKey );
47580     if( pKey ){
47581       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
47582       if( rc==SQLITE_OK ){
47583         pCur->pKey = pKey;
47584       }else{
47585         sqlite3_free(pKey);
47586       }
47587     }else{
47588       rc = SQLITE_NOMEM;
47589     }
47590   }
47591   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
47592
47593   if( rc==SQLITE_OK ){
47594     int i;
47595     for(i=0; i<=pCur->iPage; i++){
47596       releasePage(pCur->apPage[i]);
47597       pCur->apPage[i] = 0;
47598     }
47599     pCur->iPage = -1;
47600     pCur->eState = CURSOR_REQUIRESEEK;
47601   }
47602
47603   invalidateOverflowCache(pCur);
47604   return rc;
47605 }
47606
47607 /*
47608 ** Save the positions of all cursors (except pExcept) that are open on
47609 ** the table  with root-page iRoot. Usually, this is called just before cursor
47610 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
47611 */
47612 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
47613   BtCursor *p;
47614   assert( sqlite3_mutex_held(pBt->mutex) );
47615   assert( pExcept==0 || pExcept->pBt==pBt );
47616   for(p=pBt->pCursor; p; p=p->pNext){
47617     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
47618         p->eState==CURSOR_VALID ){
47619       int rc = saveCursorPosition(p);
47620       if( SQLITE_OK!=rc ){
47621         return rc;
47622       }
47623     }
47624   }
47625   return SQLITE_OK;
47626 }
47627
47628 /*
47629 ** Clear the current cursor position.
47630 */
47631 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
47632   assert( cursorHoldsMutex(pCur) );
47633   sqlite3_free(pCur->pKey);
47634   pCur->pKey = 0;
47635   pCur->eState = CURSOR_INVALID;
47636 }
47637
47638 /*
47639 ** In this version of BtreeMoveto, pKey is a packed index record
47640 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
47641 ** record and then call BtreeMovetoUnpacked() to do the work.
47642 */
47643 static int btreeMoveto(
47644   BtCursor *pCur,     /* Cursor open on the btree to be searched */
47645   const void *pKey,   /* Packed key if the btree is an index */
47646   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
47647   int bias,           /* Bias search to the high end */
47648   int *pRes           /* Write search results here */
47649 ){
47650   int rc;                    /* Status code */
47651   UnpackedRecord *pIdxKey;   /* Unpacked index key */
47652   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
47653
47654   if( pKey ){
47655     assert( nKey==(i64)(int)nKey );
47656     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
47657                                       aSpace, sizeof(aSpace));
47658     if( pIdxKey==0 ) return SQLITE_NOMEM;
47659   }else{
47660     pIdxKey = 0;
47661   }
47662   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
47663   if( pKey ){
47664     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
47665   }
47666   return rc;
47667 }
47668
47669 /*
47670 ** Restore the cursor to the position it was in (or as close to as possible)
47671 ** when saveCursorPosition() was called. Note that this call deletes the 
47672 ** saved position info stored by saveCursorPosition(), so there can be
47673 ** at most one effective restoreCursorPosition() call after each 
47674 ** saveCursorPosition().
47675 */
47676 static int btreeRestoreCursorPosition(BtCursor *pCur){
47677   int rc;
47678   assert( cursorHoldsMutex(pCur) );
47679   assert( pCur->eState>=CURSOR_REQUIRESEEK );
47680   if( pCur->eState==CURSOR_FAULT ){
47681     return pCur->skipNext;
47682   }
47683   pCur->eState = CURSOR_INVALID;
47684   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
47685   if( rc==SQLITE_OK ){
47686     sqlite3_free(pCur->pKey);
47687     pCur->pKey = 0;
47688     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
47689   }
47690   return rc;
47691 }
47692
47693 #define restoreCursorPosition(p) \
47694   (p->eState>=CURSOR_REQUIRESEEK ? \
47695          btreeRestoreCursorPosition(p) : \
47696          SQLITE_OK)
47697
47698 /*
47699 ** Determine whether or not a cursor has moved from the position it
47700 ** was last placed at.  Cursors can move when the row they are pointing
47701 ** at is deleted out from under them.
47702 **
47703 ** This routine returns an error code if something goes wrong.  The
47704 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
47705 */
47706 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
47707   int rc;
47708
47709   rc = restoreCursorPosition(pCur);
47710   if( rc ){
47711     *pHasMoved = 1;
47712     return rc;
47713   }
47714   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
47715     *pHasMoved = 1;
47716   }else{
47717     *pHasMoved = 0;
47718   }
47719   return SQLITE_OK;
47720 }
47721
47722 #ifndef SQLITE_OMIT_AUTOVACUUM
47723 /*
47724 ** Given a page number of a regular database page, return the page
47725 ** number for the pointer-map page that contains the entry for the
47726 ** input page number.
47727 **
47728 ** Return 0 (not a valid page) for pgno==1 since there is
47729 ** no pointer map associated with page 1.  The integrity_check logic
47730 ** requires that ptrmapPageno(*,1)!=1.
47731 */
47732 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
47733   int nPagesPerMapPage;
47734   Pgno iPtrMap, ret;
47735   assert( sqlite3_mutex_held(pBt->mutex) );
47736   if( pgno<2 ) return 0;
47737   nPagesPerMapPage = (pBt->usableSize/5)+1;
47738   iPtrMap = (pgno-2)/nPagesPerMapPage;
47739   ret = (iPtrMap*nPagesPerMapPage) + 2; 
47740   if( ret==PENDING_BYTE_PAGE(pBt) ){
47741     ret++;
47742   }
47743   return ret;
47744 }
47745
47746 /*
47747 ** Write an entry into the pointer map.
47748 **
47749 ** This routine updates the pointer map entry for page number 'key'
47750 ** so that it maps to type 'eType' and parent page number 'pgno'.
47751 **
47752 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
47753 ** a no-op.  If an error occurs, the appropriate error code is written
47754 ** into *pRC.
47755 */
47756 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
47757   DbPage *pDbPage;  /* The pointer map page */
47758   u8 *pPtrmap;      /* The pointer map data */
47759   Pgno iPtrmap;     /* The pointer map page number */
47760   int offset;       /* Offset in pointer map page */
47761   int rc;           /* Return code from subfunctions */
47762
47763   if( *pRC ) return;
47764
47765   assert( sqlite3_mutex_held(pBt->mutex) );
47766   /* The master-journal page number must never be used as a pointer map page */
47767   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
47768
47769   assert( pBt->autoVacuum );
47770   if( key==0 ){
47771     *pRC = SQLITE_CORRUPT_BKPT;
47772     return;
47773   }
47774   iPtrmap = PTRMAP_PAGENO(pBt, key);
47775   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47776   if( rc!=SQLITE_OK ){
47777     *pRC = rc;
47778     return;
47779   }
47780   offset = PTRMAP_PTROFFSET(iPtrmap, key);
47781   if( offset<0 ){
47782     *pRC = SQLITE_CORRUPT_BKPT;
47783     goto ptrmap_exit;
47784   }
47785   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47786
47787   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
47788     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
47789     *pRC= rc = sqlite3PagerWrite(pDbPage);
47790     if( rc==SQLITE_OK ){
47791       pPtrmap[offset] = eType;
47792       put4byte(&pPtrmap[offset+1], parent);
47793     }
47794   }
47795
47796 ptrmap_exit:
47797   sqlite3PagerUnref(pDbPage);
47798 }
47799
47800 /*
47801 ** Read an entry from the pointer map.
47802 **
47803 ** This routine retrieves the pointer map entry for page 'key', writing
47804 ** the type and parent page number to *pEType and *pPgno respectively.
47805 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
47806 */
47807 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
47808   DbPage *pDbPage;   /* The pointer map page */
47809   int iPtrmap;       /* Pointer map page index */
47810   u8 *pPtrmap;       /* Pointer map page data */
47811   int offset;        /* Offset of entry in pointer map */
47812   int rc;
47813
47814   assert( sqlite3_mutex_held(pBt->mutex) );
47815
47816   iPtrmap = PTRMAP_PAGENO(pBt, key);
47817   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
47818   if( rc!=0 ){
47819     return rc;
47820   }
47821   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
47822
47823   offset = PTRMAP_PTROFFSET(iPtrmap, key);
47824   assert( pEType!=0 );
47825   *pEType = pPtrmap[offset];
47826   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
47827
47828   sqlite3PagerUnref(pDbPage);
47829   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
47830   return SQLITE_OK;
47831 }
47832
47833 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
47834   #define ptrmapPut(w,x,y,z,rc)
47835   #define ptrmapGet(w,x,y,z) SQLITE_OK
47836   #define ptrmapPutOvflPtr(x, y, rc)
47837 #endif
47838
47839 /*
47840 ** Given a btree page and a cell index (0 means the first cell on
47841 ** the page, 1 means the second cell, and so forth) return a pointer
47842 ** to the cell content.
47843 **
47844 ** This routine works only for pages that do not contain overflow cells.
47845 */
47846 #define findCell(P,I) \
47847   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
47848
47849 /*
47850 ** This a more complex version of findCell() that works for
47851 ** pages that do contain overflow cells.
47852 */
47853 static u8 *findOverflowCell(MemPage *pPage, int iCell){
47854   int i;
47855   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47856   for(i=pPage->nOverflow-1; i>=0; i--){
47857     int k;
47858     struct _OvflCell *pOvfl;
47859     pOvfl = &pPage->aOvfl[i];
47860     k = pOvfl->idx;
47861     if( k<=iCell ){
47862       if( k==iCell ){
47863         return pOvfl->pCell;
47864       }
47865       iCell--;
47866     }
47867   }
47868   return findCell(pPage, iCell);
47869 }
47870
47871 /*
47872 ** Parse a cell content block and fill in the CellInfo structure.  There
47873 ** are two versions of this function.  btreeParseCell() takes a 
47874 ** cell index as the second argument and btreeParseCellPtr() 
47875 ** takes a pointer to the body of the cell as its second argument.
47876 **
47877 ** Within this file, the parseCell() macro can be called instead of
47878 ** btreeParseCellPtr(). Using some compilers, this will be faster.
47879 */
47880 static void btreeParseCellPtr(
47881   MemPage *pPage,         /* Page containing the cell */
47882   u8 *pCell,              /* Pointer to the cell text. */
47883   CellInfo *pInfo         /* Fill in this structure */
47884 ){
47885   u16 n;                  /* Number bytes in cell content header */
47886   u32 nPayload;           /* Number of bytes of cell payload */
47887
47888   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47889
47890   pInfo->pCell = pCell;
47891   assert( pPage->leaf==0 || pPage->leaf==1 );
47892   n = pPage->childPtrSize;
47893   assert( n==4-4*pPage->leaf );
47894   if( pPage->intKey ){
47895     if( pPage->hasData ){
47896       n += getVarint32(&pCell[n], nPayload);
47897     }else{
47898       nPayload = 0;
47899     }
47900     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
47901     pInfo->nData = nPayload;
47902   }else{
47903     pInfo->nData = 0;
47904     n += getVarint32(&pCell[n], nPayload);
47905     pInfo->nKey = nPayload;
47906   }
47907   pInfo->nPayload = nPayload;
47908   pInfo->nHeader = n;
47909   testcase( nPayload==pPage->maxLocal );
47910   testcase( nPayload==pPage->maxLocal+1 );
47911   if( likely(nPayload<=pPage->maxLocal) ){
47912     /* This is the (easy) common case where the entire payload fits
47913     ** on the local page.  No overflow is required.
47914     */
47915     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
47916     pInfo->nLocal = (u16)nPayload;
47917     pInfo->iOverflow = 0;
47918   }else{
47919     /* If the payload will not fit completely on the local page, we have
47920     ** to decide how much to store locally and how much to spill onto
47921     ** overflow pages.  The strategy is to minimize the amount of unused
47922     ** space on overflow pages while keeping the amount of local storage
47923     ** in between minLocal and maxLocal.
47924     **
47925     ** Warning:  changing the way overflow payload is distributed in any
47926     ** way will result in an incompatible file format.
47927     */
47928     int minLocal;  /* Minimum amount of payload held locally */
47929     int maxLocal;  /* Maximum amount of payload held locally */
47930     int surplus;   /* Overflow payload available for local storage */
47931
47932     minLocal = pPage->minLocal;
47933     maxLocal = pPage->maxLocal;
47934     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
47935     testcase( surplus==maxLocal );
47936     testcase( surplus==maxLocal+1 );
47937     if( surplus <= maxLocal ){
47938       pInfo->nLocal = (u16)surplus;
47939     }else{
47940       pInfo->nLocal = (u16)minLocal;
47941     }
47942     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
47943     pInfo->nSize = pInfo->iOverflow + 4;
47944   }
47945 }
47946 #define parseCell(pPage, iCell, pInfo) \
47947   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
47948 static void btreeParseCell(
47949   MemPage *pPage,         /* Page containing the cell */
47950   int iCell,              /* The cell index.  First cell is 0 */
47951   CellInfo *pInfo         /* Fill in this structure */
47952 ){
47953   parseCell(pPage, iCell, pInfo);
47954 }
47955
47956 /*
47957 ** Compute the total number of bytes that a Cell needs in the cell
47958 ** data area of the btree-page.  The return number includes the cell
47959 ** data header and the local payload, but not any overflow page or
47960 ** the space used by the cell pointer.
47961 */
47962 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
47963   u8 *pIter = &pCell[pPage->childPtrSize];
47964   u32 nSize;
47965
47966 #ifdef SQLITE_DEBUG
47967   /* The value returned by this function should always be the same as
47968   ** the (CellInfo.nSize) value found by doing a full parse of the
47969   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
47970   ** this function verifies that this invariant is not violated. */
47971   CellInfo debuginfo;
47972   btreeParseCellPtr(pPage, pCell, &debuginfo);
47973 #endif
47974
47975   if( pPage->intKey ){
47976     u8 *pEnd;
47977     if( pPage->hasData ){
47978       pIter += getVarint32(pIter, nSize);
47979     }else{
47980       nSize = 0;
47981     }
47982
47983     /* pIter now points at the 64-bit integer key value, a variable length 
47984     ** integer. The following block moves pIter to point at the first byte
47985     ** past the end of the key value. */
47986     pEnd = &pIter[9];
47987     while( (*pIter++)&0x80 && pIter<pEnd );
47988   }else{
47989     pIter += getVarint32(pIter, nSize);
47990   }
47991
47992   testcase( nSize==pPage->maxLocal );
47993   testcase( nSize==pPage->maxLocal+1 );
47994   if( nSize>pPage->maxLocal ){
47995     int minLocal = pPage->minLocal;
47996     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
47997     testcase( nSize==pPage->maxLocal );
47998     testcase( nSize==pPage->maxLocal+1 );
47999     if( nSize>pPage->maxLocal ){
48000       nSize = minLocal;
48001     }
48002     nSize += 4;
48003   }
48004   nSize += (u32)(pIter - pCell);
48005
48006   /* The minimum size of any cell is 4 bytes. */
48007   if( nSize<4 ){
48008     nSize = 4;
48009   }
48010
48011   assert( nSize==debuginfo.nSize );
48012   return (u16)nSize;
48013 }
48014
48015 #ifdef SQLITE_DEBUG
48016 /* This variation on cellSizePtr() is used inside of assert() statements
48017 ** only. */
48018 static u16 cellSize(MemPage *pPage, int iCell){
48019   return cellSizePtr(pPage, findCell(pPage, iCell));
48020 }
48021 #endif
48022
48023 #ifndef SQLITE_OMIT_AUTOVACUUM
48024 /*
48025 ** If the cell pCell, part of page pPage contains a pointer
48026 ** to an overflow page, insert an entry into the pointer-map
48027 ** for the overflow page.
48028 */
48029 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48030   CellInfo info;
48031   if( *pRC ) return;
48032   assert( pCell!=0 );
48033   btreeParseCellPtr(pPage, pCell, &info);
48034   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48035   if( info.iOverflow ){
48036     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48037     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48038   }
48039 }
48040 #endif
48041
48042
48043 /*
48044 ** Defragment the page given.  All Cells are moved to the
48045 ** end of the page and all free space is collected into one
48046 ** big FreeBlk that occurs in between the header and cell
48047 ** pointer array and the cell content area.
48048 */
48049 static int defragmentPage(MemPage *pPage){
48050   int i;                     /* Loop counter */
48051   int pc;                    /* Address of a i-th cell */
48052   int hdr;                   /* Offset to the page header */
48053   int size;                  /* Size of a cell */
48054   int usableSize;            /* Number of usable bytes on a page */
48055   int cellOffset;            /* Offset to the cell pointer array */
48056   int cbrk;                  /* Offset to the cell content area */
48057   int nCell;                 /* Number of cells on the page */
48058   unsigned char *data;       /* The page data */
48059   unsigned char *temp;       /* Temp area for cell content */
48060   int iCellFirst;            /* First allowable cell index */
48061   int iCellLast;             /* Last possible cell index */
48062
48063
48064   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48065   assert( pPage->pBt!=0 );
48066   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48067   assert( pPage->nOverflow==0 );
48068   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48069   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48070   data = pPage->aData;
48071   hdr = pPage->hdrOffset;
48072   cellOffset = pPage->cellOffset;
48073   nCell = pPage->nCell;
48074   assert( nCell==get2byte(&data[hdr+3]) );
48075   usableSize = pPage->pBt->usableSize;
48076   cbrk = get2byte(&data[hdr+5]);
48077   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48078   cbrk = usableSize;
48079   iCellFirst = cellOffset + 2*nCell;
48080   iCellLast = usableSize - 4;
48081   for(i=0; i<nCell; i++){
48082     u8 *pAddr;     /* The i-th cell pointer */
48083     pAddr = &data[cellOffset + i*2];
48084     pc = get2byte(pAddr);
48085     testcase( pc==iCellFirst );
48086     testcase( pc==iCellLast );
48087 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48088     /* These conditions have already been verified in btreeInitPage()
48089     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
48090     */
48091     if( pc<iCellFirst || pc>iCellLast ){
48092       return SQLITE_CORRUPT_BKPT;
48093     }
48094 #endif
48095     assert( pc>=iCellFirst && pc<=iCellLast );
48096     size = cellSizePtr(pPage, &temp[pc]);
48097     cbrk -= size;
48098 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48099     if( cbrk<iCellFirst ){
48100       return SQLITE_CORRUPT_BKPT;
48101     }
48102 #else
48103     if( cbrk<iCellFirst || pc+size>usableSize ){
48104       return SQLITE_CORRUPT_BKPT;
48105     }
48106 #endif
48107     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48108     testcase( cbrk+size==usableSize );
48109     testcase( pc+size==usableSize );
48110     memcpy(&data[cbrk], &temp[pc], size);
48111     put2byte(pAddr, cbrk);
48112   }
48113   assert( cbrk>=iCellFirst );
48114   put2byte(&data[hdr+5], cbrk);
48115   data[hdr+1] = 0;
48116   data[hdr+2] = 0;
48117   data[hdr+7] = 0;
48118   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48119   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48120   if( cbrk-iCellFirst!=pPage->nFree ){
48121     return SQLITE_CORRUPT_BKPT;
48122   }
48123   return SQLITE_OK;
48124 }
48125
48126 /*
48127 ** Allocate nByte bytes of space from within the B-Tree page passed
48128 ** as the first argument. Write into *pIdx the index into pPage->aData[]
48129 ** of the first byte of allocated space. Return either SQLITE_OK or
48130 ** an error code (usually SQLITE_CORRUPT).
48131 **
48132 ** The caller guarantees that there is sufficient space to make the
48133 ** allocation.  This routine might need to defragment in order to bring
48134 ** all the space together, however.  This routine will avoid using
48135 ** the first two bytes past the cell pointer area since presumably this
48136 ** allocation is being made in order to insert a new cell, so we will
48137 ** also end up needing a new cell pointer.
48138 */
48139 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48140   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
48141   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
48142   int nFrag;                           /* Number of fragmented bytes on pPage */
48143   int top;                             /* First byte of cell content area */
48144   int gap;        /* First byte of gap between cell pointers and cell content */
48145   int rc;         /* Integer return code */
48146   int usableSize; /* Usable size of the page */
48147   
48148   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48149   assert( pPage->pBt );
48150   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48151   assert( nByte>=0 );  /* Minimum cell size is 4 */
48152   assert( pPage->nFree>=nByte );
48153   assert( pPage->nOverflow==0 );
48154   usableSize = pPage->pBt->usableSize;
48155   assert( nByte < usableSize-8 );
48156
48157   nFrag = data[hdr+7];
48158   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48159   gap = pPage->cellOffset + 2*pPage->nCell;
48160   top = get2byteNotZero(&data[hdr+5]);
48161   if( gap>top ) return SQLITE_CORRUPT_BKPT;
48162   testcase( gap+2==top );
48163   testcase( gap+1==top );
48164   testcase( gap==top );
48165
48166   if( nFrag>=60 ){
48167     /* Always defragment highly fragmented pages */
48168     rc = defragmentPage(pPage);
48169     if( rc ) return rc;
48170     top = get2byteNotZero(&data[hdr+5]);
48171   }else if( gap+2<=top ){
48172     /* Search the freelist looking for a free slot big enough to satisfy 
48173     ** the request. The allocation is made from the first free slot in 
48174     ** the list that is large enough to accomadate it.
48175     */
48176     int pc, addr;
48177     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48178       int size;            /* Size of the free slot */
48179       if( pc>usableSize-4 || pc<addr+4 ){
48180         return SQLITE_CORRUPT_BKPT;
48181       }
48182       size = get2byte(&data[pc+2]);
48183       if( size>=nByte ){
48184         int x = size - nByte;
48185         testcase( x==4 );
48186         testcase( x==3 );
48187         if( x<4 ){
48188           /* Remove the slot from the free-list. Update the number of
48189           ** fragmented bytes within the page. */
48190           memcpy(&data[addr], &data[pc], 2);
48191           data[hdr+7] = (u8)(nFrag + x);
48192         }else if( size+pc > usableSize ){
48193           return SQLITE_CORRUPT_BKPT;
48194         }else{
48195           /* The slot remains on the free-list. Reduce its size to account
48196           ** for the portion used by the new allocation. */
48197           put2byte(&data[pc+2], x);
48198         }
48199         *pIdx = pc + x;
48200         return SQLITE_OK;
48201       }
48202     }
48203   }
48204
48205   /* Check to make sure there is enough space in the gap to satisfy
48206   ** the allocation.  If not, defragment.
48207   */
48208   testcase( gap+2+nByte==top );
48209   if( gap+2+nByte>top ){
48210     rc = defragmentPage(pPage);
48211     if( rc ) return rc;
48212     top = get2byteNotZero(&data[hdr+5]);
48213     assert( gap+nByte<=top );
48214   }
48215
48216
48217   /* Allocate memory from the gap in between the cell pointer array
48218   ** and the cell content area.  The btreeInitPage() call has already
48219   ** validated the freelist.  Given that the freelist is valid, there
48220   ** is no way that the allocation can extend off the end of the page.
48221   ** The assert() below verifies the previous sentence.
48222   */
48223   top -= nByte;
48224   put2byte(&data[hdr+5], top);
48225   assert( top+nByte <= (int)pPage->pBt->usableSize );
48226   *pIdx = top;
48227   return SQLITE_OK;
48228 }
48229
48230 /*
48231 ** Return a section of the pPage->aData to the freelist.
48232 ** The first byte of the new free block is pPage->aDisk[start]
48233 ** and the size of the block is "size" bytes.
48234 **
48235 ** Most of the effort here is involved in coalesing adjacent
48236 ** free blocks into a single big free block.
48237 */
48238 static int freeSpace(MemPage *pPage, int start, int size){
48239   int addr, pbegin, hdr;
48240   int iLast;                        /* Largest possible freeblock offset */
48241   unsigned char *data = pPage->aData;
48242
48243   assert( pPage->pBt!=0 );
48244   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48245   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48246   assert( (start + size) <= (int)pPage->pBt->usableSize );
48247   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48248   assert( size>=0 );   /* Minimum cell size is 4 */
48249
48250   if( pPage->pBt->secureDelete ){
48251     /* Overwrite deleted information with zeros when the secure_delete
48252     ** option is enabled */
48253     memset(&data[start], 0, size);
48254   }
48255
48256   /* Add the space back into the linked list of freeblocks.  Note that
48257   ** even though the freeblock list was checked by btreeInitPage(),
48258   ** btreeInitPage() did not detect overlapping cells or
48259   ** freeblocks that overlapped cells.   Nor does it detect when the
48260   ** cell content area exceeds the value in the page header.  If these
48261   ** situations arise, then subsequent insert operations might corrupt
48262   ** the freelist.  So we do need to check for corruption while scanning
48263   ** the freelist.
48264   */
48265   hdr = pPage->hdrOffset;
48266   addr = hdr + 1;
48267   iLast = pPage->pBt->usableSize - 4;
48268   assert( start<=iLast );
48269   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48270     if( pbegin<addr+4 ){
48271       return SQLITE_CORRUPT_BKPT;
48272     }
48273     addr = pbegin;
48274   }
48275   if( pbegin>iLast ){
48276     return SQLITE_CORRUPT_BKPT;
48277   }
48278   assert( pbegin>addr || pbegin==0 );
48279   put2byte(&data[addr], start);
48280   put2byte(&data[start], pbegin);
48281   put2byte(&data[start+2], size);
48282   pPage->nFree = pPage->nFree + (u16)size;
48283
48284   /* Coalesce adjacent free blocks */
48285   addr = hdr + 1;
48286   while( (pbegin = get2byte(&data[addr]))>0 ){
48287     int pnext, psize, x;
48288     assert( pbegin>addr );
48289     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48290     pnext = get2byte(&data[pbegin]);
48291     psize = get2byte(&data[pbegin+2]);
48292     if( pbegin + psize + 3 >= pnext && pnext>0 ){
48293       int frag = pnext - (pbegin+psize);
48294       if( (frag<0) || (frag>(int)data[hdr+7]) ){
48295         return SQLITE_CORRUPT_BKPT;
48296       }
48297       data[hdr+7] -= (u8)frag;
48298       x = get2byte(&data[pnext]);
48299       put2byte(&data[pbegin], x);
48300       x = pnext + get2byte(&data[pnext+2]) - pbegin;
48301       put2byte(&data[pbegin+2], x);
48302     }else{
48303       addr = pbegin;
48304     }
48305   }
48306
48307   /* If the cell content area begins with a freeblock, remove it. */
48308   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48309     int top;
48310     pbegin = get2byte(&data[hdr+1]);
48311     memcpy(&data[hdr+1], &data[pbegin], 2);
48312     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48313     put2byte(&data[hdr+5], top);
48314   }
48315   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48316   return SQLITE_OK;
48317 }
48318
48319 /*
48320 ** Decode the flags byte (the first byte of the header) for a page
48321 ** and initialize fields of the MemPage structure accordingly.
48322 **
48323 ** Only the following combinations are supported.  Anything different
48324 ** indicates a corrupt database files:
48325 **
48326 **         PTF_ZERODATA
48327 **         PTF_ZERODATA | PTF_LEAF
48328 **         PTF_LEAFDATA | PTF_INTKEY
48329 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48330 */
48331 static int decodeFlags(MemPage *pPage, int flagByte){
48332   BtShared *pBt;     /* A copy of pPage->pBt */
48333
48334   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48335   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48336   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
48337   flagByte &= ~PTF_LEAF;
48338   pPage->childPtrSize = 4-4*pPage->leaf;
48339   pBt = pPage->pBt;
48340   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48341     pPage->intKey = 1;
48342     pPage->hasData = pPage->leaf;
48343     pPage->maxLocal = pBt->maxLeaf;
48344     pPage->minLocal = pBt->minLeaf;
48345   }else if( flagByte==PTF_ZERODATA ){
48346     pPage->intKey = 0;
48347     pPage->hasData = 0;
48348     pPage->maxLocal = pBt->maxLocal;
48349     pPage->minLocal = pBt->minLocal;
48350   }else{
48351     return SQLITE_CORRUPT_BKPT;
48352   }
48353   return SQLITE_OK;
48354 }
48355
48356 /*
48357 ** Initialize the auxiliary information for a disk block.
48358 **
48359 ** Return SQLITE_OK on success.  If we see that the page does
48360 ** not contain a well-formed database page, then return 
48361 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
48362 ** guarantee that the page is well-formed.  It only shows that
48363 ** we failed to detect any corruption.
48364 */
48365 static int btreeInitPage(MemPage *pPage){
48366
48367   assert( pPage->pBt!=0 );
48368   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48369   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48370   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48371   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48372
48373   if( !pPage->isInit ){
48374     u16 pc;            /* Address of a freeblock within pPage->aData[] */
48375     u8 hdr;            /* Offset to beginning of page header */
48376     u8 *data;          /* Equal to pPage->aData */
48377     BtShared *pBt;        /* The main btree structure */
48378     int usableSize;    /* Amount of usable space on each page */
48379     u16 cellOffset;    /* Offset from start of page to first cell pointer */
48380     int nFree;         /* Number of unused bytes on the page */
48381     int top;           /* First byte of the cell content area */
48382     int iCellFirst;    /* First allowable cell or freeblock offset */
48383     int iCellLast;     /* Last possible cell or freeblock offset */
48384
48385     pBt = pPage->pBt;
48386
48387     hdr = pPage->hdrOffset;
48388     data = pPage->aData;
48389     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48390     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48391     pPage->maskPage = (u16)(pBt->pageSize - 1);
48392     pPage->nOverflow = 0;
48393     usableSize = pBt->usableSize;
48394     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48395     top = get2byteNotZero(&data[hdr+5]);
48396     pPage->nCell = get2byte(&data[hdr+3]);
48397     if( pPage->nCell>MX_CELL(pBt) ){
48398       /* To many cells for a single page.  The page must be corrupt */
48399       return SQLITE_CORRUPT_BKPT;
48400     }
48401     testcase( pPage->nCell==MX_CELL(pBt) );
48402
48403     /* A malformed database page might cause us to read past the end
48404     ** of page when parsing a cell.  
48405     **
48406     ** The following block of code checks early to see if a cell extends
48407     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
48408     ** returned if it does.
48409     */
48410     iCellFirst = cellOffset + 2*pPage->nCell;
48411     iCellLast = usableSize - 4;
48412 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48413     {
48414       int i;            /* Index into the cell pointer array */
48415       int sz;           /* Size of a cell */
48416
48417       if( !pPage->leaf ) iCellLast--;
48418       for(i=0; i<pPage->nCell; i++){
48419         pc = get2byte(&data[cellOffset+i*2]);
48420         testcase( pc==iCellFirst );
48421         testcase( pc==iCellLast );
48422         if( pc<iCellFirst || pc>iCellLast ){
48423           return SQLITE_CORRUPT_BKPT;
48424         }
48425         sz = cellSizePtr(pPage, &data[pc]);
48426         testcase( pc+sz==usableSize );
48427         if( pc+sz>usableSize ){
48428           return SQLITE_CORRUPT_BKPT;
48429         }
48430       }
48431       if( !pPage->leaf ) iCellLast++;
48432     }  
48433 #endif
48434
48435     /* Compute the total free space on the page */
48436     pc = get2byte(&data[hdr+1]);
48437     nFree = data[hdr+7] + top;
48438     while( pc>0 ){
48439       u16 next, size;
48440       if( pc<iCellFirst || pc>iCellLast ){
48441         /* Start of free block is off the page */
48442         return SQLITE_CORRUPT_BKPT; 
48443       }
48444       next = get2byte(&data[pc]);
48445       size = get2byte(&data[pc+2]);
48446       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48447         /* Free blocks must be in ascending order. And the last byte of
48448         ** the free-block must lie on the database page.  */
48449         return SQLITE_CORRUPT_BKPT; 
48450       }
48451       nFree = nFree + size;
48452       pc = next;
48453     }
48454
48455     /* At this point, nFree contains the sum of the offset to the start
48456     ** of the cell-content area plus the number of free bytes within
48457     ** the cell-content area. If this is greater than the usable-size
48458     ** of the page, then the page must be corrupted. This check also
48459     ** serves to verify that the offset to the start of the cell-content
48460     ** area, according to the page header, lies within the page.
48461     */
48462     if( nFree>usableSize ){
48463       return SQLITE_CORRUPT_BKPT; 
48464     }
48465     pPage->nFree = (u16)(nFree - iCellFirst);
48466     pPage->isInit = 1;
48467   }
48468   return SQLITE_OK;
48469 }
48470
48471 /*
48472 ** Set up a raw page so that it looks like a database page holding
48473 ** no entries.
48474 */
48475 static void zeroPage(MemPage *pPage, int flags){
48476   unsigned char *data = pPage->aData;
48477   BtShared *pBt = pPage->pBt;
48478   u8 hdr = pPage->hdrOffset;
48479   u16 first;
48480
48481   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
48482   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48483   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
48484   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48485   assert( sqlite3_mutex_held(pBt->mutex) );
48486   if( pBt->secureDelete ){
48487     memset(&data[hdr], 0, pBt->usableSize - hdr);
48488   }
48489   data[hdr] = (char)flags;
48490   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
48491   memset(&data[hdr+1], 0, 4);
48492   data[hdr+7] = 0;
48493   put2byte(&data[hdr+5], pBt->usableSize);
48494   pPage->nFree = (u16)(pBt->usableSize - first);
48495   decodeFlags(pPage, flags);
48496   pPage->hdrOffset = hdr;
48497   pPage->cellOffset = first;
48498   pPage->nOverflow = 0;
48499   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48500   pPage->maskPage = (u16)(pBt->pageSize - 1);
48501   pPage->nCell = 0;
48502   pPage->isInit = 1;
48503 }
48504
48505
48506 /*
48507 ** Convert a DbPage obtained from the pager into a MemPage used by
48508 ** the btree layer.
48509 */
48510 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
48511   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
48512   pPage->aData = sqlite3PagerGetData(pDbPage);
48513   pPage->pDbPage = pDbPage;
48514   pPage->pBt = pBt;
48515   pPage->pgno = pgno;
48516   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
48517   return pPage; 
48518 }
48519
48520 /*
48521 ** Get a page from the pager.  Initialize the MemPage.pBt and
48522 ** MemPage.aData elements if needed.
48523 **
48524 ** If the noContent flag is set, it means that we do not care about
48525 ** the content of the page at this time.  So do not go to the disk
48526 ** to fetch the content.  Just fill in the content with zeros for now.
48527 ** If in the future we call sqlite3PagerWrite() on this page, that
48528 ** means we have started to be concerned about content and the disk
48529 ** read should occur at that point.
48530 */
48531 static int btreeGetPage(
48532   BtShared *pBt,       /* The btree */
48533   Pgno pgno,           /* Number of the page to fetch */
48534   MemPage **ppPage,    /* Return the page in this parameter */
48535   int noContent        /* Do not load page content if true */
48536 ){
48537   int rc;
48538   DbPage *pDbPage;
48539
48540   assert( sqlite3_mutex_held(pBt->mutex) );
48541   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
48542   if( rc ) return rc;
48543   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
48544   return SQLITE_OK;
48545 }
48546
48547 /*
48548 ** Retrieve a page from the pager cache. If the requested page is not
48549 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
48550 ** MemPage.aData elements if needed.
48551 */
48552 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
48553   DbPage *pDbPage;
48554   assert( sqlite3_mutex_held(pBt->mutex) );
48555   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
48556   if( pDbPage ){
48557     return btreePageFromDbPage(pDbPage, pgno, pBt);
48558   }
48559   return 0;
48560 }
48561
48562 /*
48563 ** Return the size of the database file in pages. If there is any kind of
48564 ** error, return ((unsigned int)-1).
48565 */
48566 static Pgno btreePagecount(BtShared *pBt){
48567   return pBt->nPage;
48568 }
48569 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
48570   assert( sqlite3BtreeHoldsMutex(p) );
48571   assert( ((p->pBt->nPage)&0x8000000)==0 );
48572   return (int)btreePagecount(p->pBt);
48573 }
48574
48575 /*
48576 ** Get a page from the pager and initialize it.  This routine is just a
48577 ** convenience wrapper around separate calls to btreeGetPage() and 
48578 ** btreeInitPage().
48579 **
48580 ** If an error occurs, then the value *ppPage is set to is undefined. It
48581 ** may remain unchanged, or it may be set to an invalid value.
48582 */
48583 static int getAndInitPage(
48584   BtShared *pBt,          /* The database file */
48585   Pgno pgno,           /* Number of the page to get */
48586   MemPage **ppPage     /* Write the page pointer here */
48587 ){
48588   int rc;
48589   assert( sqlite3_mutex_held(pBt->mutex) );
48590
48591   if( pgno>btreePagecount(pBt) ){
48592     rc = SQLITE_CORRUPT_BKPT;
48593   }else{
48594     rc = btreeGetPage(pBt, pgno, ppPage, 0);
48595     if( rc==SQLITE_OK ){
48596       rc = btreeInitPage(*ppPage);
48597       if( rc!=SQLITE_OK ){
48598         releasePage(*ppPage);
48599       }
48600     }
48601   }
48602
48603   testcase( pgno==0 );
48604   assert( pgno!=0 || rc==SQLITE_CORRUPT );
48605   return rc;
48606 }
48607
48608 /*
48609 ** Release a MemPage.  This should be called once for each prior
48610 ** call to btreeGetPage.
48611 */
48612 static void releasePage(MemPage *pPage){
48613   if( pPage ){
48614     assert( pPage->aData );
48615     assert( pPage->pBt );
48616     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48617     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
48618     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48619     sqlite3PagerUnref(pPage->pDbPage);
48620   }
48621 }
48622
48623 /*
48624 ** During a rollback, when the pager reloads information into the cache
48625 ** so that the cache is restored to its original state at the start of
48626 ** the transaction, for each page restored this routine is called.
48627 **
48628 ** This routine needs to reset the extra data section at the end of the
48629 ** page to agree with the restored data.
48630 */
48631 static void pageReinit(DbPage *pData){
48632   MemPage *pPage;
48633   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
48634   assert( sqlite3PagerPageRefcount(pData)>0 );
48635   if( pPage->isInit ){
48636     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48637     pPage->isInit = 0;
48638     if( sqlite3PagerPageRefcount(pData)>1 ){
48639       /* pPage might not be a btree page;  it might be an overflow page
48640       ** or ptrmap page or a free page.  In those cases, the following
48641       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
48642       ** But no harm is done by this.  And it is very important that
48643       ** btreeInitPage() be called on every btree page so we make
48644       ** the call for every page that comes in for re-initing. */
48645       btreeInitPage(pPage);
48646     }
48647   }
48648 }
48649
48650 /*
48651 ** Invoke the busy handler for a btree.
48652 */
48653 static int btreeInvokeBusyHandler(void *pArg){
48654   BtShared *pBt = (BtShared*)pArg;
48655   assert( pBt->db );
48656   assert( sqlite3_mutex_held(pBt->db->mutex) );
48657   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
48658 }
48659
48660 /*
48661 ** Open a database file.
48662 ** 
48663 ** zFilename is the name of the database file.  If zFilename is NULL
48664 ** then an ephemeral database is created.  The ephemeral database might
48665 ** be exclusively in memory, or it might use a disk-based memory cache.
48666 ** Either way, the ephemeral database will be automatically deleted 
48667 ** when sqlite3BtreeClose() is called.
48668 **
48669 ** If zFilename is ":memory:" then an in-memory database is created
48670 ** that is automatically destroyed when it is closed.
48671 **
48672 ** The "flags" parameter is a bitmask that might contain bits
48673 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
48674 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
48675 ** These flags are passed through into sqlite3PagerOpen() and must
48676 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
48677 **
48678 ** If the database is already opened in the same database connection
48679 ** and we are in shared cache mode, then the open will fail with an
48680 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
48681 ** objects in the same database connection since doing so will lead
48682 ** to problems with locking.
48683 */
48684 SQLITE_PRIVATE int sqlite3BtreeOpen(
48685   const char *zFilename,  /* Name of the file containing the BTree database */
48686   sqlite3 *db,            /* Associated database handle */
48687   Btree **ppBtree,        /* Pointer to new Btree object written here */
48688   int flags,              /* Options */
48689   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
48690 ){
48691   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
48692   BtShared *pBt = 0;             /* Shared part of btree structure */
48693   Btree *p;                      /* Handle to return */
48694   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
48695   int rc = SQLITE_OK;            /* Result code from this function */
48696   u8 nReserve;                   /* Byte of unused space on each page */
48697   unsigned char zDbHeader[100];  /* Database header content */
48698
48699   /* True if opening an ephemeral, temporary database */
48700   const int isTempDb = zFilename==0 || zFilename[0]==0;
48701
48702   /* Set the variable isMemdb to true for an in-memory database, or 
48703   ** false for a file-based database.
48704   */
48705 #ifdef SQLITE_OMIT_MEMORYDB
48706   const int isMemdb = 0;
48707 #else
48708   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
48709                        || (isTempDb && sqlite3TempInMemory(db));
48710 #endif
48711
48712   assert( db!=0 );
48713   assert( sqlite3_mutex_held(db->mutex) );
48714   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
48715
48716   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
48717   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
48718
48719   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
48720   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
48721
48722   if( db->flags & SQLITE_NoReadlock ){
48723     flags |= BTREE_NO_READLOCK;
48724   }
48725   if( isMemdb ){
48726     flags |= BTREE_MEMORY;
48727   }
48728   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
48729     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
48730   }
48731   pVfs = db->pVfs;
48732   p = sqlite3MallocZero(sizeof(Btree));
48733   if( !p ){
48734     return SQLITE_NOMEM;
48735   }
48736   p->inTrans = TRANS_NONE;
48737   p->db = db;
48738 #ifndef SQLITE_OMIT_SHARED_CACHE
48739   p->lock.pBtree = p;
48740   p->lock.iTable = 1;
48741 #endif
48742
48743 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48744   /*
48745   ** If this Btree is a candidate for shared cache, try to find an
48746   ** existing BtShared object that we can share with
48747   */
48748   if( isMemdb==0 && isTempDb==0 ){
48749     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
48750       int nFullPathname = pVfs->mxPathname+1;
48751       char *zFullPathname = sqlite3Malloc(nFullPathname);
48752       sqlite3_mutex *mutexShared;
48753       p->sharable = 1;
48754       if( !zFullPathname ){
48755         sqlite3_free(p);
48756         return SQLITE_NOMEM;
48757       }
48758       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
48759       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
48760       sqlite3_mutex_enter(mutexOpen);
48761       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48762       sqlite3_mutex_enter(mutexShared);
48763       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
48764         assert( pBt->nRef>0 );
48765         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
48766                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
48767           int iDb;
48768           for(iDb=db->nDb-1; iDb>=0; iDb--){
48769             Btree *pExisting = db->aDb[iDb].pBt;
48770             if( pExisting && pExisting->pBt==pBt ){
48771               sqlite3_mutex_leave(mutexShared);
48772               sqlite3_mutex_leave(mutexOpen);
48773               sqlite3_free(zFullPathname);
48774               sqlite3_free(p);
48775               return SQLITE_CONSTRAINT;
48776             }
48777           }
48778           p->pBt = pBt;
48779           pBt->nRef++;
48780           break;
48781         }
48782       }
48783       sqlite3_mutex_leave(mutexShared);
48784       sqlite3_free(zFullPathname);
48785     }
48786 #ifdef SQLITE_DEBUG
48787     else{
48788       /* In debug mode, we mark all persistent databases as sharable
48789       ** even when they are not.  This exercises the locking code and
48790       ** gives more opportunity for asserts(sqlite3_mutex_held())
48791       ** statements to find locking problems.
48792       */
48793       p->sharable = 1;
48794     }
48795 #endif
48796   }
48797 #endif
48798   if( pBt==0 ){
48799     /*
48800     ** The following asserts make sure that structures used by the btree are
48801     ** the right size.  This is to guard against size changes that result
48802     ** when compiling on a different architecture.
48803     */
48804     assert( sizeof(i64)==8 || sizeof(i64)==4 );
48805     assert( sizeof(u64)==8 || sizeof(u64)==4 );
48806     assert( sizeof(u32)==4 );
48807     assert( sizeof(u16)==2 );
48808     assert( sizeof(Pgno)==4 );
48809   
48810     pBt = sqlite3MallocZero( sizeof(*pBt) );
48811     if( pBt==0 ){
48812       rc = SQLITE_NOMEM;
48813       goto btree_open_out;
48814     }
48815     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
48816                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
48817     if( rc==SQLITE_OK ){
48818       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
48819     }
48820     if( rc!=SQLITE_OK ){
48821       goto btree_open_out;
48822     }
48823     pBt->openFlags = (u8)flags;
48824     pBt->db = db;
48825     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
48826     p->pBt = pBt;
48827   
48828     pBt->pCursor = 0;
48829     pBt->pPage1 = 0;
48830     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
48831 #ifdef SQLITE_SECURE_DELETE
48832     pBt->secureDelete = 1;
48833 #endif
48834     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
48835     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
48836          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
48837       pBt->pageSize = 0;
48838 #ifndef SQLITE_OMIT_AUTOVACUUM
48839       /* If the magic name ":memory:" will create an in-memory database, then
48840       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
48841       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
48842       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
48843       ** regular file-name. In this case the auto-vacuum applies as per normal.
48844       */
48845       if( zFilename && !isMemdb ){
48846         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
48847         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
48848       }
48849 #endif
48850       nReserve = 0;
48851     }else{
48852       nReserve = zDbHeader[20];
48853       pBt->pageSizeFixed = 1;
48854 #ifndef SQLITE_OMIT_AUTOVACUUM
48855       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
48856       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
48857 #endif
48858     }
48859     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
48860     if( rc ) goto btree_open_out;
48861     pBt->usableSize = pBt->pageSize - nReserve;
48862     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
48863    
48864 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48865     /* Add the new BtShared object to the linked list sharable BtShareds.
48866     */
48867     if( p->sharable ){
48868       sqlite3_mutex *mutexShared;
48869       pBt->nRef = 1;
48870       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48871       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
48872         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
48873         if( pBt->mutex==0 ){
48874           rc = SQLITE_NOMEM;
48875           db->mallocFailed = 0;
48876           goto btree_open_out;
48877         }
48878       }
48879       sqlite3_mutex_enter(mutexShared);
48880       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
48881       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
48882       sqlite3_mutex_leave(mutexShared);
48883     }
48884 #endif
48885   }
48886
48887 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
48888   /* If the new Btree uses a sharable pBtShared, then link the new
48889   ** Btree into the list of all sharable Btrees for the same connection.
48890   ** The list is kept in ascending order by pBt address.
48891   */
48892   if( p->sharable ){
48893     int i;
48894     Btree *pSib;
48895     for(i=0; i<db->nDb; i++){
48896       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
48897         while( pSib->pPrev ){ pSib = pSib->pPrev; }
48898         if( p->pBt<pSib->pBt ){
48899           p->pNext = pSib;
48900           p->pPrev = 0;
48901           pSib->pPrev = p;
48902         }else{
48903           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
48904             pSib = pSib->pNext;
48905           }
48906           p->pNext = pSib->pNext;
48907           p->pPrev = pSib;
48908           if( p->pNext ){
48909             p->pNext->pPrev = p;
48910           }
48911           pSib->pNext = p;
48912         }
48913         break;
48914       }
48915     }
48916   }
48917 #endif
48918   *ppBtree = p;
48919
48920 btree_open_out:
48921   if( rc!=SQLITE_OK ){
48922     if( pBt && pBt->pPager ){
48923       sqlite3PagerClose(pBt->pPager);
48924     }
48925     sqlite3_free(pBt);
48926     sqlite3_free(p);
48927     *ppBtree = 0;
48928   }else{
48929     /* If the B-Tree was successfully opened, set the pager-cache size to the
48930     ** default value. Except, when opening on an existing shared pager-cache,
48931     ** do not change the pager-cache size.
48932     */
48933     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
48934       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
48935     }
48936   }
48937   if( mutexOpen ){
48938     assert( sqlite3_mutex_held(mutexOpen) );
48939     sqlite3_mutex_leave(mutexOpen);
48940   }
48941   return rc;
48942 }
48943
48944 /*
48945 ** Decrement the BtShared.nRef counter.  When it reaches zero,
48946 ** remove the BtShared structure from the sharing list.  Return
48947 ** true if the BtShared.nRef counter reaches zero and return
48948 ** false if it is still positive.
48949 */
48950 static int removeFromSharingList(BtShared *pBt){
48951 #ifndef SQLITE_OMIT_SHARED_CACHE
48952   sqlite3_mutex *pMaster;
48953   BtShared *pList;
48954   int removed = 0;
48955
48956   assert( sqlite3_mutex_notheld(pBt->mutex) );
48957   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
48958   sqlite3_mutex_enter(pMaster);
48959   pBt->nRef--;
48960   if( pBt->nRef<=0 ){
48961     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
48962       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
48963     }else{
48964       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
48965       while( ALWAYS(pList) && pList->pNext!=pBt ){
48966         pList=pList->pNext;
48967       }
48968       if( ALWAYS(pList) ){
48969         pList->pNext = pBt->pNext;
48970       }
48971     }
48972     if( SQLITE_THREADSAFE ){
48973       sqlite3_mutex_free(pBt->mutex);
48974     }
48975     removed = 1;
48976   }
48977   sqlite3_mutex_leave(pMaster);
48978   return removed;
48979 #else
48980   return 1;
48981 #endif
48982 }
48983
48984 /*
48985 ** Make sure pBt->pTmpSpace points to an allocation of 
48986 ** MX_CELL_SIZE(pBt) bytes.
48987 */
48988 static void allocateTempSpace(BtShared *pBt){
48989   if( !pBt->pTmpSpace ){
48990     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
48991   }
48992 }
48993
48994 /*
48995 ** Free the pBt->pTmpSpace allocation
48996 */
48997 static void freeTempSpace(BtShared *pBt){
48998   sqlite3PageFree( pBt->pTmpSpace);
48999   pBt->pTmpSpace = 0;
49000 }
49001
49002 /*
49003 ** Close an open database and invalidate all cursors.
49004 */
49005 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49006   BtShared *pBt = p->pBt;
49007   BtCursor *pCur;
49008
49009   /* Close all cursors opened via this handle.  */
49010   assert( sqlite3_mutex_held(p->db->mutex) );
49011   sqlite3BtreeEnter(p);
49012   pCur = pBt->pCursor;
49013   while( pCur ){
49014     BtCursor *pTmp = pCur;
49015     pCur = pCur->pNext;
49016     if( pTmp->pBtree==p ){
49017       sqlite3BtreeCloseCursor(pTmp);
49018     }
49019   }
49020
49021   /* Rollback any active transaction and free the handle structure.
49022   ** The call to sqlite3BtreeRollback() drops any table-locks held by
49023   ** this handle.
49024   */
49025   sqlite3BtreeRollback(p);
49026   sqlite3BtreeLeave(p);
49027
49028   /* If there are still other outstanding references to the shared-btree
49029   ** structure, return now. The remainder of this procedure cleans 
49030   ** up the shared-btree.
49031   */
49032   assert( p->wantToLock==0 && p->locked==0 );
49033   if( !p->sharable || removeFromSharingList(pBt) ){
49034     /* The pBt is no longer on the sharing list, so we can access
49035     ** it without having to hold the mutex.
49036     **
49037     ** Clean out and delete the BtShared object.
49038     */
49039     assert( !pBt->pCursor );
49040     sqlite3PagerClose(pBt->pPager);
49041     if( pBt->xFreeSchema && pBt->pSchema ){
49042       pBt->xFreeSchema(pBt->pSchema);
49043     }
49044     sqlite3DbFree(0, pBt->pSchema);
49045     freeTempSpace(pBt);
49046     sqlite3_free(pBt);
49047   }
49048
49049 #ifndef SQLITE_OMIT_SHARED_CACHE
49050   assert( p->wantToLock==0 );
49051   assert( p->locked==0 );
49052   if( p->pPrev ) p->pPrev->pNext = p->pNext;
49053   if( p->pNext ) p->pNext->pPrev = p->pPrev;
49054 #endif
49055
49056   sqlite3_free(p);
49057   return SQLITE_OK;
49058 }
49059
49060 /*
49061 ** Change the limit on the number of pages allowed in the cache.
49062 **
49063 ** The maximum number of cache pages is set to the absolute
49064 ** value of mxPage.  If mxPage is negative, the pager will
49065 ** operate asynchronously - it will not stop to do fsync()s
49066 ** to insure data is written to the disk surface before
49067 ** continuing.  Transactions still work if synchronous is off,
49068 ** and the database cannot be corrupted if this program
49069 ** crashes.  But if the operating system crashes or there is
49070 ** an abrupt power failure when synchronous is off, the database
49071 ** could be left in an inconsistent and unrecoverable state.
49072 ** Synchronous is on by default so database corruption is not
49073 ** normally a worry.
49074 */
49075 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49076   BtShared *pBt = p->pBt;
49077   assert( sqlite3_mutex_held(p->db->mutex) );
49078   sqlite3BtreeEnter(p);
49079   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49080   sqlite3BtreeLeave(p);
49081   return SQLITE_OK;
49082 }
49083
49084 /*
49085 ** Change the way data is synced to disk in order to increase or decrease
49086 ** how well the database resists damage due to OS crashes and power
49087 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
49088 ** there is a high probability of damage)  Level 2 is the default.  There
49089 ** is a very low but non-zero probability of damage.  Level 3 reduces the
49090 ** probability of damage to near zero but with a write performance reduction.
49091 */
49092 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49093 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49094   Btree *p,              /* The btree to set the safety level on */
49095   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
49096   int fullSync,          /* PRAGMA fullfsync. */
49097   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
49098 ){
49099   BtShared *pBt = p->pBt;
49100   assert( sqlite3_mutex_held(p->db->mutex) );
49101   assert( level>=1 && level<=3 );
49102   sqlite3BtreeEnter(p);
49103   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49104   sqlite3BtreeLeave(p);
49105   return SQLITE_OK;
49106 }
49107 #endif
49108
49109 /*
49110 ** Return TRUE if the given btree is set to safety level 1.  In other
49111 ** words, return TRUE if no sync() occurs on the disk files.
49112 */
49113 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49114   BtShared *pBt = p->pBt;
49115   int rc;
49116   assert( sqlite3_mutex_held(p->db->mutex) );  
49117   sqlite3BtreeEnter(p);
49118   assert( pBt && pBt->pPager );
49119   rc = sqlite3PagerNosync(pBt->pPager);
49120   sqlite3BtreeLeave(p);
49121   return rc;
49122 }
49123
49124 /*
49125 ** Change the default pages size and the number of reserved bytes per page.
49126 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
49127 ** without changing anything.
49128 **
49129 ** The page size must be a power of 2 between 512 and 65536.  If the page
49130 ** size supplied does not meet this constraint then the page size is not
49131 ** changed.
49132 **
49133 ** Page sizes are constrained to be a power of two so that the region
49134 ** of the database file used for locking (beginning at PENDING_BYTE,
49135 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
49136 ** at the beginning of a page.
49137 **
49138 ** If parameter nReserve is less than zero, then the number of reserved
49139 ** bytes per page is left unchanged.
49140 **
49141 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49142 ** and autovacuum mode can no longer be changed.
49143 */
49144 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49145   int rc = SQLITE_OK;
49146   BtShared *pBt = p->pBt;
49147   assert( nReserve>=-1 && nReserve<=255 );
49148   sqlite3BtreeEnter(p);
49149   if( pBt->pageSizeFixed ){
49150     sqlite3BtreeLeave(p);
49151     return SQLITE_READONLY;
49152   }
49153   if( nReserve<0 ){
49154     nReserve = pBt->pageSize - pBt->usableSize;
49155   }
49156   assert( nReserve>=0 && nReserve<=255 );
49157   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49158         ((pageSize-1)&pageSize)==0 ){
49159     assert( (pageSize & 7)==0 );
49160     assert( !pBt->pPage1 && !pBt->pCursor );
49161     pBt->pageSize = (u32)pageSize;
49162     freeTempSpace(pBt);
49163   }
49164   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49165   pBt->usableSize = pBt->pageSize - (u16)nReserve;
49166   if( iFix ) pBt->pageSizeFixed = 1;
49167   sqlite3BtreeLeave(p);
49168   return rc;
49169 }
49170
49171 /*
49172 ** Return the currently defined page size
49173 */
49174 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49175   return p->pBt->pageSize;
49176 }
49177
49178 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49179 /*
49180 ** Return the number of bytes of space at the end of every page that
49181 ** are intentually left unused.  This is the "reserved" space that is
49182 ** sometimes used by extensions.
49183 */
49184 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49185   int n;
49186   sqlite3BtreeEnter(p);
49187   n = p->pBt->pageSize - p->pBt->usableSize;
49188   sqlite3BtreeLeave(p);
49189   return n;
49190 }
49191
49192 /*
49193 ** Set the maximum page count for a database if mxPage is positive.
49194 ** No changes are made if mxPage is 0 or negative.
49195 ** Regardless of the value of mxPage, return the maximum page count.
49196 */
49197 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49198   int n;
49199   sqlite3BtreeEnter(p);
49200   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49201   sqlite3BtreeLeave(p);
49202   return n;
49203 }
49204
49205 /*
49206 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
49207 ** then make no changes.  Always return the value of the secureDelete
49208 ** setting after the change.
49209 */
49210 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49211   int b;
49212   if( p==0 ) return 0;
49213   sqlite3BtreeEnter(p);
49214   if( newFlag>=0 ){
49215     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49216   } 
49217   b = p->pBt->secureDelete;
49218   sqlite3BtreeLeave(p);
49219   return b;
49220 }
49221 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49222
49223 /*
49224 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49225 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49226 ** is disabled. The default value for the auto-vacuum property is 
49227 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49228 */
49229 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49230 #ifdef SQLITE_OMIT_AUTOVACUUM
49231   return SQLITE_READONLY;
49232 #else
49233   BtShared *pBt = p->pBt;
49234   int rc = SQLITE_OK;
49235   u8 av = (u8)autoVacuum;
49236
49237   sqlite3BtreeEnter(p);
49238   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49239     rc = SQLITE_READONLY;
49240   }else{
49241     pBt->autoVacuum = av ?1:0;
49242     pBt->incrVacuum = av==2 ?1:0;
49243   }
49244   sqlite3BtreeLeave(p);
49245   return rc;
49246 #endif
49247 }
49248
49249 /*
49250 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
49251 ** enabled 1 is returned. Otherwise 0.
49252 */
49253 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49254 #ifdef SQLITE_OMIT_AUTOVACUUM
49255   return BTREE_AUTOVACUUM_NONE;
49256 #else
49257   int rc;
49258   sqlite3BtreeEnter(p);
49259   rc = (
49260     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49261     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49262     BTREE_AUTOVACUUM_INCR
49263   );
49264   sqlite3BtreeLeave(p);
49265   return rc;
49266 #endif
49267 }
49268
49269
49270 /*
49271 ** Get a reference to pPage1 of the database file.  This will
49272 ** also acquire a readlock on that file.
49273 **
49274 ** SQLITE_OK is returned on success.  If the file is not a
49275 ** well-formed database file, then SQLITE_CORRUPT is returned.
49276 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
49277 ** is returned if we run out of memory. 
49278 */
49279 static int lockBtree(BtShared *pBt){
49280   int rc;              /* Result code from subfunctions */
49281   MemPage *pPage1;     /* Page 1 of the database file */
49282   int nPage;           /* Number of pages in the database */
49283   int nPageFile = 0;   /* Number of pages in the database file */
49284   int nPageHeader;     /* Number of pages in the database according to hdr */
49285
49286   assert( sqlite3_mutex_held(pBt->mutex) );
49287   assert( pBt->pPage1==0 );
49288   rc = sqlite3PagerSharedLock(pBt->pPager);
49289   if( rc!=SQLITE_OK ) return rc;
49290   rc = btreeGetPage(pBt, 1, &pPage1, 0);
49291   if( rc!=SQLITE_OK ) return rc;
49292
49293   /* Do some checking to help insure the file we opened really is
49294   ** a valid database file. 
49295   */
49296   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49297   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49298   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49299     nPage = nPageFile;
49300   }
49301   if( nPage>0 ){
49302     u32 pageSize;
49303     u32 usableSize;
49304     u8 *page1 = pPage1->aData;
49305     rc = SQLITE_NOTADB;
49306     if( memcmp(page1, zMagicHeader, 16)!=0 ){
49307       goto page1_init_failed;
49308     }
49309
49310 #ifdef SQLITE_OMIT_WAL
49311     if( page1[18]>1 ){
49312       pBt->readOnly = 1;
49313     }
49314     if( page1[19]>1 ){
49315       goto page1_init_failed;
49316     }
49317 #else
49318     if( page1[18]>2 ){
49319       pBt->readOnly = 1;
49320     }
49321     if( page1[19]>2 ){
49322       goto page1_init_failed;
49323     }
49324
49325     /* If the write version is set to 2, this database should be accessed
49326     ** in WAL mode. If the log is not already open, open it now. Then 
49327     ** return SQLITE_OK and return without populating BtShared.pPage1.
49328     ** The caller detects this and calls this function again. This is
49329     ** required as the version of page 1 currently in the page1 buffer
49330     ** may not be the latest version - there may be a newer one in the log
49331     ** file.
49332     */
49333     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49334       int isOpen = 0;
49335       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49336       if( rc!=SQLITE_OK ){
49337         goto page1_init_failed;
49338       }else if( isOpen==0 ){
49339         releasePage(pPage1);
49340         return SQLITE_OK;
49341       }
49342       rc = SQLITE_NOTADB;
49343     }
49344 #endif
49345
49346     /* The maximum embedded fraction must be exactly 25%.  And the minimum
49347     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49348     ** The original design allowed these amounts to vary, but as of
49349     ** version 3.6.0, we require them to be fixed.
49350     */
49351     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49352       goto page1_init_failed;
49353     }
49354     pageSize = (page1[16]<<8) | (page1[17]<<16);
49355     if( ((pageSize-1)&pageSize)!=0
49356      || pageSize>SQLITE_MAX_PAGE_SIZE 
49357      || pageSize<=256 
49358     ){
49359       goto page1_init_failed;
49360     }
49361     assert( (pageSize & 7)==0 );
49362     usableSize = pageSize - page1[20];
49363     if( (u32)pageSize!=pBt->pageSize ){
49364       /* After reading the first page of the database assuming a page size
49365       ** of BtShared.pageSize, we have discovered that the page-size is
49366       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49367       ** zero and return SQLITE_OK. The caller will call this function
49368       ** again with the correct page-size.
49369       */
49370       releasePage(pPage1);
49371       pBt->usableSize = usableSize;
49372       pBt->pageSize = pageSize;
49373       freeTempSpace(pBt);
49374       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49375                                    pageSize-usableSize);
49376       return rc;
49377     }
49378     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49379       rc = SQLITE_CORRUPT_BKPT;
49380       goto page1_init_failed;
49381     }
49382     if( usableSize<480 ){
49383       goto page1_init_failed;
49384     }
49385     pBt->pageSize = pageSize;
49386     pBt->usableSize = usableSize;
49387 #ifndef SQLITE_OMIT_AUTOVACUUM
49388     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49389     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49390 #endif
49391   }
49392
49393   /* maxLocal is the maximum amount of payload to store locally for
49394   ** a cell.  Make sure it is small enough so that at least minFanout
49395   ** cells can will fit on one page.  We assume a 10-byte page header.
49396   ** Besides the payload, the cell must store:
49397   **     2-byte pointer to the cell
49398   **     4-byte child pointer
49399   **     9-byte nKey value
49400   **     4-byte nData value
49401   **     4-byte overflow page pointer
49402   ** So a cell consists of a 2-byte pointer, a header which is as much as
49403   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49404   ** page pointer.
49405   */
49406   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49407   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49408   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49409   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49410   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49411   pBt->pPage1 = pPage1;
49412   pBt->nPage = nPage;
49413   return SQLITE_OK;
49414
49415 page1_init_failed:
49416   releasePage(pPage1);
49417   pBt->pPage1 = 0;
49418   return rc;
49419 }
49420
49421 /*
49422 ** If there are no outstanding cursors and we are not in the middle
49423 ** of a transaction but there is a read lock on the database, then
49424 ** this routine unrefs the first page of the database file which 
49425 ** has the effect of releasing the read lock.
49426 **
49427 ** If there is a transaction in progress, this routine is a no-op.
49428 */
49429 static void unlockBtreeIfUnused(BtShared *pBt){
49430   assert( sqlite3_mutex_held(pBt->mutex) );
49431   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49432   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49433     assert( pBt->pPage1->aData );
49434     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49435     assert( pBt->pPage1->aData );
49436     releasePage(pBt->pPage1);
49437     pBt->pPage1 = 0;
49438   }
49439 }
49440
49441 /*
49442 ** If pBt points to an empty file then convert that empty file
49443 ** into a new empty database by initializing the first page of
49444 ** the database.
49445 */
49446 static int newDatabase(BtShared *pBt){
49447   MemPage *pP1;
49448   unsigned char *data;
49449   int rc;
49450
49451   assert( sqlite3_mutex_held(pBt->mutex) );
49452   if( pBt->nPage>0 ){
49453     return SQLITE_OK;
49454   }
49455   pP1 = pBt->pPage1;
49456   assert( pP1!=0 );
49457   data = pP1->aData;
49458   rc = sqlite3PagerWrite(pP1->pDbPage);
49459   if( rc ) return rc;
49460   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49461   assert( sizeof(zMagicHeader)==16 );
49462   data[16] = (u8)((pBt->pageSize>>8)&0xff);
49463   data[17] = (u8)((pBt->pageSize>>16)&0xff);
49464   data[18] = 1;
49465   data[19] = 1;
49466   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49467   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49468   data[21] = 64;
49469   data[22] = 32;
49470   data[23] = 32;
49471   memset(&data[24], 0, 100-24);
49472   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49473   pBt->pageSizeFixed = 1;
49474 #ifndef SQLITE_OMIT_AUTOVACUUM
49475   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
49476   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
49477   put4byte(&data[36 + 4*4], pBt->autoVacuum);
49478   put4byte(&data[36 + 7*4], pBt->incrVacuum);
49479 #endif
49480   pBt->nPage = 1;
49481   data[31] = 1;
49482   return SQLITE_OK;
49483 }
49484
49485 /*
49486 ** Attempt to start a new transaction. A write-transaction
49487 ** is started if the second argument is nonzero, otherwise a read-
49488 ** transaction.  If the second argument is 2 or more and exclusive
49489 ** transaction is started, meaning that no other process is allowed
49490 ** to access the database.  A preexisting transaction may not be
49491 ** upgraded to exclusive by calling this routine a second time - the
49492 ** exclusivity flag only works for a new transaction.
49493 **
49494 ** A write-transaction must be started before attempting any 
49495 ** changes to the database.  None of the following routines 
49496 ** will work unless a transaction is started first:
49497 **
49498 **      sqlite3BtreeCreateTable()
49499 **      sqlite3BtreeCreateIndex()
49500 **      sqlite3BtreeClearTable()
49501 **      sqlite3BtreeDropTable()
49502 **      sqlite3BtreeInsert()
49503 **      sqlite3BtreeDelete()
49504 **      sqlite3BtreeUpdateMeta()
49505 **
49506 ** If an initial attempt to acquire the lock fails because of lock contention
49507 ** and the database was previously unlocked, then invoke the busy handler
49508 ** if there is one.  But if there was previously a read-lock, do not
49509 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
49510 ** returned when there is already a read-lock in order to avoid a deadlock.
49511 **
49512 ** Suppose there are two processes A and B.  A has a read lock and B has
49513 ** a reserved lock.  B tries to promote to exclusive but is blocked because
49514 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
49515 ** One or the other of the two processes must give way or there can be
49516 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
49517 ** when A already has a read lock, we encourage A to give up and let B
49518 ** proceed.
49519 */
49520 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
49521   sqlite3 *pBlock = 0;
49522   BtShared *pBt = p->pBt;
49523   int rc = SQLITE_OK;
49524
49525   sqlite3BtreeEnter(p);
49526   btreeIntegrity(p);
49527
49528   /* If the btree is already in a write-transaction, or it
49529   ** is already in a read-transaction and a read-transaction
49530   ** is requested, this is a no-op.
49531   */
49532   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
49533     goto trans_begun;
49534   }
49535
49536   /* Write transactions are not possible on a read-only database */
49537   if( pBt->readOnly && wrflag ){
49538     rc = SQLITE_READONLY;
49539     goto trans_begun;
49540   }
49541
49542 #ifndef SQLITE_OMIT_SHARED_CACHE
49543   /* If another database handle has already opened a write transaction 
49544   ** on this shared-btree structure and a second write transaction is
49545   ** requested, return SQLITE_LOCKED.
49546   */
49547   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
49548     pBlock = pBt->pWriter->db;
49549   }else if( wrflag>1 ){
49550     BtLock *pIter;
49551     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49552       if( pIter->pBtree!=p ){
49553         pBlock = pIter->pBtree->db;
49554         break;
49555       }
49556     }
49557   }
49558   if( pBlock ){
49559     sqlite3ConnectionBlocked(p->db, pBlock);
49560     rc = SQLITE_LOCKED_SHAREDCACHE;
49561     goto trans_begun;
49562   }
49563 #endif
49564
49565   /* Any read-only or read-write transaction implies a read-lock on 
49566   ** page 1. So if some other shared-cache client already has a write-lock 
49567   ** on page 1, the transaction cannot be opened. */
49568   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
49569   if( SQLITE_OK!=rc ) goto trans_begun;
49570
49571   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
49572   do {
49573     /* Call lockBtree() until either pBt->pPage1 is populated or
49574     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
49575     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
49576     ** reading page 1 it discovers that the page-size of the database 
49577     ** file is not pBt->pageSize. In this case lockBtree() will update
49578     ** pBt->pageSize to the page-size of the file on disk.
49579     */
49580     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
49581
49582     if( rc==SQLITE_OK && wrflag ){
49583       if( pBt->readOnly ){
49584         rc = SQLITE_READONLY;
49585       }else{
49586         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
49587         if( rc==SQLITE_OK ){
49588           rc = newDatabase(pBt);
49589         }
49590       }
49591     }
49592   
49593     if( rc!=SQLITE_OK ){
49594       unlockBtreeIfUnused(pBt);
49595     }
49596   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
49597           btreeInvokeBusyHandler(pBt) );
49598
49599   if( rc==SQLITE_OK ){
49600     if( p->inTrans==TRANS_NONE ){
49601       pBt->nTransaction++;
49602 #ifndef SQLITE_OMIT_SHARED_CACHE
49603       if( p->sharable ){
49604         assert( p->lock.pBtree==p && p->lock.iTable==1 );
49605         p->lock.eLock = READ_LOCK;
49606         p->lock.pNext = pBt->pLock;
49607         pBt->pLock = &p->lock;
49608       }
49609 #endif
49610     }
49611     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
49612     if( p->inTrans>pBt->inTransaction ){
49613       pBt->inTransaction = p->inTrans;
49614     }
49615     if( wrflag ){
49616       MemPage *pPage1 = pBt->pPage1;
49617 #ifndef SQLITE_OMIT_SHARED_CACHE
49618       assert( !pBt->pWriter );
49619       pBt->pWriter = p;
49620       pBt->isExclusive = (u8)(wrflag>1);
49621 #endif
49622
49623       /* If the db-size header field is incorrect (as it may be if an old
49624       ** client has been writing the database file), update it now. Doing
49625       ** this sooner rather than later means the database size can safely 
49626       ** re-read the database size from page 1 if a savepoint or transaction
49627       ** rollback occurs within the transaction.
49628       */
49629       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
49630         rc = sqlite3PagerWrite(pPage1->pDbPage);
49631         if( rc==SQLITE_OK ){
49632           put4byte(&pPage1->aData[28], pBt->nPage);
49633         }
49634       }
49635     }
49636   }
49637
49638
49639 trans_begun:
49640   if( rc==SQLITE_OK && wrflag ){
49641     /* This call makes sure that the pager has the correct number of
49642     ** open savepoints. If the second parameter is greater than 0 and
49643     ** the sub-journal is not already open, then it will be opened here.
49644     */
49645     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
49646   }
49647
49648   btreeIntegrity(p);
49649   sqlite3BtreeLeave(p);
49650   return rc;
49651 }
49652
49653 #ifndef SQLITE_OMIT_AUTOVACUUM
49654
49655 /*
49656 ** Set the pointer-map entries for all children of page pPage. Also, if
49657 ** pPage contains cells that point to overflow pages, set the pointer
49658 ** map entries for the overflow pages as well.
49659 */
49660 static int setChildPtrmaps(MemPage *pPage){
49661   int i;                             /* Counter variable */
49662   int nCell;                         /* Number of cells in page pPage */
49663   int rc;                            /* Return code */
49664   BtShared *pBt = pPage->pBt;
49665   u8 isInitOrig = pPage->isInit;
49666   Pgno pgno = pPage->pgno;
49667
49668   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49669   rc = btreeInitPage(pPage);
49670   if( rc!=SQLITE_OK ){
49671     goto set_child_ptrmaps_out;
49672   }
49673   nCell = pPage->nCell;
49674
49675   for(i=0; i<nCell; i++){
49676     u8 *pCell = findCell(pPage, i);
49677
49678     ptrmapPutOvflPtr(pPage, pCell, &rc);
49679
49680     if( !pPage->leaf ){
49681       Pgno childPgno = get4byte(pCell);
49682       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49683     }
49684   }
49685
49686   if( !pPage->leaf ){
49687     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49688     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49689   }
49690
49691 set_child_ptrmaps_out:
49692   pPage->isInit = isInitOrig;
49693   return rc;
49694 }
49695
49696 /*
49697 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
49698 ** that it points to iTo. Parameter eType describes the type of pointer to
49699 ** be modified, as  follows:
49700 **
49701 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
49702 **                   page of pPage.
49703 **
49704 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
49705 **                   page pointed to by one of the cells on pPage.
49706 **
49707 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
49708 **                   overflow page in the list.
49709 */
49710 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
49711   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49712   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49713   if( eType==PTRMAP_OVERFLOW2 ){
49714     /* The pointer is always the first 4 bytes of the page in this case.  */
49715     if( get4byte(pPage->aData)!=iFrom ){
49716       return SQLITE_CORRUPT_BKPT;
49717     }
49718     put4byte(pPage->aData, iTo);
49719   }else{
49720     u8 isInitOrig = pPage->isInit;
49721     int i;
49722     int nCell;
49723
49724     btreeInitPage(pPage);
49725     nCell = pPage->nCell;
49726
49727     for(i=0; i<nCell; i++){
49728       u8 *pCell = findCell(pPage, i);
49729       if( eType==PTRMAP_OVERFLOW1 ){
49730         CellInfo info;
49731         btreeParseCellPtr(pPage, pCell, &info);
49732         if( info.iOverflow ){
49733           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
49734             put4byte(&pCell[info.iOverflow], iTo);
49735             break;
49736           }
49737         }
49738       }else{
49739         if( get4byte(pCell)==iFrom ){
49740           put4byte(pCell, iTo);
49741           break;
49742         }
49743       }
49744     }
49745   
49746     if( i==nCell ){
49747       if( eType!=PTRMAP_BTREE || 
49748           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
49749         return SQLITE_CORRUPT_BKPT;
49750       }
49751       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
49752     }
49753
49754     pPage->isInit = isInitOrig;
49755   }
49756   return SQLITE_OK;
49757 }
49758
49759
49760 /*
49761 ** Move the open database page pDbPage to location iFreePage in the 
49762 ** database. The pDbPage reference remains valid.
49763 **
49764 ** The isCommit flag indicates that there is no need to remember that
49765 ** the journal needs to be sync()ed before database page pDbPage->pgno 
49766 ** can be written to. The caller has already promised not to write to that
49767 ** page.
49768 */
49769 static int relocatePage(
49770   BtShared *pBt,           /* Btree */
49771   MemPage *pDbPage,        /* Open page to move */
49772   u8 eType,                /* Pointer map 'type' entry for pDbPage */
49773   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
49774   Pgno iFreePage,          /* The location to move pDbPage to */
49775   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
49776 ){
49777   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
49778   Pgno iDbPage = pDbPage->pgno;
49779   Pager *pPager = pBt->pPager;
49780   int rc;
49781
49782   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
49783       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
49784   assert( sqlite3_mutex_held(pBt->mutex) );
49785   assert( pDbPage->pBt==pBt );
49786
49787   /* Move page iDbPage from its current location to page number iFreePage */
49788   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
49789       iDbPage, iFreePage, iPtrPage, eType));
49790   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
49791   if( rc!=SQLITE_OK ){
49792     return rc;
49793   }
49794   pDbPage->pgno = iFreePage;
49795
49796   /* If pDbPage was a btree-page, then it may have child pages and/or cells
49797   ** that point to overflow pages. The pointer map entries for all these
49798   ** pages need to be changed.
49799   **
49800   ** If pDbPage is an overflow page, then the first 4 bytes may store a
49801   ** pointer to a subsequent overflow page. If this is the case, then
49802   ** the pointer map needs to be updated for the subsequent overflow page.
49803   */
49804   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
49805     rc = setChildPtrmaps(pDbPage);
49806     if( rc!=SQLITE_OK ){
49807       return rc;
49808     }
49809   }else{
49810     Pgno nextOvfl = get4byte(pDbPage->aData);
49811     if( nextOvfl!=0 ){
49812       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
49813       if( rc!=SQLITE_OK ){
49814         return rc;
49815       }
49816     }
49817   }
49818
49819   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
49820   ** that it points at iFreePage. Also fix the pointer map entry for
49821   ** iPtrPage.
49822   */
49823   if( eType!=PTRMAP_ROOTPAGE ){
49824     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
49825     if( rc!=SQLITE_OK ){
49826       return rc;
49827     }
49828     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
49829     if( rc!=SQLITE_OK ){
49830       releasePage(pPtrPage);
49831       return rc;
49832     }
49833     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
49834     releasePage(pPtrPage);
49835     if( rc==SQLITE_OK ){
49836       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
49837     }
49838   }
49839   return rc;
49840 }
49841
49842 /* Forward declaration required by incrVacuumStep(). */
49843 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
49844
49845 /*
49846 ** Perform a single step of an incremental-vacuum. If successful,
49847 ** return SQLITE_OK. If there is no work to do (and therefore no
49848 ** point in calling this function again), return SQLITE_DONE.
49849 **
49850 ** More specificly, this function attempts to re-organize the 
49851 ** database so that the last page of the file currently in use
49852 ** is no longer in use.
49853 **
49854 ** If the nFin parameter is non-zero, this function assumes
49855 ** that the caller will keep calling incrVacuumStep() until
49856 ** it returns SQLITE_DONE or an error, and that nFin is the
49857 ** number of pages the database file will contain after this 
49858 ** process is complete.  If nFin is zero, it is assumed that
49859 ** incrVacuumStep() will be called a finite amount of times
49860 ** which may or may not empty the freelist.  A full autovacuum
49861 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
49862 */
49863 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
49864   Pgno nFreeList;           /* Number of pages still on the free-list */
49865   int rc;
49866
49867   assert( sqlite3_mutex_held(pBt->mutex) );
49868   assert( iLastPg>nFin );
49869
49870   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
49871     u8 eType;
49872     Pgno iPtrPage;
49873
49874     nFreeList = get4byte(&pBt->pPage1->aData[36]);
49875     if( nFreeList==0 ){
49876       return SQLITE_DONE;
49877     }
49878
49879     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
49880     if( rc!=SQLITE_OK ){
49881       return rc;
49882     }
49883     if( eType==PTRMAP_ROOTPAGE ){
49884       return SQLITE_CORRUPT_BKPT;
49885     }
49886
49887     if( eType==PTRMAP_FREEPAGE ){
49888       if( nFin==0 ){
49889         /* Remove the page from the files free-list. This is not required
49890         ** if nFin is non-zero. In that case, the free-list will be
49891         ** truncated to zero after this function returns, so it doesn't 
49892         ** matter if it still contains some garbage entries.
49893         */
49894         Pgno iFreePg;
49895         MemPage *pFreePg;
49896         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
49897         if( rc!=SQLITE_OK ){
49898           return rc;
49899         }
49900         assert( iFreePg==iLastPg );
49901         releasePage(pFreePg);
49902       }
49903     } else {
49904       Pgno iFreePg;             /* Index of free page to move pLastPg to */
49905       MemPage *pLastPg;
49906
49907       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
49908       if( rc!=SQLITE_OK ){
49909         return rc;
49910       }
49911
49912       /* If nFin is zero, this loop runs exactly once and page pLastPg
49913       ** is swapped with the first free page pulled off the free list.
49914       **
49915       ** On the other hand, if nFin is greater than zero, then keep
49916       ** looping until a free-page located within the first nFin pages
49917       ** of the file is found.
49918       */
49919       do {
49920         MemPage *pFreePg;
49921         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
49922         if( rc!=SQLITE_OK ){
49923           releasePage(pLastPg);
49924           return rc;
49925         }
49926         releasePage(pFreePg);
49927       }while( nFin!=0 && iFreePg>nFin );
49928       assert( iFreePg<iLastPg );
49929       
49930       rc = sqlite3PagerWrite(pLastPg->pDbPage);
49931       if( rc==SQLITE_OK ){
49932         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
49933       }
49934       releasePage(pLastPg);
49935       if( rc!=SQLITE_OK ){
49936         return rc;
49937       }
49938     }
49939   }
49940
49941   if( nFin==0 ){
49942     iLastPg--;
49943     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
49944       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
49945         MemPage *pPg;
49946         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
49947         if( rc!=SQLITE_OK ){
49948           return rc;
49949         }
49950         rc = sqlite3PagerWrite(pPg->pDbPage);
49951         releasePage(pPg);
49952         if( rc!=SQLITE_OK ){
49953           return rc;
49954         }
49955       }
49956       iLastPg--;
49957     }
49958     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
49959     pBt->nPage = iLastPg;
49960   }
49961   return SQLITE_OK;
49962 }
49963
49964 /*
49965 ** A write-transaction must be opened before calling this function.
49966 ** It performs a single unit of work towards an incremental vacuum.
49967 **
49968 ** If the incremental vacuum is finished after this function has run,
49969 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
49970 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
49971 */
49972 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
49973   int rc;
49974   BtShared *pBt = p->pBt;
49975
49976   sqlite3BtreeEnter(p);
49977   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
49978   if( !pBt->autoVacuum ){
49979     rc = SQLITE_DONE;
49980   }else{
49981     invalidateAllOverflowCache(pBt);
49982     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
49983     if( rc==SQLITE_OK ){
49984       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
49985       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
49986     }
49987   }
49988   sqlite3BtreeLeave(p);
49989   return rc;
49990 }
49991
49992 /*
49993 ** This routine is called prior to sqlite3PagerCommit when a transaction
49994 ** is commited for an auto-vacuum database.
49995 **
49996 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
49997 ** the database file should be truncated to during the commit process. 
49998 ** i.e. the database has been reorganized so that only the first *pnTrunc
49999 ** pages are in use.
50000 */
50001 static int autoVacuumCommit(BtShared *pBt){
50002   int rc = SQLITE_OK;
50003   Pager *pPager = pBt->pPager;
50004   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50005
50006   assert( sqlite3_mutex_held(pBt->mutex) );
50007   invalidateAllOverflowCache(pBt);
50008   assert(pBt->autoVacuum);
50009   if( !pBt->incrVacuum ){
50010     Pgno nFin;         /* Number of pages in database after autovacuuming */
50011     Pgno nFree;        /* Number of pages on the freelist initially */
50012     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
50013     Pgno iFree;        /* The next page to be freed */
50014     int nEntry;        /* Number of entries on one ptrmap page */
50015     Pgno nOrig;        /* Database size before freeing */
50016
50017     nOrig = btreePagecount(pBt);
50018     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50019       /* It is not possible to create a database for which the final page
50020       ** is either a pointer-map page or the pending-byte page. If one
50021       ** is encountered, this indicates corruption.
50022       */
50023       return SQLITE_CORRUPT_BKPT;
50024     }
50025
50026     nFree = get4byte(&pBt->pPage1->aData[36]);
50027     nEntry = pBt->usableSize/5;
50028     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50029     nFin = nOrig - nFree - nPtrmap;
50030     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50031       nFin--;
50032     }
50033     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50034       nFin--;
50035     }
50036     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50037
50038     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50039       rc = incrVacuumStep(pBt, nFin, iFree);
50040     }
50041     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50042       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50043       put4byte(&pBt->pPage1->aData[32], 0);
50044       put4byte(&pBt->pPage1->aData[36], 0);
50045       put4byte(&pBt->pPage1->aData[28], nFin);
50046       sqlite3PagerTruncateImage(pBt->pPager, nFin);
50047       pBt->nPage = nFin;
50048     }
50049     if( rc!=SQLITE_OK ){
50050       sqlite3PagerRollback(pPager);
50051     }
50052   }
50053
50054   assert( nRef==sqlite3PagerRefcount(pPager) );
50055   return rc;
50056 }
50057
50058 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50059 # define setChildPtrmaps(x) SQLITE_OK
50060 #endif
50061
50062 /*
50063 ** This routine does the first phase of a two-phase commit.  This routine
50064 ** causes a rollback journal to be created (if it does not already exist)
50065 ** and populated with enough information so that if a power loss occurs
50066 ** the database can be restored to its original state by playing back
50067 ** the journal.  Then the contents of the journal are flushed out to
50068 ** the disk.  After the journal is safely on oxide, the changes to the
50069 ** database are written into the database file and flushed to oxide.
50070 ** At the end of this call, the rollback journal still exists on the
50071 ** disk and we are still holding all locks, so the transaction has not
50072 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50073 ** commit process.
50074 **
50075 ** This call is a no-op if no write-transaction is currently active on pBt.
50076 **
50077 ** Otherwise, sync the database file for the btree pBt. zMaster points to
50078 ** the name of a master journal file that should be written into the
50079 ** individual journal file, or is NULL, indicating no master journal file 
50080 ** (single database transaction).
50081 **
50082 ** When this is called, the master journal should already have been
50083 ** created, populated with this journal pointer and synced to disk.
50084 **
50085 ** Once this is routine has returned, the only thing required to commit
50086 ** the write-transaction for this database file is to delete the journal.
50087 */
50088 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50089   int rc = SQLITE_OK;
50090   if( p->inTrans==TRANS_WRITE ){
50091     BtShared *pBt = p->pBt;
50092     sqlite3BtreeEnter(p);
50093 #ifndef SQLITE_OMIT_AUTOVACUUM
50094     if( pBt->autoVacuum ){
50095       rc = autoVacuumCommit(pBt);
50096       if( rc!=SQLITE_OK ){
50097         sqlite3BtreeLeave(p);
50098         return rc;
50099       }
50100     }
50101 #endif
50102     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50103     sqlite3BtreeLeave(p);
50104   }
50105   return rc;
50106 }
50107
50108 /*
50109 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50110 ** at the conclusion of a transaction.
50111 */
50112 static void btreeEndTransaction(Btree *p){
50113   BtShared *pBt = p->pBt;
50114   assert( sqlite3BtreeHoldsMutex(p) );
50115
50116   btreeClearHasContent(pBt);
50117   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50118     /* If there are other active statements that belong to this database
50119     ** handle, downgrade to a read-only transaction. The other statements
50120     ** may still be reading from the database.  */
50121     downgradeAllSharedCacheTableLocks(p);
50122     p->inTrans = TRANS_READ;
50123   }else{
50124     /* If the handle had any kind of transaction open, decrement the 
50125     ** transaction count of the shared btree. If the transaction count 
50126     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50127     ** call below will unlock the pager.  */
50128     if( p->inTrans!=TRANS_NONE ){
50129       clearAllSharedCacheTableLocks(p);
50130       pBt->nTransaction--;
50131       if( 0==pBt->nTransaction ){
50132         pBt->inTransaction = TRANS_NONE;
50133       }
50134     }
50135
50136     /* Set the current transaction state to TRANS_NONE and unlock the 
50137     ** pager if this call closed the only read or write transaction.  */
50138     p->inTrans = TRANS_NONE;
50139     unlockBtreeIfUnused(pBt);
50140   }
50141
50142   btreeIntegrity(p);
50143 }
50144
50145 /*
50146 ** Commit the transaction currently in progress.
50147 **
50148 ** This routine implements the second phase of a 2-phase commit.  The
50149 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50150 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
50151 ** routine did all the work of writing information out to disk and flushing the
50152 ** contents so that they are written onto the disk platter.  All this
50153 ** routine has to do is delete or truncate or zero the header in the
50154 ** the rollback journal (which causes the transaction to commit) and
50155 ** drop locks.
50156 **
50157 ** Normally, if an error occurs while the pager layer is attempting to 
50158 ** finalize the underlying journal file, this function returns an error and
50159 ** the upper layer will attempt a rollback. However, if the second argument
50160 ** is non-zero then this b-tree transaction is part of a multi-file 
50161 ** transaction. In this case, the transaction has already been committed 
50162 ** (by deleting a master journal file) and the caller will ignore this 
50163 ** functions return code. So, even if an error occurs in the pager layer,
50164 ** reset the b-tree objects internal state to indicate that the write
50165 ** transaction has been closed. This is quite safe, as the pager will have
50166 ** transitioned to the error state.
50167 **
50168 ** This will release the write lock on the database file.  If there
50169 ** are no active cursors, it also releases the read lock.
50170 */
50171 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50172
50173   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50174   sqlite3BtreeEnter(p);
50175   btreeIntegrity(p);
50176
50177   /* If the handle has a write-transaction open, commit the shared-btrees 
50178   ** transaction and set the shared state to TRANS_READ.
50179   */
50180   if( p->inTrans==TRANS_WRITE ){
50181     int rc;
50182     BtShared *pBt = p->pBt;
50183     assert( pBt->inTransaction==TRANS_WRITE );
50184     assert( pBt->nTransaction>0 );
50185     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50186     if( rc!=SQLITE_OK && bCleanup==0 ){
50187       sqlite3BtreeLeave(p);
50188       return rc;
50189     }
50190     pBt->inTransaction = TRANS_READ;
50191   }
50192
50193   btreeEndTransaction(p);
50194   sqlite3BtreeLeave(p);
50195   return SQLITE_OK;
50196 }
50197
50198 /*
50199 ** Do both phases of a commit.
50200 */
50201 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50202   int rc;
50203   sqlite3BtreeEnter(p);
50204   rc = sqlite3BtreeCommitPhaseOne(p, 0);
50205   if( rc==SQLITE_OK ){
50206     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50207   }
50208   sqlite3BtreeLeave(p);
50209   return rc;
50210 }
50211
50212 #ifndef NDEBUG
50213 /*
50214 ** Return the number of write-cursors open on this handle. This is for use
50215 ** in assert() expressions, so it is only compiled if NDEBUG is not
50216 ** defined.
50217 **
50218 ** For the purposes of this routine, a write-cursor is any cursor that
50219 ** is capable of writing to the databse.  That means the cursor was
50220 ** originally opened for writing and the cursor has not be disabled
50221 ** by having its state changed to CURSOR_FAULT.
50222 */
50223 static int countWriteCursors(BtShared *pBt){
50224   BtCursor *pCur;
50225   int r = 0;
50226   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50227     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
50228   }
50229   return r;
50230 }
50231 #endif
50232
50233 /*
50234 ** This routine sets the state to CURSOR_FAULT and the error
50235 ** code to errCode for every cursor on BtShared that pBtree
50236 ** references.
50237 **
50238 ** Every cursor is tripped, including cursors that belong
50239 ** to other database connections that happen to be sharing
50240 ** the cache with pBtree.
50241 **
50242 ** This routine gets called when a rollback occurs.
50243 ** All cursors using the same cache must be tripped
50244 ** to prevent them from trying to use the btree after
50245 ** the rollback.  The rollback may have deleted tables
50246 ** or moved root pages, so it is not sufficient to
50247 ** save the state of the cursor.  The cursor must be
50248 ** invalidated.
50249 */
50250 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50251   BtCursor *p;
50252   sqlite3BtreeEnter(pBtree);
50253   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50254     int i;
50255     sqlite3BtreeClearCursor(p);
50256     p->eState = CURSOR_FAULT;
50257     p->skipNext = errCode;
50258     for(i=0; i<=p->iPage; i++){
50259       releasePage(p->apPage[i]);
50260       p->apPage[i] = 0;
50261     }
50262   }
50263   sqlite3BtreeLeave(pBtree);
50264 }
50265
50266 /*
50267 ** Rollback the transaction in progress.  All cursors will be
50268 ** invalided by this operation.  Any attempt to use a cursor
50269 ** that was open at the beginning of this operation will result
50270 ** in an error.
50271 **
50272 ** This will release the write lock on the database file.  If there
50273 ** are no active cursors, it also releases the read lock.
50274 */
50275 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50276   int rc;
50277   BtShared *pBt = p->pBt;
50278   MemPage *pPage1;
50279
50280   sqlite3BtreeEnter(p);
50281   rc = saveAllCursors(pBt, 0, 0);
50282 #ifndef SQLITE_OMIT_SHARED_CACHE
50283   if( rc!=SQLITE_OK ){
50284     /* This is a horrible situation. An IO or malloc() error occurred whilst
50285     ** trying to save cursor positions. If this is an automatic rollback (as
50286     ** the result of a constraint, malloc() failure or IO error) then 
50287     ** the cache may be internally inconsistent (not contain valid trees) so
50288     ** we cannot simply return the error to the caller. Instead, abort 
50289     ** all queries that may be using any of the cursors that failed to save.
50290     */
50291     sqlite3BtreeTripAllCursors(p, rc);
50292   }
50293 #endif
50294   btreeIntegrity(p);
50295
50296   if( p->inTrans==TRANS_WRITE ){
50297     int rc2;
50298
50299     assert( TRANS_WRITE==pBt->inTransaction );
50300     rc2 = sqlite3PagerRollback(pBt->pPager);
50301     if( rc2!=SQLITE_OK ){
50302       rc = rc2;
50303     }
50304
50305     /* The rollback may have destroyed the pPage1->aData value.  So
50306     ** call btreeGetPage() on page 1 again to make
50307     ** sure pPage1->aData is set correctly. */
50308     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50309       int nPage = get4byte(28+(u8*)pPage1->aData);
50310       testcase( nPage==0 );
50311       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50312       testcase( pBt->nPage!=nPage );
50313       pBt->nPage = nPage;
50314       releasePage(pPage1);
50315     }
50316     assert( countWriteCursors(pBt)==0 );
50317     pBt->inTransaction = TRANS_READ;
50318   }
50319
50320   btreeEndTransaction(p);
50321   sqlite3BtreeLeave(p);
50322   return rc;
50323 }
50324
50325 /*
50326 ** Start a statement subtransaction. The subtransaction can can be rolled
50327 ** back independently of the main transaction. You must start a transaction 
50328 ** before starting a subtransaction. The subtransaction is ended automatically 
50329 ** if the main transaction commits or rolls back.
50330 **
50331 ** Statement subtransactions are used around individual SQL statements
50332 ** that are contained within a BEGIN...COMMIT block.  If a constraint
50333 ** error occurs within the statement, the effect of that one statement
50334 ** can be rolled back without having to rollback the entire transaction.
50335 **
50336 ** A statement sub-transaction is implemented as an anonymous savepoint. The
50337 ** value passed as the second parameter is the total number of savepoints,
50338 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50339 ** are no active savepoints and no other statement-transactions open,
50340 ** iStatement is 1. This anonymous savepoint can be released or rolled back
50341 ** using the sqlite3BtreeSavepoint() function.
50342 */
50343 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50344   int rc;
50345   BtShared *pBt = p->pBt;
50346   sqlite3BtreeEnter(p);
50347   assert( p->inTrans==TRANS_WRITE );
50348   assert( pBt->readOnly==0 );
50349   assert( iStatement>0 );
50350   assert( iStatement>p->db->nSavepoint );
50351   assert( pBt->inTransaction==TRANS_WRITE );
50352   /* At the pager level, a statement transaction is a savepoint with
50353   ** an index greater than all savepoints created explicitly using
50354   ** SQL statements. It is illegal to open, release or rollback any
50355   ** such savepoints while the statement transaction savepoint is active.
50356   */
50357   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50358   sqlite3BtreeLeave(p);
50359   return rc;
50360 }
50361
50362 /*
50363 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50364 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50365 ** savepoint identified by parameter iSavepoint, depending on the value 
50366 ** of op.
50367 **
50368 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
50369 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
50370 ** contents of the entire transaction are rolled back. This is different
50371 ** from a normal transaction rollback, as no locks are released and the
50372 ** transaction remains open.
50373 */
50374 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50375   int rc = SQLITE_OK;
50376   if( p && p->inTrans==TRANS_WRITE ){
50377     BtShared *pBt = p->pBt;
50378     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50379     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50380     sqlite3BtreeEnter(p);
50381     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50382     if( rc==SQLITE_OK ){
50383       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50384       rc = newDatabase(pBt);
50385       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50386
50387       /* The database size was written into the offset 28 of the header
50388       ** when the transaction started, so we know that the value at offset
50389       ** 28 is nonzero. */
50390       assert( pBt->nPage>0 );
50391     }
50392     sqlite3BtreeLeave(p);
50393   }
50394   return rc;
50395 }
50396
50397 /*
50398 ** Create a new cursor for the BTree whose root is on the page
50399 ** iTable. If a read-only cursor is requested, it is assumed that
50400 ** the caller already has at least a read-only transaction open
50401 ** on the database already. If a write-cursor is requested, then
50402 ** the caller is assumed to have an open write transaction.
50403 **
50404 ** If wrFlag==0, then the cursor can only be used for reading.
50405 ** If wrFlag==1, then the cursor can be used for reading or for
50406 ** writing if other conditions for writing are also met.  These
50407 ** are the conditions that must be met in order for writing to
50408 ** be allowed:
50409 **
50410 ** 1:  The cursor must have been opened with wrFlag==1
50411 **
50412 ** 2:  Other database connections that share the same pager cache
50413 **     but which are not in the READ_UNCOMMITTED state may not have
50414 **     cursors open with wrFlag==0 on the same table.  Otherwise
50415 **     the changes made by this write cursor would be visible to
50416 **     the read cursors in the other database connection.
50417 **
50418 ** 3:  The database must be writable (not on read-only media)
50419 **
50420 ** 4:  There must be an active transaction.
50421 **
50422 ** No checking is done to make sure that page iTable really is the
50423 ** root page of a b-tree.  If it is not, then the cursor acquired
50424 ** will not work correctly.
50425 **
50426 ** It is assumed that the sqlite3BtreeCursorZero() has been called
50427 ** on pCur to initialize the memory space prior to invoking this routine.
50428 */
50429 static int btreeCursor(
50430   Btree *p,                              /* The btree */
50431   int iTable,                            /* Root page of table to open */
50432   int wrFlag,                            /* 1 to write. 0 read-only */
50433   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
50434   BtCursor *pCur                         /* Space for new cursor */
50435 ){
50436   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
50437
50438   assert( sqlite3BtreeHoldsMutex(p) );
50439   assert( wrFlag==0 || wrFlag==1 );
50440
50441   /* The following assert statements verify that if this is a sharable 
50442   ** b-tree database, the connection is holding the required table locks, 
50443   ** and that no other connection has any open cursor that conflicts with 
50444   ** this lock.  */
50445   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50446   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50447
50448   /* Assert that the caller has opened the required transaction. */
50449   assert( p->inTrans>TRANS_NONE );
50450   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50451   assert( pBt->pPage1 && pBt->pPage1->aData );
50452
50453   if( NEVER(wrFlag && pBt->readOnly) ){
50454     return SQLITE_READONLY;
50455   }
50456   if( iTable==1 && btreePagecount(pBt)==0 ){
50457     return SQLITE_EMPTY;
50458   }
50459
50460   /* Now that no other errors can occur, finish filling in the BtCursor
50461   ** variables and link the cursor into the BtShared list.  */
50462   pCur->pgnoRoot = (Pgno)iTable;
50463   pCur->iPage = -1;
50464   pCur->pKeyInfo = pKeyInfo;
50465   pCur->pBtree = p;
50466   pCur->pBt = pBt;
50467   pCur->wrFlag = (u8)wrFlag;
50468   pCur->pNext = pBt->pCursor;
50469   if( pCur->pNext ){
50470     pCur->pNext->pPrev = pCur;
50471   }
50472   pBt->pCursor = pCur;
50473   pCur->eState = CURSOR_INVALID;
50474   pCur->cachedRowid = 0;
50475   return SQLITE_OK;
50476 }
50477 SQLITE_PRIVATE int sqlite3BtreeCursor(
50478   Btree *p,                                   /* The btree */
50479   int iTable,                                 /* Root page of table to open */
50480   int wrFlag,                                 /* 1 to write. 0 read-only */
50481   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
50482   BtCursor *pCur                              /* Write new cursor here */
50483 ){
50484   int rc;
50485   sqlite3BtreeEnter(p);
50486   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
50487   sqlite3BtreeLeave(p);
50488   return rc;
50489 }
50490
50491 /*
50492 ** Return the size of a BtCursor object in bytes.
50493 **
50494 ** This interfaces is needed so that users of cursors can preallocate
50495 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
50496 ** to users so they cannot do the sizeof() themselves - they must call
50497 ** this routine.
50498 */
50499 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
50500   return ROUND8(sizeof(BtCursor));
50501 }
50502
50503 /*
50504 ** Initialize memory that will be converted into a BtCursor object.
50505 **
50506 ** The simple approach here would be to memset() the entire object
50507 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
50508 ** do not need to be zeroed and they are large, so we can save a lot
50509 ** of run-time by skipping the initialization of those elements.
50510 */
50511 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
50512   memset(p, 0, offsetof(BtCursor, iPage));
50513 }
50514
50515 /*
50516 ** Set the cached rowid value of every cursor in the same database file
50517 ** as pCur and having the same root page number as pCur.  The value is
50518 ** set to iRowid.
50519 **
50520 ** Only positive rowid values are considered valid for this cache.
50521 ** The cache is initialized to zero, indicating an invalid cache.
50522 ** A btree will work fine with zero or negative rowids.  We just cannot
50523 ** cache zero or negative rowids, which means tables that use zero or
50524 ** negative rowids might run a little slower.  But in practice, zero
50525 ** or negative rowids are very uncommon so this should not be a problem.
50526 */
50527 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
50528   BtCursor *p;
50529   for(p=pCur->pBt->pCursor; p; p=p->pNext){
50530     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
50531   }
50532   assert( pCur->cachedRowid==iRowid );
50533 }
50534
50535 /*
50536 ** Return the cached rowid for the given cursor.  A negative or zero
50537 ** return value indicates that the rowid cache is invalid and should be
50538 ** ignored.  If the rowid cache has never before been set, then a
50539 ** zero is returned.
50540 */
50541 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
50542   return pCur->cachedRowid;
50543 }
50544
50545 /*
50546 ** Close a cursor.  The read lock on the database file is released
50547 ** when the last cursor is closed.
50548 */
50549 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
50550   Btree *pBtree = pCur->pBtree;
50551   if( pBtree ){
50552     int i;
50553     BtShared *pBt = pCur->pBt;
50554     sqlite3BtreeEnter(pBtree);
50555     sqlite3BtreeClearCursor(pCur);
50556     if( pCur->pPrev ){
50557       pCur->pPrev->pNext = pCur->pNext;
50558     }else{
50559       pBt->pCursor = pCur->pNext;
50560     }
50561     if( pCur->pNext ){
50562       pCur->pNext->pPrev = pCur->pPrev;
50563     }
50564     for(i=0; i<=pCur->iPage; i++){
50565       releasePage(pCur->apPage[i]);
50566     }
50567     unlockBtreeIfUnused(pBt);
50568     invalidateOverflowCache(pCur);
50569     /* sqlite3_free(pCur); */
50570     sqlite3BtreeLeave(pBtree);
50571   }
50572   return SQLITE_OK;
50573 }
50574
50575 /*
50576 ** Make sure the BtCursor* given in the argument has a valid
50577 ** BtCursor.info structure.  If it is not already valid, call
50578 ** btreeParseCell() to fill it in.
50579 **
50580 ** BtCursor.info is a cache of the information in the current cell.
50581 ** Using this cache reduces the number of calls to btreeParseCell().
50582 **
50583 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
50584 ** compiler to crash when getCellInfo() is implemented as a macro.
50585 ** But there is a measureable speed advantage to using the macro on gcc
50586 ** (when less compiler optimizations like -Os or -O0 are used and the
50587 ** compiler is not doing agressive inlining.)  So we use a real function
50588 ** for MSVC and a macro for everything else.  Ticket #2457.
50589 */
50590 #ifndef NDEBUG
50591   static void assertCellInfo(BtCursor *pCur){
50592     CellInfo info;
50593     int iPage = pCur->iPage;
50594     memset(&info, 0, sizeof(info));
50595     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
50596     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
50597   }
50598 #else
50599   #define assertCellInfo(x)
50600 #endif
50601 #ifdef _MSC_VER
50602   /* Use a real function in MSVC to work around bugs in that compiler. */
50603   static void getCellInfo(BtCursor *pCur){
50604     if( pCur->info.nSize==0 ){
50605       int iPage = pCur->iPage;
50606       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
50607       pCur->validNKey = 1;
50608     }else{
50609       assertCellInfo(pCur);
50610     }
50611   }
50612 #else /* if not _MSC_VER */
50613   /* Use a macro in all other compilers so that the function is inlined */
50614 #define getCellInfo(pCur)                                                      \
50615   if( pCur->info.nSize==0 ){                                                   \
50616     int iPage = pCur->iPage;                                                   \
50617     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
50618     pCur->validNKey = 1;                                                       \
50619   }else{                                                                       \
50620     assertCellInfo(pCur);                                                      \
50621   }
50622 #endif /* _MSC_VER */
50623
50624 #ifndef NDEBUG  /* The next routine used only within assert() statements */
50625 /*
50626 ** Return true if the given BtCursor is valid.  A valid cursor is one
50627 ** that is currently pointing to a row in a (non-empty) table.
50628 ** This is a verification routine is used only within assert() statements.
50629 */
50630 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
50631   return pCur && pCur->eState==CURSOR_VALID;
50632 }
50633 #endif /* NDEBUG */
50634
50635 /*
50636 ** Set *pSize to the size of the buffer needed to hold the value of
50637 ** the key for the current entry.  If the cursor is not pointing
50638 ** to a valid entry, *pSize is set to 0. 
50639 **
50640 ** For a table with the INTKEY flag set, this routine returns the key
50641 ** itself, not the number of bytes in the key.
50642 **
50643 ** The caller must position the cursor prior to invoking this routine.
50644 ** 
50645 ** This routine cannot fail.  It always returns SQLITE_OK.  
50646 */
50647 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
50648   assert( cursorHoldsMutex(pCur) );
50649   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
50650   if( pCur->eState!=CURSOR_VALID ){
50651     *pSize = 0;
50652   }else{
50653     getCellInfo(pCur);
50654     *pSize = pCur->info.nKey;
50655   }
50656   return SQLITE_OK;
50657 }
50658
50659 /*
50660 ** Set *pSize to the number of bytes of data in the entry the
50661 ** cursor currently points to.
50662 **
50663 ** The caller must guarantee that the cursor is pointing to a non-NULL
50664 ** valid entry.  In other words, the calling procedure must guarantee
50665 ** that the cursor has Cursor.eState==CURSOR_VALID.
50666 **
50667 ** Failure is not possible.  This function always returns SQLITE_OK.
50668 ** It might just as well be a procedure (returning void) but we continue
50669 ** to return an integer result code for historical reasons.
50670 */
50671 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
50672   assert( cursorHoldsMutex(pCur) );
50673   assert( pCur->eState==CURSOR_VALID );
50674   getCellInfo(pCur);
50675   *pSize = pCur->info.nData;
50676   return SQLITE_OK;
50677 }
50678
50679 /*
50680 ** Given the page number of an overflow page in the database (parameter
50681 ** ovfl), this function finds the page number of the next page in the 
50682 ** linked list of overflow pages. If possible, it uses the auto-vacuum
50683 ** pointer-map data instead of reading the content of page ovfl to do so. 
50684 **
50685 ** If an error occurs an SQLite error code is returned. Otherwise:
50686 **
50687 ** The page number of the next overflow page in the linked list is 
50688 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
50689 ** list, *pPgnoNext is set to zero. 
50690 **
50691 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
50692 ** to page number pOvfl was obtained, then *ppPage is set to point to that
50693 ** reference. It is the responsibility of the caller to call releasePage()
50694 ** on *ppPage to free the reference. In no reference was obtained (because
50695 ** the pointer-map was used to obtain the value for *pPgnoNext), then
50696 ** *ppPage is set to zero.
50697 */
50698 static int getOverflowPage(
50699   BtShared *pBt,               /* The database file */
50700   Pgno ovfl,                   /* Current overflow page number */
50701   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
50702   Pgno *pPgnoNext              /* OUT: Next overflow page number */
50703 ){
50704   Pgno next = 0;
50705   MemPage *pPage = 0;
50706   int rc = SQLITE_OK;
50707
50708   assert( sqlite3_mutex_held(pBt->mutex) );
50709   assert(pPgnoNext);
50710
50711 #ifndef SQLITE_OMIT_AUTOVACUUM
50712   /* Try to find the next page in the overflow list using the
50713   ** autovacuum pointer-map pages. Guess that the next page in 
50714   ** the overflow list is page number (ovfl+1). If that guess turns 
50715   ** out to be wrong, fall back to loading the data of page 
50716   ** number ovfl to determine the next page number.
50717   */
50718   if( pBt->autoVacuum ){
50719     Pgno pgno;
50720     Pgno iGuess = ovfl+1;
50721     u8 eType;
50722
50723     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
50724       iGuess++;
50725     }
50726
50727     if( iGuess<=btreePagecount(pBt) ){
50728       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
50729       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
50730         next = iGuess;
50731         rc = SQLITE_DONE;
50732       }
50733     }
50734   }
50735 #endif
50736
50737   assert( next==0 || rc==SQLITE_DONE );
50738   if( rc==SQLITE_OK ){
50739     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
50740     assert( rc==SQLITE_OK || pPage==0 );
50741     if( rc==SQLITE_OK ){
50742       next = get4byte(pPage->aData);
50743     }
50744   }
50745
50746   *pPgnoNext = next;
50747   if( ppPage ){
50748     *ppPage = pPage;
50749   }else{
50750     releasePage(pPage);
50751   }
50752   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
50753 }
50754
50755 /*
50756 ** Copy data from a buffer to a page, or from a page to a buffer.
50757 **
50758 ** pPayload is a pointer to data stored on database page pDbPage.
50759 ** If argument eOp is false, then nByte bytes of data are copied
50760 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
50761 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
50762 ** of data are copied from the buffer pBuf to pPayload.
50763 **
50764 ** SQLITE_OK is returned on success, otherwise an error code.
50765 */
50766 static int copyPayload(
50767   void *pPayload,           /* Pointer to page data */
50768   void *pBuf,               /* Pointer to buffer */
50769   int nByte,                /* Number of bytes to copy */
50770   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
50771   DbPage *pDbPage           /* Page containing pPayload */
50772 ){
50773   if( eOp ){
50774     /* Copy data from buffer to page (a write operation) */
50775     int rc = sqlite3PagerWrite(pDbPage);
50776     if( rc!=SQLITE_OK ){
50777       return rc;
50778     }
50779     memcpy(pPayload, pBuf, nByte);
50780   }else{
50781     /* Copy data from page to buffer (a read operation) */
50782     memcpy(pBuf, pPayload, nByte);
50783   }
50784   return SQLITE_OK;
50785 }
50786
50787 /*
50788 ** This function is used to read or overwrite payload information
50789 ** for the entry that the pCur cursor is pointing to. If the eOp
50790 ** parameter is 0, this is a read operation (data copied into
50791 ** buffer pBuf). If it is non-zero, a write (data copied from
50792 ** buffer pBuf).
50793 **
50794 ** A total of "amt" bytes are read or written beginning at "offset".
50795 ** Data is read to or from the buffer pBuf.
50796 **
50797 ** The content being read or written might appear on the main page
50798 ** or be scattered out on multiple overflow pages.
50799 **
50800 ** If the BtCursor.isIncrblobHandle flag is set, and the current
50801 ** cursor entry uses one or more overflow pages, this function
50802 ** allocates space for and lazily popluates the overflow page-list 
50803 ** cache array (BtCursor.aOverflow). Subsequent calls use this
50804 ** cache to make seeking to the supplied offset more efficient.
50805 **
50806 ** Once an overflow page-list cache has been allocated, it may be
50807 ** invalidated if some other cursor writes to the same table, or if
50808 ** the cursor is moved to a different row. Additionally, in auto-vacuum
50809 ** mode, the following events may invalidate an overflow page-list cache.
50810 **
50811 **   * An incremental vacuum,
50812 **   * A commit in auto_vacuum="full" mode,
50813 **   * Creating a table (may require moving an overflow page).
50814 */
50815 static int accessPayload(
50816   BtCursor *pCur,      /* Cursor pointing to entry to read from */
50817   u32 offset,          /* Begin reading this far into payload */
50818   u32 amt,             /* Read this many bytes */
50819   unsigned char *pBuf, /* Write the bytes into this buffer */ 
50820   int eOp              /* zero to read. non-zero to write. */
50821 ){
50822   unsigned char *aPayload;
50823   int rc = SQLITE_OK;
50824   u32 nKey;
50825   int iIdx = 0;
50826   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
50827   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
50828
50829   assert( pPage );
50830   assert( pCur->eState==CURSOR_VALID );
50831   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
50832   assert( cursorHoldsMutex(pCur) );
50833
50834   getCellInfo(pCur);
50835   aPayload = pCur->info.pCell + pCur->info.nHeader;
50836   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
50837
50838   if( NEVER(offset+amt > nKey+pCur->info.nData) 
50839    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
50840   ){
50841     /* Trying to read or write past the end of the data is an error */
50842     return SQLITE_CORRUPT_BKPT;
50843   }
50844
50845   /* Check if data must be read/written to/from the btree page itself. */
50846   if( offset<pCur->info.nLocal ){
50847     int a = amt;
50848     if( a+offset>pCur->info.nLocal ){
50849       a = pCur->info.nLocal - offset;
50850     }
50851     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
50852     offset = 0;
50853     pBuf += a;
50854     amt -= a;
50855   }else{
50856     offset -= pCur->info.nLocal;
50857   }
50858
50859   if( rc==SQLITE_OK && amt>0 ){
50860     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
50861     Pgno nextPage;
50862
50863     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
50864
50865 #ifndef SQLITE_OMIT_INCRBLOB
50866     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
50867     ** has not been allocated, allocate it now. The array is sized at
50868     ** one entry for each overflow page in the overflow chain. The
50869     ** page number of the first overflow page is stored in aOverflow[0],
50870     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
50871     ** (the cache is lazily populated).
50872     */
50873     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
50874       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
50875       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
50876       /* nOvfl is always positive.  If it were zero, fetchPayload would have
50877       ** been used instead of this routine. */
50878       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
50879         rc = SQLITE_NOMEM;
50880       }
50881     }
50882
50883     /* If the overflow page-list cache has been allocated and the
50884     ** entry for the first required overflow page is valid, skip
50885     ** directly to it.
50886     */
50887     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
50888       iIdx = (offset/ovflSize);
50889       nextPage = pCur->aOverflow[iIdx];
50890       offset = (offset%ovflSize);
50891     }
50892 #endif
50893
50894     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
50895
50896 #ifndef SQLITE_OMIT_INCRBLOB
50897       /* If required, populate the overflow page-list cache. */
50898       if( pCur->aOverflow ){
50899         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
50900         pCur->aOverflow[iIdx] = nextPage;
50901       }
50902 #endif
50903
50904       if( offset>=ovflSize ){
50905         /* The only reason to read this page is to obtain the page
50906         ** number for the next page in the overflow chain. The page
50907         ** data is not required. So first try to lookup the overflow
50908         ** page-list cache, if any, then fall back to the getOverflowPage()
50909         ** function.
50910         */
50911 #ifndef SQLITE_OMIT_INCRBLOB
50912         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
50913           nextPage = pCur->aOverflow[iIdx+1];
50914         } else 
50915 #endif
50916           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
50917         offset -= ovflSize;
50918       }else{
50919         /* Need to read this page properly. It contains some of the
50920         ** range of data that is being read (eOp==0) or written (eOp!=0).
50921         */
50922         DbPage *pDbPage;
50923         int a = amt;
50924         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
50925         if( rc==SQLITE_OK ){
50926           aPayload = sqlite3PagerGetData(pDbPage);
50927           nextPage = get4byte(aPayload);
50928           if( a + offset > ovflSize ){
50929             a = ovflSize - offset;
50930           }
50931           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
50932           sqlite3PagerUnref(pDbPage);
50933           offset = 0;
50934           amt -= a;
50935           pBuf += a;
50936         }
50937       }
50938     }
50939   }
50940
50941   if( rc==SQLITE_OK && amt>0 ){
50942     return SQLITE_CORRUPT_BKPT;
50943   }
50944   return rc;
50945 }
50946
50947 /*
50948 ** Read part of the key associated with cursor pCur.  Exactly
50949 ** "amt" bytes will be transfered into pBuf[].  The transfer
50950 ** begins at "offset".
50951 **
50952 ** The caller must ensure that pCur is pointing to a valid row
50953 ** in the table.
50954 **
50955 ** Return SQLITE_OK on success or an error code if anything goes
50956 ** wrong.  An error is returned if "offset+amt" is larger than
50957 ** the available payload.
50958 */
50959 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
50960   assert( cursorHoldsMutex(pCur) );
50961   assert( pCur->eState==CURSOR_VALID );
50962   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
50963   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
50964   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
50965 }
50966
50967 /*
50968 ** Read part of the data associated with cursor pCur.  Exactly
50969 ** "amt" bytes will be transfered into pBuf[].  The transfer
50970 ** begins at "offset".
50971 **
50972 ** Return SQLITE_OK on success or an error code if anything goes
50973 ** wrong.  An error is returned if "offset+amt" is larger than
50974 ** the available payload.
50975 */
50976 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
50977   int rc;
50978
50979 #ifndef SQLITE_OMIT_INCRBLOB
50980   if ( pCur->eState==CURSOR_INVALID ){
50981     return SQLITE_ABORT;
50982   }
50983 #endif
50984
50985   assert( cursorHoldsMutex(pCur) );
50986   rc = restoreCursorPosition(pCur);
50987   if( rc==SQLITE_OK ){
50988     assert( pCur->eState==CURSOR_VALID );
50989     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
50990     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
50991     rc = accessPayload(pCur, offset, amt, pBuf, 0);
50992   }
50993   return rc;
50994 }
50995
50996 /*
50997 ** Return a pointer to payload information from the entry that the 
50998 ** pCur cursor is pointing to.  The pointer is to the beginning of
50999 ** the key if skipKey==0 and it points to the beginning of data if
51000 ** skipKey==1.  The number of bytes of available key/data is written
51001 ** into *pAmt.  If *pAmt==0, then the value returned will not be
51002 ** a valid pointer.
51003 **
51004 ** This routine is an optimization.  It is common for the entire key
51005 ** and data to fit on the local page and for there to be no overflow
51006 ** pages.  When that is so, this routine can be used to access the
51007 ** key and data without making a copy.  If the key and/or data spills
51008 ** onto overflow pages, then accessPayload() must be used to reassemble
51009 ** the key/data and copy it into a preallocated buffer.
51010 **
51011 ** The pointer returned by this routine looks directly into the cached
51012 ** page of the database.  The data might change or move the next time
51013 ** any btree routine is called.
51014 */
51015 static const unsigned char *fetchPayload(
51016   BtCursor *pCur,      /* Cursor pointing to entry to read from */
51017   int *pAmt,           /* Write the number of available bytes here */
51018   int skipKey          /* read beginning at data if this is true */
51019 ){
51020   unsigned char *aPayload;
51021   MemPage *pPage;
51022   u32 nKey;
51023   u32 nLocal;
51024
51025   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51026   assert( pCur->eState==CURSOR_VALID );
51027   assert( cursorHoldsMutex(pCur) );
51028   pPage = pCur->apPage[pCur->iPage];
51029   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51030   if( NEVER(pCur->info.nSize==0) ){
51031     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51032                    &pCur->info);
51033   }
51034   aPayload = pCur->info.pCell;
51035   aPayload += pCur->info.nHeader;
51036   if( pPage->intKey ){
51037     nKey = 0;
51038   }else{
51039     nKey = (int)pCur->info.nKey;
51040   }
51041   if( skipKey ){
51042     aPayload += nKey;
51043     nLocal = pCur->info.nLocal - nKey;
51044   }else{
51045     nLocal = pCur->info.nLocal;
51046     assert( nLocal<=nKey );
51047   }
51048   *pAmt = nLocal;
51049   return aPayload;
51050 }
51051
51052
51053 /*
51054 ** For the entry that cursor pCur is point to, return as
51055 ** many bytes of the key or data as are available on the local
51056 ** b-tree page.  Write the number of available bytes into *pAmt.
51057 **
51058 ** The pointer returned is ephemeral.  The key/data may move
51059 ** or be destroyed on the next call to any Btree routine,
51060 ** including calls from other threads against the same cache.
51061 ** Hence, a mutex on the BtShared should be held prior to calling
51062 ** this routine.
51063 **
51064 ** These routines is used to get quick access to key and data
51065 ** in the common case where no overflow pages are used.
51066 */
51067 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51068   const void *p = 0;
51069   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51070   assert( cursorHoldsMutex(pCur) );
51071   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51072     p = (const void*)fetchPayload(pCur, pAmt, 0);
51073   }
51074   return p;
51075 }
51076 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51077   const void *p = 0;
51078   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51079   assert( cursorHoldsMutex(pCur) );
51080   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51081     p = (const void*)fetchPayload(pCur, pAmt, 1);
51082   }
51083   return p;
51084 }
51085
51086
51087 /*
51088 ** Move the cursor down to a new child page.  The newPgno argument is the
51089 ** page number of the child page to move to.
51090 **
51091 ** This function returns SQLITE_CORRUPT if the page-header flags field of
51092 ** the new child page does not match the flags field of the parent (i.e.
51093 ** if an intkey page appears to be the parent of a non-intkey page, or
51094 ** vice-versa).
51095 */
51096 static int moveToChild(BtCursor *pCur, u32 newPgno){
51097   int rc;
51098   int i = pCur->iPage;
51099   MemPage *pNewPage;
51100   BtShared *pBt = pCur->pBt;
51101
51102   assert( cursorHoldsMutex(pCur) );
51103   assert( pCur->eState==CURSOR_VALID );
51104   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51105   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51106     return SQLITE_CORRUPT_BKPT;
51107   }
51108   rc = getAndInitPage(pBt, newPgno, &pNewPage);
51109   if( rc ) return rc;
51110   pCur->apPage[i+1] = pNewPage;
51111   pCur->aiIdx[i+1] = 0;
51112   pCur->iPage++;
51113
51114   pCur->info.nSize = 0;
51115   pCur->validNKey = 0;
51116   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51117     return SQLITE_CORRUPT_BKPT;
51118   }
51119   return SQLITE_OK;
51120 }
51121
51122 #ifndef NDEBUG
51123 /*
51124 ** Page pParent is an internal (non-leaf) tree page. This function 
51125 ** asserts that page number iChild is the left-child if the iIdx'th
51126 ** cell in page pParent. Or, if iIdx is equal to the total number of
51127 ** cells in pParent, that page number iChild is the right-child of
51128 ** the page.
51129 */
51130 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51131   assert( iIdx<=pParent->nCell );
51132   if( iIdx==pParent->nCell ){
51133     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51134   }else{
51135     assert( get4byte(findCell(pParent, iIdx))==iChild );
51136   }
51137 }
51138 #else
51139 #  define assertParentIndex(x,y,z) 
51140 #endif
51141
51142 /*
51143 ** Move the cursor up to the parent page.
51144 **
51145 ** pCur->idx is set to the cell index that contains the pointer
51146 ** to the page we are coming from.  If we are coming from the
51147 ** right-most child page then pCur->idx is set to one more than
51148 ** the largest cell index.
51149 */
51150 static void moveToParent(BtCursor *pCur){
51151   assert( cursorHoldsMutex(pCur) );
51152   assert( pCur->eState==CURSOR_VALID );
51153   assert( pCur->iPage>0 );
51154   assert( pCur->apPage[pCur->iPage] );
51155   assertParentIndex(
51156     pCur->apPage[pCur->iPage-1], 
51157     pCur->aiIdx[pCur->iPage-1], 
51158     pCur->apPage[pCur->iPage]->pgno
51159   );
51160   releasePage(pCur->apPage[pCur->iPage]);
51161   pCur->iPage--;
51162   pCur->info.nSize = 0;
51163   pCur->validNKey = 0;
51164 }
51165
51166 /*
51167 ** Move the cursor to point to the root page of its b-tree structure.
51168 **
51169 ** If the table has a virtual root page, then the cursor is moved to point
51170 ** to the virtual root page instead of the actual root page. A table has a
51171 ** virtual root page when the actual root page contains no cells and a 
51172 ** single child page. This can only happen with the table rooted at page 1.
51173 **
51174 ** If the b-tree structure is empty, the cursor state is set to 
51175 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51176 ** cell located on the root (or virtual root) page and the cursor state
51177 ** is set to CURSOR_VALID.
51178 **
51179 ** If this function returns successfully, it may be assumed that the
51180 ** page-header flags indicate that the [virtual] root-page is the expected 
51181 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
51182 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51183 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
51184 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51185 ** b-tree).
51186 */
51187 static int moveToRoot(BtCursor *pCur){
51188   MemPage *pRoot;
51189   int rc = SQLITE_OK;
51190   Btree *p = pCur->pBtree;
51191   BtShared *pBt = p->pBt;
51192
51193   assert( cursorHoldsMutex(pCur) );
51194   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51195   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
51196   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
51197   if( pCur->eState>=CURSOR_REQUIRESEEK ){
51198     if( pCur->eState==CURSOR_FAULT ){
51199       assert( pCur->skipNext!=SQLITE_OK );
51200       return pCur->skipNext;
51201     }
51202     sqlite3BtreeClearCursor(pCur);
51203   }
51204
51205   if( pCur->iPage>=0 ){
51206     int i;
51207     for(i=1; i<=pCur->iPage; i++){
51208       releasePage(pCur->apPage[i]);
51209     }
51210     pCur->iPage = 0;
51211   }else{
51212     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51213     if( rc!=SQLITE_OK ){
51214       pCur->eState = CURSOR_INVALID;
51215       return rc;
51216     }
51217     pCur->iPage = 0;
51218
51219     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51220     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51221     ** NULL, the caller expects a table b-tree. If this is not the case,
51222     ** return an SQLITE_CORRUPT error.  */
51223     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51224     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51225       return SQLITE_CORRUPT_BKPT;
51226     }
51227   }
51228
51229   /* Assert that the root page is of the correct type. This must be the
51230   ** case as the call to this function that loaded the root-page (either
51231   ** this call or a previous invocation) would have detected corruption 
51232   ** if the assumption were not true, and it is not possible for the flags 
51233   ** byte to have been modified while this cursor is holding a reference
51234   ** to the page.  */
51235   pRoot = pCur->apPage[0];
51236   assert( pRoot->pgno==pCur->pgnoRoot );
51237   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51238
51239   pCur->aiIdx[0] = 0;
51240   pCur->info.nSize = 0;
51241   pCur->atLast = 0;
51242   pCur->validNKey = 0;
51243
51244   if( pRoot->nCell==0 && !pRoot->leaf ){
51245     Pgno subpage;
51246     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51247     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51248     pCur->eState = CURSOR_VALID;
51249     rc = moveToChild(pCur, subpage);
51250   }else{
51251     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51252   }
51253   return rc;
51254 }
51255
51256 /*
51257 ** Move the cursor down to the left-most leaf entry beneath the
51258 ** entry to which it is currently pointing.
51259 **
51260 ** The left-most leaf is the one with the smallest key - the first
51261 ** in ascending order.
51262 */
51263 static int moveToLeftmost(BtCursor *pCur){
51264   Pgno pgno;
51265   int rc = SQLITE_OK;
51266   MemPage *pPage;
51267
51268   assert( cursorHoldsMutex(pCur) );
51269   assert( pCur->eState==CURSOR_VALID );
51270   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51271     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51272     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51273     rc = moveToChild(pCur, pgno);
51274   }
51275   return rc;
51276 }
51277
51278 /*
51279 ** Move the cursor down to the right-most leaf entry beneath the
51280 ** page to which it is currently pointing.  Notice the difference
51281 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
51282 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51283 ** finds the right-most entry beneath the *page*.
51284 **
51285 ** The right-most entry is the one with the largest key - the last
51286 ** key in ascending order.
51287 */
51288 static int moveToRightmost(BtCursor *pCur){
51289   Pgno pgno;
51290   int rc = SQLITE_OK;
51291   MemPage *pPage = 0;
51292
51293   assert( cursorHoldsMutex(pCur) );
51294   assert( pCur->eState==CURSOR_VALID );
51295   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51296     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51297     pCur->aiIdx[pCur->iPage] = pPage->nCell;
51298     rc = moveToChild(pCur, pgno);
51299   }
51300   if( rc==SQLITE_OK ){
51301     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51302     pCur->info.nSize = 0;
51303     pCur->validNKey = 0;
51304   }
51305   return rc;
51306 }
51307
51308 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
51309 ** on success.  Set *pRes to 0 if the cursor actually points to something
51310 ** or set *pRes to 1 if the table is empty.
51311 */
51312 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51313   int rc;
51314
51315   assert( cursorHoldsMutex(pCur) );
51316   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51317   rc = moveToRoot(pCur);
51318   if( rc==SQLITE_OK ){
51319     if( pCur->eState==CURSOR_INVALID ){
51320       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51321       *pRes = 1;
51322     }else{
51323       assert( pCur->apPage[pCur->iPage]->nCell>0 );
51324       *pRes = 0;
51325       rc = moveToLeftmost(pCur);
51326     }
51327   }
51328   return rc;
51329 }
51330
51331 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
51332 ** on success.  Set *pRes to 0 if the cursor actually points to something
51333 ** or set *pRes to 1 if the table is empty.
51334 */
51335 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51336   int rc;
51337  
51338   assert( cursorHoldsMutex(pCur) );
51339   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51340
51341   /* If the cursor already points to the last entry, this is a no-op. */
51342   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51343 #ifdef SQLITE_DEBUG
51344     /* This block serves to assert() that the cursor really does point 
51345     ** to the last entry in the b-tree. */
51346     int ii;
51347     for(ii=0; ii<pCur->iPage; ii++){
51348       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51349     }
51350     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51351     assert( pCur->apPage[pCur->iPage]->leaf );
51352 #endif
51353     return SQLITE_OK;
51354   }
51355
51356   rc = moveToRoot(pCur);
51357   if( rc==SQLITE_OK ){
51358     if( CURSOR_INVALID==pCur->eState ){
51359       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51360       *pRes = 1;
51361     }else{
51362       assert( pCur->eState==CURSOR_VALID );
51363       *pRes = 0;
51364       rc = moveToRightmost(pCur);
51365       pCur->atLast = rc==SQLITE_OK ?1:0;
51366     }
51367   }
51368   return rc;
51369 }
51370
51371 /* Move the cursor so that it points to an entry near the key 
51372 ** specified by pIdxKey or intKey.   Return a success code.
51373 **
51374 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
51375 ** must be NULL.  For index tables, pIdxKey is used and intKey
51376 ** is ignored.
51377 **
51378 ** If an exact match is not found, then the cursor is always
51379 ** left pointing at a leaf page which would hold the entry if it
51380 ** were present.  The cursor might point to an entry that comes
51381 ** before or after the key.
51382 **
51383 ** An integer is written into *pRes which is the result of
51384 ** comparing the key with the entry to which the cursor is 
51385 ** pointing.  The meaning of the integer written into
51386 ** *pRes is as follows:
51387 **
51388 **     *pRes<0      The cursor is left pointing at an entry that
51389 **                  is smaller than intKey/pIdxKey or if the table is empty
51390 **                  and the cursor is therefore left point to nothing.
51391 **
51392 **     *pRes==0     The cursor is left pointing at an entry that
51393 **                  exactly matches intKey/pIdxKey.
51394 **
51395 **     *pRes>0      The cursor is left pointing at an entry that
51396 **                  is larger than intKey/pIdxKey.
51397 **
51398 */
51399 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51400   BtCursor *pCur,          /* The cursor to be moved */
51401   UnpackedRecord *pIdxKey, /* Unpacked index key */
51402   i64 intKey,              /* The table key */
51403   int biasRight,           /* If true, bias the search to the high end */
51404   int *pRes                /* Write search results here */
51405 ){
51406   int rc;
51407
51408   assert( cursorHoldsMutex(pCur) );
51409   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51410   assert( pRes );
51411   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51412
51413   /* If the cursor is already positioned at the point we are trying
51414   ** to move to, then just return without doing any work */
51415   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
51416    && pCur->apPage[0]->intKey 
51417   ){
51418     if( pCur->info.nKey==intKey ){
51419       *pRes = 0;
51420       return SQLITE_OK;
51421     }
51422     if( pCur->atLast && pCur->info.nKey<intKey ){
51423       *pRes = -1;
51424       return SQLITE_OK;
51425     }
51426   }
51427
51428   rc = moveToRoot(pCur);
51429   if( rc ){
51430     return rc;
51431   }
51432   assert( pCur->apPage[pCur->iPage] );
51433   assert( pCur->apPage[pCur->iPage]->isInit );
51434   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51435   if( pCur->eState==CURSOR_INVALID ){
51436     *pRes = -1;
51437     assert( pCur->apPage[pCur->iPage]->nCell==0 );
51438     return SQLITE_OK;
51439   }
51440   assert( pCur->apPage[0]->intKey || pIdxKey );
51441   for(;;){
51442     int lwr, upr;
51443     Pgno chldPg;
51444     MemPage *pPage = pCur->apPage[pCur->iPage];
51445     int c;
51446
51447     /* pPage->nCell must be greater than zero. If this is the root-page
51448     ** the cursor would have been INVALID above and this for(;;) loop
51449     ** not run. If this is not the root-page, then the moveToChild() routine
51450     ** would have already detected db corruption. Similarly, pPage must
51451     ** be the right kind (index or table) of b-tree page. Otherwise
51452     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
51453     assert( pPage->nCell>0 );
51454     assert( pPage->intKey==(pIdxKey==0) );
51455     lwr = 0;
51456     upr = pPage->nCell-1;
51457     if( biasRight ){
51458       pCur->aiIdx[pCur->iPage] = (u16)upr;
51459     }else{
51460       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
51461     }
51462     for(;;){
51463       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
51464       u8 *pCell;                          /* Pointer to current cell in pPage */
51465
51466       pCur->info.nSize = 0;
51467       pCell = findCell(pPage, idx) + pPage->childPtrSize;
51468       if( pPage->intKey ){
51469         i64 nCellKey;
51470         if( pPage->hasData ){
51471           u32 dummy;
51472           pCell += getVarint32(pCell, dummy);
51473         }
51474         getVarint(pCell, (u64*)&nCellKey);
51475         if( nCellKey==intKey ){
51476           c = 0;
51477         }else if( nCellKey<intKey ){
51478           c = -1;
51479         }else{
51480           assert( nCellKey>intKey );
51481           c = +1;
51482         }
51483         pCur->validNKey = 1;
51484         pCur->info.nKey = nCellKey;
51485       }else{
51486         /* The maximum supported page-size is 65536 bytes. This means that
51487         ** the maximum number of record bytes stored on an index B-Tree
51488         ** page is less than 16384 bytes and may be stored as a 2-byte
51489         ** varint. This information is used to attempt to avoid parsing 
51490         ** the entire cell by checking for the cases where the record is 
51491         ** stored entirely within the b-tree page by inspecting the first 
51492         ** 2 bytes of the cell.
51493         */
51494         int nCell = pCell[0];
51495         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
51496           /* This branch runs if the record-size field of the cell is a
51497           ** single byte varint and the record fits entirely on the main
51498           ** b-tree page.  */
51499           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
51500         }else if( !(pCell[1] & 0x80) 
51501           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
51502         ){
51503           /* The record-size field is a 2 byte varint and the record 
51504           ** fits entirely on the main b-tree page.  */
51505           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
51506         }else{
51507           /* The record flows over onto one or more overflow pages. In
51508           ** this case the whole cell needs to be parsed, a buffer allocated
51509           ** and accessPayload() used to retrieve the record into the
51510           ** buffer before VdbeRecordCompare() can be called. */
51511           void *pCellKey;
51512           u8 * const pCellBody = pCell - pPage->childPtrSize;
51513           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
51514           nCell = (int)pCur->info.nKey;
51515           pCellKey = sqlite3Malloc( nCell );
51516           if( pCellKey==0 ){
51517             rc = SQLITE_NOMEM;
51518             goto moveto_finish;
51519           }
51520           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
51521           if( rc ){
51522             sqlite3_free(pCellKey);
51523             goto moveto_finish;
51524           }
51525           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
51526           sqlite3_free(pCellKey);
51527         }
51528       }
51529       if( c==0 ){
51530         if( pPage->intKey && !pPage->leaf ){
51531           lwr = idx;
51532           upr = lwr - 1;
51533           break;
51534         }else{
51535           *pRes = 0;
51536           rc = SQLITE_OK;
51537           goto moveto_finish;
51538         }
51539       }
51540       if( c<0 ){
51541         lwr = idx+1;
51542       }else{
51543         upr = idx-1;
51544       }
51545       if( lwr>upr ){
51546         break;
51547       }
51548       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
51549     }
51550     assert( lwr==upr+1 );
51551     assert( pPage->isInit );
51552     if( pPage->leaf ){
51553       chldPg = 0;
51554     }else if( lwr>=pPage->nCell ){
51555       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51556     }else{
51557       chldPg = get4byte(findCell(pPage, lwr));
51558     }
51559     if( chldPg==0 ){
51560       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51561       *pRes = c;
51562       rc = SQLITE_OK;
51563       goto moveto_finish;
51564     }
51565     pCur->aiIdx[pCur->iPage] = (u16)lwr;
51566     pCur->info.nSize = 0;
51567     pCur->validNKey = 0;
51568     rc = moveToChild(pCur, chldPg);
51569     if( rc ) goto moveto_finish;
51570   }
51571 moveto_finish:
51572   return rc;
51573 }
51574
51575
51576 /*
51577 ** Return TRUE if the cursor is not pointing at an entry of the table.
51578 **
51579 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
51580 ** past the last entry in the table or sqlite3BtreePrev() moves past
51581 ** the first entry.  TRUE is also returned if the table is empty.
51582 */
51583 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
51584   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
51585   ** have been deleted? This API will need to change to return an error code
51586   ** as well as the boolean result value.
51587   */
51588   return (CURSOR_VALID!=pCur->eState);
51589 }
51590
51591 /*
51592 ** Advance the cursor to the next entry in the database.  If
51593 ** successful then set *pRes=0.  If the cursor
51594 ** was already pointing to the last entry in the database before
51595 ** this routine was called, then set *pRes=1.
51596 */
51597 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
51598   int rc;
51599   int idx;
51600   MemPage *pPage;
51601
51602   assert( cursorHoldsMutex(pCur) );
51603   rc = restoreCursorPosition(pCur);
51604   if( rc!=SQLITE_OK ){
51605     return rc;
51606   }
51607   assert( pRes!=0 );
51608   if( CURSOR_INVALID==pCur->eState ){
51609     *pRes = 1;
51610     return SQLITE_OK;
51611   }
51612   if( pCur->skipNext>0 ){
51613     pCur->skipNext = 0;
51614     *pRes = 0;
51615     return SQLITE_OK;
51616   }
51617   pCur->skipNext = 0;
51618
51619   pPage = pCur->apPage[pCur->iPage];
51620   idx = ++pCur->aiIdx[pCur->iPage];
51621   assert( pPage->isInit );
51622   assert( idx<=pPage->nCell );
51623
51624   pCur->info.nSize = 0;
51625   pCur->validNKey = 0;
51626   if( idx>=pPage->nCell ){
51627     if( !pPage->leaf ){
51628       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51629       if( rc ) return rc;
51630       rc = moveToLeftmost(pCur);
51631       *pRes = 0;
51632       return rc;
51633     }
51634     do{
51635       if( pCur->iPage==0 ){
51636         *pRes = 1;
51637         pCur->eState = CURSOR_INVALID;
51638         return SQLITE_OK;
51639       }
51640       moveToParent(pCur);
51641       pPage = pCur->apPage[pCur->iPage];
51642     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
51643     *pRes = 0;
51644     if( pPage->intKey ){
51645       rc = sqlite3BtreeNext(pCur, pRes);
51646     }else{
51647       rc = SQLITE_OK;
51648     }
51649     return rc;
51650   }
51651   *pRes = 0;
51652   if( pPage->leaf ){
51653     return SQLITE_OK;
51654   }
51655   rc = moveToLeftmost(pCur);
51656   return rc;
51657 }
51658
51659
51660 /*
51661 ** Step the cursor to the back to the previous entry in the database.  If
51662 ** successful then set *pRes=0.  If the cursor
51663 ** was already pointing to the first entry in the database before
51664 ** this routine was called, then set *pRes=1.
51665 */
51666 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
51667   int rc;
51668   MemPage *pPage;
51669
51670   assert( cursorHoldsMutex(pCur) );
51671   rc = restoreCursorPosition(pCur);
51672   if( rc!=SQLITE_OK ){
51673     return rc;
51674   }
51675   pCur->atLast = 0;
51676   if( CURSOR_INVALID==pCur->eState ){
51677     *pRes = 1;
51678     return SQLITE_OK;
51679   }
51680   if( pCur->skipNext<0 ){
51681     pCur->skipNext = 0;
51682     *pRes = 0;
51683     return SQLITE_OK;
51684   }
51685   pCur->skipNext = 0;
51686
51687   pPage = pCur->apPage[pCur->iPage];
51688   assert( pPage->isInit );
51689   if( !pPage->leaf ){
51690     int idx = pCur->aiIdx[pCur->iPage];
51691     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
51692     if( rc ){
51693       return rc;
51694     }
51695     rc = moveToRightmost(pCur);
51696   }else{
51697     while( pCur->aiIdx[pCur->iPage]==0 ){
51698       if( pCur->iPage==0 ){
51699         pCur->eState = CURSOR_INVALID;
51700         *pRes = 1;
51701         return SQLITE_OK;
51702       }
51703       moveToParent(pCur);
51704     }
51705     pCur->info.nSize = 0;
51706     pCur->validNKey = 0;
51707
51708     pCur->aiIdx[pCur->iPage]--;
51709     pPage = pCur->apPage[pCur->iPage];
51710     if( pPage->intKey && !pPage->leaf ){
51711       rc = sqlite3BtreePrevious(pCur, pRes);
51712     }else{
51713       rc = SQLITE_OK;
51714     }
51715   }
51716   *pRes = 0;
51717   return rc;
51718 }
51719
51720 /*
51721 ** Allocate a new page from the database file.
51722 **
51723 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
51724 ** has already been called on the new page.)  The new page has also
51725 ** been referenced and the calling routine is responsible for calling
51726 ** sqlite3PagerUnref() on the new page when it is done.
51727 **
51728 ** SQLITE_OK is returned on success.  Any other return value indicates
51729 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
51730 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
51731 **
51732 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
51733 ** locate a page close to the page number "nearby".  This can be used in an
51734 ** attempt to keep related pages close to each other in the database file,
51735 ** which in turn can make database access faster.
51736 **
51737 ** If the "exact" parameter is not 0, and the page-number nearby exists 
51738 ** anywhere on the free-list, then it is guarenteed to be returned. This
51739 ** is only used by auto-vacuum databases when allocating a new table.
51740 */
51741 static int allocateBtreePage(
51742   BtShared *pBt, 
51743   MemPage **ppPage, 
51744   Pgno *pPgno, 
51745   Pgno nearby,
51746   u8 exact
51747 ){
51748   MemPage *pPage1;
51749   int rc;
51750   u32 n;     /* Number of pages on the freelist */
51751   u32 k;     /* Number of leaves on the trunk of the freelist */
51752   MemPage *pTrunk = 0;
51753   MemPage *pPrevTrunk = 0;
51754   Pgno mxPage;     /* Total size of the database file */
51755
51756   assert( sqlite3_mutex_held(pBt->mutex) );
51757   pPage1 = pBt->pPage1;
51758   mxPage = btreePagecount(pBt);
51759   n = get4byte(&pPage1->aData[36]);
51760   testcase( n==mxPage-1 );
51761   if( n>=mxPage ){
51762     return SQLITE_CORRUPT_BKPT;
51763   }
51764   if( n>0 ){
51765     /* There are pages on the freelist.  Reuse one of those pages. */
51766     Pgno iTrunk;
51767     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
51768     
51769     /* If the 'exact' parameter was true and a query of the pointer-map
51770     ** shows that the page 'nearby' is somewhere on the free-list, then
51771     ** the entire-list will be searched for that page.
51772     */
51773 #ifndef SQLITE_OMIT_AUTOVACUUM
51774     if( exact && nearby<=mxPage ){
51775       u8 eType;
51776       assert( nearby>0 );
51777       assert( pBt->autoVacuum );
51778       rc = ptrmapGet(pBt, nearby, &eType, 0);
51779       if( rc ) return rc;
51780       if( eType==PTRMAP_FREEPAGE ){
51781         searchList = 1;
51782       }
51783       *pPgno = nearby;
51784     }
51785 #endif
51786
51787     /* Decrement the free-list count by 1. Set iTrunk to the index of the
51788     ** first free-list trunk page. iPrevTrunk is initially 1.
51789     */
51790     rc = sqlite3PagerWrite(pPage1->pDbPage);
51791     if( rc ) return rc;
51792     put4byte(&pPage1->aData[36], n-1);
51793
51794     /* The code within this loop is run only once if the 'searchList' variable
51795     ** is not true. Otherwise, it runs once for each trunk-page on the
51796     ** free-list until the page 'nearby' is located.
51797     */
51798     do {
51799       pPrevTrunk = pTrunk;
51800       if( pPrevTrunk ){
51801         iTrunk = get4byte(&pPrevTrunk->aData[0]);
51802       }else{
51803         iTrunk = get4byte(&pPage1->aData[32]);
51804       }
51805       testcase( iTrunk==mxPage );
51806       if( iTrunk>mxPage ){
51807         rc = SQLITE_CORRUPT_BKPT;
51808       }else{
51809         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
51810       }
51811       if( rc ){
51812         pTrunk = 0;
51813         goto end_allocate_page;
51814       }
51815
51816       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
51817       if( k==0 && !searchList ){
51818         /* The trunk has no leaves and the list is not being searched. 
51819         ** So extract the trunk page itself and use it as the newly 
51820         ** allocated page */
51821         assert( pPrevTrunk==0 );
51822         rc = sqlite3PagerWrite(pTrunk->pDbPage);
51823         if( rc ){
51824           goto end_allocate_page;
51825         }
51826         *pPgno = iTrunk;
51827         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51828         *ppPage = pTrunk;
51829         pTrunk = 0;
51830         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
51831       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
51832         /* Value of k is out of range.  Database corruption */
51833         rc = SQLITE_CORRUPT_BKPT;
51834         goto end_allocate_page;
51835 #ifndef SQLITE_OMIT_AUTOVACUUM
51836       }else if( searchList && nearby==iTrunk ){
51837         /* The list is being searched and this trunk page is the page
51838         ** to allocate, regardless of whether it has leaves.
51839         */
51840         assert( *pPgno==iTrunk );
51841         *ppPage = pTrunk;
51842         searchList = 0;
51843         rc = sqlite3PagerWrite(pTrunk->pDbPage);
51844         if( rc ){
51845           goto end_allocate_page;
51846         }
51847         if( k==0 ){
51848           if( !pPrevTrunk ){
51849             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
51850           }else{
51851             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
51852             if( rc!=SQLITE_OK ){
51853               goto end_allocate_page;
51854             }
51855             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
51856           }
51857         }else{
51858           /* The trunk page is required by the caller but it contains 
51859           ** pointers to free-list leaves. The first leaf becomes a trunk
51860           ** page in this case.
51861           */
51862           MemPage *pNewTrunk;
51863           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
51864           if( iNewTrunk>mxPage ){ 
51865             rc = SQLITE_CORRUPT_BKPT;
51866             goto end_allocate_page;
51867           }
51868           testcase( iNewTrunk==mxPage );
51869           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
51870           if( rc!=SQLITE_OK ){
51871             goto end_allocate_page;
51872           }
51873           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
51874           if( rc!=SQLITE_OK ){
51875             releasePage(pNewTrunk);
51876             goto end_allocate_page;
51877           }
51878           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
51879           put4byte(&pNewTrunk->aData[4], k-1);
51880           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
51881           releasePage(pNewTrunk);
51882           if( !pPrevTrunk ){
51883             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
51884             put4byte(&pPage1->aData[32], iNewTrunk);
51885           }else{
51886             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
51887             if( rc ){
51888               goto end_allocate_page;
51889             }
51890             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
51891           }
51892         }
51893         pTrunk = 0;
51894         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
51895 #endif
51896       }else if( k>0 ){
51897         /* Extract a leaf from the trunk */
51898         u32 closest;
51899         Pgno iPage;
51900         unsigned char *aData = pTrunk->aData;
51901         if( nearby>0 ){
51902           u32 i;
51903           int dist;
51904           closest = 0;
51905           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
51906           for(i=1; i<k; i++){
51907             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
51908             if( d2<dist ){
51909               closest = i;
51910               dist = d2;
51911             }
51912           }
51913         }else{
51914           closest = 0;
51915         }
51916
51917         iPage = get4byte(&aData[8+closest*4]);
51918         testcase( iPage==mxPage );
51919         if( iPage>mxPage ){
51920           rc = SQLITE_CORRUPT_BKPT;
51921           goto end_allocate_page;
51922         }
51923         testcase( iPage==mxPage );
51924         if( !searchList || iPage==nearby ){
51925           int noContent;
51926           *pPgno = iPage;
51927           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
51928                  ": %d more free pages\n",
51929                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
51930           rc = sqlite3PagerWrite(pTrunk->pDbPage);
51931           if( rc ) goto end_allocate_page;
51932           if( closest<k-1 ){
51933             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
51934           }
51935           put4byte(&aData[4], k-1);
51936           noContent = !btreeGetHasContent(pBt, *pPgno);
51937           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
51938           if( rc==SQLITE_OK ){
51939             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
51940             if( rc!=SQLITE_OK ){
51941               releasePage(*ppPage);
51942             }
51943           }
51944           searchList = 0;
51945         }
51946       }
51947       releasePage(pPrevTrunk);
51948       pPrevTrunk = 0;
51949     }while( searchList );
51950   }else{
51951     /* There are no pages on the freelist, so create a new page at the
51952     ** end of the file */
51953     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51954     if( rc ) return rc;
51955     pBt->nPage++;
51956     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
51957
51958 #ifndef SQLITE_OMIT_AUTOVACUUM
51959     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
51960       /* If *pPgno refers to a pointer-map page, allocate two new pages
51961       ** at the end of the file instead of one. The first allocated page
51962       ** becomes a new pointer-map page, the second is used by the caller.
51963       */
51964       MemPage *pPg = 0;
51965       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
51966       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
51967       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
51968       if( rc==SQLITE_OK ){
51969         rc = sqlite3PagerWrite(pPg->pDbPage);
51970         releasePage(pPg);
51971       }
51972       if( rc ) return rc;
51973       pBt->nPage++;
51974       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
51975     }
51976 #endif
51977     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
51978     *pPgno = pBt->nPage;
51979
51980     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
51981     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
51982     if( rc ) return rc;
51983     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
51984     if( rc!=SQLITE_OK ){
51985       releasePage(*ppPage);
51986     }
51987     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
51988   }
51989
51990   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
51991
51992 end_allocate_page:
51993   releasePage(pTrunk);
51994   releasePage(pPrevTrunk);
51995   if( rc==SQLITE_OK ){
51996     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
51997       releasePage(*ppPage);
51998       return SQLITE_CORRUPT_BKPT;
51999     }
52000     (*ppPage)->isInit = 0;
52001   }else{
52002     *ppPage = 0;
52003   }
52004   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
52005   return rc;
52006 }
52007
52008 /*
52009 ** This function is used to add page iPage to the database file free-list. 
52010 ** It is assumed that the page is not already a part of the free-list.
52011 **
52012 ** The value passed as the second argument to this function is optional.
52013 ** If the caller happens to have a pointer to the MemPage object 
52014 ** corresponding to page iPage handy, it may pass it as the second value. 
52015 ** Otherwise, it may pass NULL.
52016 **
52017 ** If a pointer to a MemPage object is passed as the second argument,
52018 ** its reference count is not altered by this function.
52019 */
52020 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52021   MemPage *pTrunk = 0;                /* Free-list trunk page */
52022   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
52023   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
52024   MemPage *pPage;                     /* Page being freed. May be NULL. */
52025   int rc;                             /* Return Code */
52026   int nFree;                          /* Initial number of pages on free-list */
52027
52028   assert( sqlite3_mutex_held(pBt->mutex) );
52029   assert( iPage>1 );
52030   assert( !pMemPage || pMemPage->pgno==iPage );
52031
52032   if( pMemPage ){
52033     pPage = pMemPage;
52034     sqlite3PagerRef(pPage->pDbPage);
52035   }else{
52036     pPage = btreePageLookup(pBt, iPage);
52037   }
52038
52039   /* Increment the free page count on pPage1 */
52040   rc = sqlite3PagerWrite(pPage1->pDbPage);
52041   if( rc ) goto freepage_out;
52042   nFree = get4byte(&pPage1->aData[36]);
52043   put4byte(&pPage1->aData[36], nFree+1);
52044
52045   if( pBt->secureDelete ){
52046     /* If the secure_delete option is enabled, then
52047     ** always fully overwrite deleted information with zeros.
52048     */
52049     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52050      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52051     ){
52052       goto freepage_out;
52053     }
52054     memset(pPage->aData, 0, pPage->pBt->pageSize);
52055   }
52056
52057   /* If the database supports auto-vacuum, write an entry in the pointer-map
52058   ** to indicate that the page is free.
52059   */
52060   if( ISAUTOVACUUM ){
52061     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52062     if( rc ) goto freepage_out;
52063   }
52064
52065   /* Now manipulate the actual database free-list structure. There are two
52066   ** possibilities. If the free-list is currently empty, or if the first
52067   ** trunk page in the free-list is full, then this page will become a
52068   ** new free-list trunk page. Otherwise, it will become a leaf of the
52069   ** first trunk page in the current free-list. This block tests if it
52070   ** is possible to add the page as a new free-list leaf.
52071   */
52072   if( nFree!=0 ){
52073     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
52074
52075     iTrunk = get4byte(&pPage1->aData[32]);
52076     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52077     if( rc!=SQLITE_OK ){
52078       goto freepage_out;
52079     }
52080
52081     nLeaf = get4byte(&pTrunk->aData[4]);
52082     assert( pBt->usableSize>32 );
52083     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52084       rc = SQLITE_CORRUPT_BKPT;
52085       goto freepage_out;
52086     }
52087     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52088       /* In this case there is room on the trunk page to insert the page
52089       ** being freed as a new leaf.
52090       **
52091       ** Note that the trunk page is not really full until it contains
52092       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52093       ** coded.  But due to a coding error in versions of SQLite prior to
52094       ** 3.6.0, databases with freelist trunk pages holding more than
52095       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
52096       ** to maintain backwards compatibility with older versions of SQLite,
52097       ** we will continue to restrict the number of entries to usableSize/4 - 8
52098       ** for now.  At some point in the future (once everyone has upgraded
52099       ** to 3.6.0 or later) we should consider fixing the conditional above
52100       ** to read "usableSize/4-2" instead of "usableSize/4-8".
52101       */
52102       rc = sqlite3PagerWrite(pTrunk->pDbPage);
52103       if( rc==SQLITE_OK ){
52104         put4byte(&pTrunk->aData[4], nLeaf+1);
52105         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52106         if( pPage && !pBt->secureDelete ){
52107           sqlite3PagerDontWrite(pPage->pDbPage);
52108         }
52109         rc = btreeSetHasContent(pBt, iPage);
52110       }
52111       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52112       goto freepage_out;
52113     }
52114   }
52115
52116   /* If control flows to this point, then it was not possible to add the
52117   ** the page being freed as a leaf page of the first trunk in the free-list.
52118   ** Possibly because the free-list is empty, or possibly because the 
52119   ** first trunk in the free-list is full. Either way, the page being freed
52120   ** will become the new first trunk page in the free-list.
52121   */
52122   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52123     goto freepage_out;
52124   }
52125   rc = sqlite3PagerWrite(pPage->pDbPage);
52126   if( rc!=SQLITE_OK ){
52127     goto freepage_out;
52128   }
52129   put4byte(pPage->aData, iTrunk);
52130   put4byte(&pPage->aData[4], 0);
52131   put4byte(&pPage1->aData[32], iPage);
52132   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52133
52134 freepage_out:
52135   if( pPage ){
52136     pPage->isInit = 0;
52137   }
52138   releasePage(pPage);
52139   releasePage(pTrunk);
52140   return rc;
52141 }
52142 static void freePage(MemPage *pPage, int *pRC){
52143   if( (*pRC)==SQLITE_OK ){
52144     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52145   }
52146 }
52147
52148 /*
52149 ** Free any overflow pages associated with the given Cell.
52150 */
52151 static int clearCell(MemPage *pPage, unsigned char *pCell){
52152   BtShared *pBt = pPage->pBt;
52153   CellInfo info;
52154   Pgno ovflPgno;
52155   int rc;
52156   int nOvfl;
52157   u32 ovflPageSize;
52158
52159   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52160   btreeParseCellPtr(pPage, pCell, &info);
52161   if( info.iOverflow==0 ){
52162     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
52163   }
52164   ovflPgno = get4byte(&pCell[info.iOverflow]);
52165   assert( pBt->usableSize > 4 );
52166   ovflPageSize = pBt->usableSize - 4;
52167   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52168   assert( ovflPgno==0 || nOvfl>0 );
52169   while( nOvfl-- ){
52170     Pgno iNext = 0;
52171     MemPage *pOvfl = 0;
52172     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52173       /* 0 is not a legal page number and page 1 cannot be an 
52174       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
52175       ** file the database must be corrupt. */
52176       return SQLITE_CORRUPT_BKPT;
52177     }
52178     if( nOvfl ){
52179       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52180       if( rc ) return rc;
52181     }
52182
52183     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52184      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52185     ){
52186       /* There is no reason any cursor should have an outstanding reference 
52187       ** to an overflow page belonging to a cell that is being deleted/updated.
52188       ** So if there exists more than one reference to this page, then it 
52189       ** must not really be an overflow page and the database must be corrupt. 
52190       ** It is helpful to detect this before calling freePage2(), as 
52191       ** freePage2() may zero the page contents if secure-delete mode is
52192       ** enabled. If this 'overflow' page happens to be a page that the
52193       ** caller is iterating through or using in some other way, this
52194       ** can be problematic.
52195       */
52196       rc = SQLITE_CORRUPT_BKPT;
52197     }else{
52198       rc = freePage2(pBt, pOvfl, ovflPgno);
52199     }
52200
52201     if( pOvfl ){
52202       sqlite3PagerUnref(pOvfl->pDbPage);
52203     }
52204     if( rc ) return rc;
52205     ovflPgno = iNext;
52206   }
52207   return SQLITE_OK;
52208 }
52209
52210 /*
52211 ** Create the byte sequence used to represent a cell on page pPage
52212 ** and write that byte sequence into pCell[].  Overflow pages are
52213 ** allocated and filled in as necessary.  The calling procedure
52214 ** is responsible for making sure sufficient space has been allocated
52215 ** for pCell[].
52216 **
52217 ** Note that pCell does not necessary need to point to the pPage->aData
52218 ** area.  pCell might point to some temporary storage.  The cell will
52219 ** be constructed in this temporary area then copied into pPage->aData
52220 ** later.
52221 */
52222 static int fillInCell(
52223   MemPage *pPage,                /* The page that contains the cell */
52224   unsigned char *pCell,          /* Complete text of the cell */
52225   const void *pKey, i64 nKey,    /* The key */
52226   const void *pData,int nData,   /* The data */
52227   int nZero,                     /* Extra zero bytes to append to pData */
52228   int *pnSize                    /* Write cell size here */
52229 ){
52230   int nPayload;
52231   const u8 *pSrc;
52232   int nSrc, n, rc;
52233   int spaceLeft;
52234   MemPage *pOvfl = 0;
52235   MemPage *pToRelease = 0;
52236   unsigned char *pPrior;
52237   unsigned char *pPayload;
52238   BtShared *pBt = pPage->pBt;
52239   Pgno pgnoOvfl = 0;
52240   int nHeader;
52241   CellInfo info;
52242
52243   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52244
52245   /* pPage is not necessarily writeable since pCell might be auxiliary
52246   ** buffer space that is separate from the pPage buffer area */
52247   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52248             || sqlite3PagerIswriteable(pPage->pDbPage) );
52249
52250   /* Fill in the header. */
52251   nHeader = 0;
52252   if( !pPage->leaf ){
52253     nHeader += 4;
52254   }
52255   if( pPage->hasData ){
52256     nHeader += putVarint(&pCell[nHeader], nData+nZero);
52257   }else{
52258     nData = nZero = 0;
52259   }
52260   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52261   btreeParseCellPtr(pPage, pCell, &info);
52262   assert( info.nHeader==nHeader );
52263   assert( info.nKey==nKey );
52264   assert( info.nData==(u32)(nData+nZero) );
52265   
52266   /* Fill in the payload */
52267   nPayload = nData + nZero;
52268   if( pPage->intKey ){
52269     pSrc = pData;
52270     nSrc = nData;
52271     nData = 0;
52272   }else{ 
52273     if( NEVER(nKey>0x7fffffff || pKey==0) ){
52274       return SQLITE_CORRUPT_BKPT;
52275     }
52276     nPayload += (int)nKey;
52277     pSrc = pKey;
52278     nSrc = (int)nKey;
52279   }
52280   *pnSize = info.nSize;
52281   spaceLeft = info.nLocal;
52282   pPayload = &pCell[nHeader];
52283   pPrior = &pCell[info.iOverflow];
52284
52285   while( nPayload>0 ){
52286     if( spaceLeft==0 ){
52287 #ifndef SQLITE_OMIT_AUTOVACUUM
52288       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52289       if( pBt->autoVacuum ){
52290         do{
52291           pgnoOvfl++;
52292         } while( 
52293           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
52294         );
52295       }
52296 #endif
52297       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52298 #ifndef SQLITE_OMIT_AUTOVACUUM
52299       /* If the database supports auto-vacuum, and the second or subsequent
52300       ** overflow page is being allocated, add an entry to the pointer-map
52301       ** for that page now. 
52302       **
52303       ** If this is the first overflow page, then write a partial entry 
52304       ** to the pointer-map. If we write nothing to this pointer-map slot,
52305       ** then the optimistic overflow chain processing in clearCell()
52306       ** may misinterpret the uninitialised values and delete the
52307       ** wrong pages from the database.
52308       */
52309       if( pBt->autoVacuum && rc==SQLITE_OK ){
52310         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52311         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52312         if( rc ){
52313           releasePage(pOvfl);
52314         }
52315       }
52316 #endif
52317       if( rc ){
52318         releasePage(pToRelease);
52319         return rc;
52320       }
52321
52322       /* If pToRelease is not zero than pPrior points into the data area
52323       ** of pToRelease.  Make sure pToRelease is still writeable. */
52324       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52325
52326       /* If pPrior is part of the data area of pPage, then make sure pPage
52327       ** is still writeable */
52328       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52329             || sqlite3PagerIswriteable(pPage->pDbPage) );
52330
52331       put4byte(pPrior, pgnoOvfl);
52332       releasePage(pToRelease);
52333       pToRelease = pOvfl;
52334       pPrior = pOvfl->aData;
52335       put4byte(pPrior, 0);
52336       pPayload = &pOvfl->aData[4];
52337       spaceLeft = pBt->usableSize - 4;
52338     }
52339     n = nPayload;
52340     if( n>spaceLeft ) n = spaceLeft;
52341
52342     /* If pToRelease is not zero than pPayload points into the data area
52343     ** of pToRelease.  Make sure pToRelease is still writeable. */
52344     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52345
52346     /* If pPayload is part of the data area of pPage, then make sure pPage
52347     ** is still writeable */
52348     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52349             || sqlite3PagerIswriteable(pPage->pDbPage) );
52350
52351     if( nSrc>0 ){
52352       if( n>nSrc ) n = nSrc;
52353       assert( pSrc );
52354       memcpy(pPayload, pSrc, n);
52355     }else{
52356       memset(pPayload, 0, n);
52357     }
52358     nPayload -= n;
52359     pPayload += n;
52360     pSrc += n;
52361     nSrc -= n;
52362     spaceLeft -= n;
52363     if( nSrc==0 ){
52364       nSrc = nData;
52365       pSrc = pData;
52366     }
52367   }
52368   releasePage(pToRelease);
52369   return SQLITE_OK;
52370 }
52371
52372 /*
52373 ** Remove the i-th cell from pPage.  This routine effects pPage only.
52374 ** The cell content is not freed or deallocated.  It is assumed that
52375 ** the cell content has been copied someplace else.  This routine just
52376 ** removes the reference to the cell from pPage.
52377 **
52378 ** "sz" must be the number of bytes in the cell.
52379 */
52380 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52381   int i;          /* Loop counter */
52382   u32 pc;         /* Offset to cell content of cell being deleted */
52383   u8 *data;       /* pPage->aData */
52384   u8 *ptr;        /* Used to move bytes around within data[] */
52385   int rc;         /* The return code */
52386   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
52387
52388   if( *pRC ) return;
52389
52390   assert( idx>=0 && idx<pPage->nCell );
52391   assert( sz==cellSize(pPage, idx) );
52392   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52393   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52394   data = pPage->aData;
52395   ptr = &data[pPage->cellOffset + 2*idx];
52396   pc = get2byte(ptr);
52397   hdr = pPage->hdrOffset;
52398   testcase( pc==get2byte(&data[hdr+5]) );
52399   testcase( pc+sz==pPage->pBt->usableSize );
52400   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52401     *pRC = SQLITE_CORRUPT_BKPT;
52402     return;
52403   }
52404   rc = freeSpace(pPage, pc, sz);
52405   if( rc ){
52406     *pRC = rc;
52407     return;
52408   }
52409   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
52410     ptr[0] = ptr[2];
52411     ptr[1] = ptr[3];
52412   }
52413   pPage->nCell--;
52414   put2byte(&data[hdr+3], pPage->nCell);
52415   pPage->nFree += 2;
52416 }
52417
52418 /*
52419 ** Insert a new cell on pPage at cell index "i".  pCell points to the
52420 ** content of the cell.
52421 **
52422 ** If the cell content will fit on the page, then put it there.  If it
52423 ** will not fit, then make a copy of the cell content into pTemp if
52424 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
52425 ** in pPage->aOvfl[] and make it point to the cell content (either
52426 ** in pTemp or the original pCell) and also record its index. 
52427 ** Allocating a new entry in pPage->aCell[] implies that 
52428 ** pPage->nOverflow is incremented.
52429 **
52430 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52431 ** cell. The caller will overwrite them after this function returns. If
52432 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
52433 ** (but pCell+nSkip is always valid).
52434 */
52435 static void insertCell(
52436   MemPage *pPage,   /* Page into which we are copying */
52437   int i,            /* New cell becomes the i-th cell of the page */
52438   u8 *pCell,        /* Content of the new cell */
52439   int sz,           /* Bytes of content in pCell */
52440   u8 *pTemp,        /* Temp storage space for pCell, if needed */
52441   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
52442   int *pRC          /* Read and write return code from here */
52443 ){
52444   int idx = 0;      /* Where to write new cell content in data[] */
52445   int j;            /* Loop counter */
52446   int end;          /* First byte past the last cell pointer in data[] */
52447   int ins;          /* Index in data[] where new cell pointer is inserted */
52448   int cellOffset;   /* Address of first cell pointer in data[] */
52449   u8 *data;         /* The content of the whole page */
52450   u8 *ptr;          /* Used for moving information around in data[] */
52451
52452   int nSkip = (iChild ? 4 : 0);
52453
52454   if( *pRC ) return;
52455
52456   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52457   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52458   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52459   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52460   /* The cell should normally be sized correctly.  However, when moving a
52461   ** malformed cell from a leaf page to an interior page, if the cell size
52462   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52463   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
52464   ** the term after the || in the following assert(). */
52465   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52466   if( pPage->nOverflow || sz+2>pPage->nFree ){
52467     if( pTemp ){
52468       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52469       pCell = pTemp;
52470     }
52471     if( iChild ){
52472       put4byte(pCell, iChild);
52473     }
52474     j = pPage->nOverflow++;
52475     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
52476     pPage->aOvfl[j].pCell = pCell;
52477     pPage->aOvfl[j].idx = (u16)i;
52478   }else{
52479     int rc = sqlite3PagerWrite(pPage->pDbPage);
52480     if( rc!=SQLITE_OK ){
52481       *pRC = rc;
52482       return;
52483     }
52484     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52485     data = pPage->aData;
52486     cellOffset = pPage->cellOffset;
52487     end = cellOffset + 2*pPage->nCell;
52488     ins = cellOffset + 2*i;
52489     rc = allocateSpace(pPage, sz, &idx);
52490     if( rc ){ *pRC = rc; return; }
52491     /* The allocateSpace() routine guarantees the following two properties
52492     ** if it returns success */
52493     assert( idx >= end+2 );
52494     assert( idx+sz <= (int)pPage->pBt->usableSize );
52495     pPage->nCell++;
52496     pPage->nFree -= (u16)(2 + sz);
52497     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
52498     if( iChild ){
52499       put4byte(&data[idx], iChild);
52500     }
52501     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
52502       ptr[0] = ptr[-2];
52503       ptr[1] = ptr[-1];
52504     }
52505     put2byte(&data[ins], idx);
52506     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
52507 #ifndef SQLITE_OMIT_AUTOVACUUM
52508     if( pPage->pBt->autoVacuum ){
52509       /* The cell may contain a pointer to an overflow page. If so, write
52510       ** the entry for the overflow page into the pointer map.
52511       */
52512       ptrmapPutOvflPtr(pPage, pCell, pRC);
52513     }
52514 #endif
52515   }
52516 }
52517
52518 /*
52519 ** Add a list of cells to a page.  The page should be initially empty.
52520 ** The cells are guaranteed to fit on the page.
52521 */
52522 static void assemblePage(
52523   MemPage *pPage,   /* The page to be assemblied */
52524   int nCell,        /* The number of cells to add to this page */
52525   u8 **apCell,      /* Pointers to cell bodies */
52526   u16 *aSize        /* Sizes of the cells */
52527 ){
52528   int i;            /* Loop counter */
52529   u8 *pCellptr;     /* Address of next cell pointer */
52530   int cellbody;     /* Address of next cell body */
52531   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
52532   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
52533   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
52534
52535   assert( pPage->nOverflow==0 );
52536   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52537   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
52538             && (int)MX_CELL(pPage->pBt)<=10921);
52539   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52540
52541   /* Check that the page has just been zeroed by zeroPage() */
52542   assert( pPage->nCell==0 );
52543   assert( get2byteNotZero(&data[hdr+5])==nUsable );
52544
52545   pCellptr = &data[pPage->cellOffset + nCell*2];
52546   cellbody = nUsable;
52547   for(i=nCell-1; i>=0; i--){
52548     pCellptr -= 2;
52549     cellbody -= aSize[i];
52550     put2byte(pCellptr, cellbody);
52551     memcpy(&data[cellbody], apCell[i], aSize[i]);
52552   }
52553   put2byte(&data[hdr+3], nCell);
52554   put2byte(&data[hdr+5], cellbody);
52555   pPage->nFree -= (nCell*2 + nUsable - cellbody);
52556   pPage->nCell = (u16)nCell;
52557 }
52558
52559 /*
52560 ** The following parameters determine how many adjacent pages get involved
52561 ** in a balancing operation.  NN is the number of neighbors on either side
52562 ** of the page that participate in the balancing operation.  NB is the
52563 ** total number of pages that participate, including the target page and
52564 ** NN neighbors on either side.
52565 **
52566 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
52567 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
52568 ** in exchange for a larger degradation in INSERT and UPDATE performance.
52569 ** The value of NN appears to give the best results overall.
52570 */
52571 #define NN 1             /* Number of neighbors on either side of pPage */
52572 #define NB (NN*2+1)      /* Total pages involved in the balance */
52573
52574
52575 #ifndef SQLITE_OMIT_QUICKBALANCE
52576 /*
52577 ** This version of balance() handles the common special case where
52578 ** a new entry is being inserted on the extreme right-end of the
52579 ** tree, in other words, when the new entry will become the largest
52580 ** entry in the tree.
52581 **
52582 ** Instead of trying to balance the 3 right-most leaf pages, just add
52583 ** a new page to the right-hand side and put the one new entry in
52584 ** that page.  This leaves the right side of the tree somewhat
52585 ** unbalanced.  But odds are that we will be inserting new entries
52586 ** at the end soon afterwards so the nearly empty page will quickly
52587 ** fill up.  On average.
52588 **
52589 ** pPage is the leaf page which is the right-most page in the tree.
52590 ** pParent is its parent.  pPage must have a single overflow entry
52591 ** which is also the right-most entry on the page.
52592 **
52593 ** The pSpace buffer is used to store a temporary copy of the divider
52594 ** cell that will be inserted into pParent. Such a cell consists of a 4
52595 ** byte page number followed by a variable length integer. In other
52596 ** words, at most 13 bytes. Hence the pSpace buffer must be at
52597 ** least 13 bytes in size.
52598 */
52599 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
52600   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
52601   MemPage *pNew;                       /* Newly allocated page */
52602   int rc;                              /* Return Code */
52603   Pgno pgnoNew;                        /* Page number of pNew */
52604
52605   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52606   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52607   assert( pPage->nOverflow==1 );
52608
52609   /* This error condition is now caught prior to reaching this function */
52610   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
52611
52612   /* Allocate a new page. This page will become the right-sibling of 
52613   ** pPage. Make the parent page writable, so that the new divider cell
52614   ** may be inserted. If both these operations are successful, proceed.
52615   */
52616   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
52617
52618   if( rc==SQLITE_OK ){
52619
52620     u8 *pOut = &pSpace[4];
52621     u8 *pCell = pPage->aOvfl[0].pCell;
52622     u16 szCell = cellSizePtr(pPage, pCell);
52623     u8 *pStop;
52624
52625     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
52626     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
52627     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
52628     assemblePage(pNew, 1, &pCell, &szCell);
52629
52630     /* If this is an auto-vacuum database, update the pointer map
52631     ** with entries for the new page, and any pointer from the 
52632     ** cell on the page to an overflow page. If either of these
52633     ** operations fails, the return code is set, but the contents
52634     ** of the parent page are still manipulated by thh code below.
52635     ** That is Ok, at this point the parent page is guaranteed to
52636     ** be marked as dirty. Returning an error code will cause a
52637     ** rollback, undoing any changes made to the parent page.
52638     */
52639     if( ISAUTOVACUUM ){
52640       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
52641       if( szCell>pNew->minLocal ){
52642         ptrmapPutOvflPtr(pNew, pCell, &rc);
52643       }
52644     }
52645   
52646     /* Create a divider cell to insert into pParent. The divider cell
52647     ** consists of a 4-byte page number (the page number of pPage) and
52648     ** a variable length key value (which must be the same value as the
52649     ** largest key on pPage).
52650     **
52651     ** To find the largest key value on pPage, first find the right-most 
52652     ** cell on pPage. The first two fields of this cell are the 
52653     ** record-length (a variable length integer at most 32-bits in size)
52654     ** and the key value (a variable length integer, may have any value).
52655     ** The first of the while(...) loops below skips over the record-length
52656     ** field. The second while(...) loop copies the key value from the
52657     ** cell on pPage into the pSpace buffer.
52658     */
52659     pCell = findCell(pPage, pPage->nCell-1);
52660     pStop = &pCell[9];
52661     while( (*(pCell++)&0x80) && pCell<pStop );
52662     pStop = &pCell[9];
52663     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
52664
52665     /* Insert the new divider cell into pParent. */
52666     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
52667                0, pPage->pgno, &rc);
52668
52669     /* Set the right-child pointer of pParent to point to the new page. */
52670     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
52671   
52672     /* Release the reference to the new page. */
52673     releasePage(pNew);
52674   }
52675
52676   return rc;
52677 }
52678 #endif /* SQLITE_OMIT_QUICKBALANCE */
52679
52680 #if 0
52681 /*
52682 ** This function does not contribute anything to the operation of SQLite.
52683 ** it is sometimes activated temporarily while debugging code responsible 
52684 ** for setting pointer-map entries.
52685 */
52686 static int ptrmapCheckPages(MemPage **apPage, int nPage){
52687   int i, j;
52688   for(i=0; i<nPage; i++){
52689     Pgno n;
52690     u8 e;
52691     MemPage *pPage = apPage[i];
52692     BtShared *pBt = pPage->pBt;
52693     assert( pPage->isInit );
52694
52695     for(j=0; j<pPage->nCell; j++){
52696       CellInfo info;
52697       u8 *z;
52698      
52699       z = findCell(pPage, j);
52700       btreeParseCellPtr(pPage, z, &info);
52701       if( info.iOverflow ){
52702         Pgno ovfl = get4byte(&z[info.iOverflow]);
52703         ptrmapGet(pBt, ovfl, &e, &n);
52704         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
52705       }
52706       if( !pPage->leaf ){
52707         Pgno child = get4byte(z);
52708         ptrmapGet(pBt, child, &e, &n);
52709         assert( n==pPage->pgno && e==PTRMAP_BTREE );
52710       }
52711     }
52712     if( !pPage->leaf ){
52713       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52714       ptrmapGet(pBt, child, &e, &n);
52715       assert( n==pPage->pgno && e==PTRMAP_BTREE );
52716     }
52717   }
52718   return 1;
52719 }
52720 #endif
52721
52722 /*
52723 ** This function is used to copy the contents of the b-tree node stored 
52724 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
52725 ** the pointer-map entries for each child page are updated so that the
52726 ** parent page stored in the pointer map is page pTo. If pFrom contained
52727 ** any cells with overflow page pointers, then the corresponding pointer
52728 ** map entries are also updated so that the parent page is page pTo.
52729 **
52730 ** If pFrom is currently carrying any overflow cells (entries in the
52731 ** MemPage.aOvfl[] array), they are not copied to pTo. 
52732 **
52733 ** Before returning, page pTo is reinitialized using btreeInitPage().
52734 **
52735 ** The performance of this function is not critical. It is only used by 
52736 ** the balance_shallower() and balance_deeper() procedures, neither of
52737 ** which are called often under normal circumstances.
52738 */
52739 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
52740   if( (*pRC)==SQLITE_OK ){
52741     BtShared * const pBt = pFrom->pBt;
52742     u8 * const aFrom = pFrom->aData;
52743     u8 * const aTo = pTo->aData;
52744     int const iFromHdr = pFrom->hdrOffset;
52745     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
52746     int rc;
52747     int iData;
52748   
52749   
52750     assert( pFrom->isInit );
52751     assert( pFrom->nFree>=iToHdr );
52752     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
52753   
52754     /* Copy the b-tree node content from page pFrom to page pTo. */
52755     iData = get2byte(&aFrom[iFromHdr+5]);
52756     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
52757     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
52758   
52759     /* Reinitialize page pTo so that the contents of the MemPage structure
52760     ** match the new data. The initialization of pTo can actually fail under
52761     ** fairly obscure circumstances, even though it is a copy of initialized 
52762     ** page pFrom.
52763     */
52764     pTo->isInit = 0;
52765     rc = btreeInitPage(pTo);
52766     if( rc!=SQLITE_OK ){
52767       *pRC = rc;
52768       return;
52769     }
52770   
52771     /* If this is an auto-vacuum database, update the pointer-map entries
52772     ** for any b-tree or overflow pages that pTo now contains the pointers to.
52773     */
52774     if( ISAUTOVACUUM ){
52775       *pRC = setChildPtrmaps(pTo);
52776     }
52777   }
52778 }
52779
52780 /*
52781 ** This routine redistributes cells on the iParentIdx'th child of pParent
52782 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
52783 ** same amount of free space. Usually a single sibling on either side of the
52784 ** page are used in the balancing, though both siblings might come from one
52785 ** side if the page is the first or last child of its parent. If the page 
52786 ** has fewer than 2 siblings (something which can only happen if the page
52787 ** is a root page or a child of a root page) then all available siblings
52788 ** participate in the balancing.
52789 **
52790 ** The number of siblings of the page might be increased or decreased by 
52791 ** one or two in an effort to keep pages nearly full but not over full. 
52792 **
52793 ** Note that when this routine is called, some of the cells on the page
52794 ** might not actually be stored in MemPage.aData[]. This can happen
52795 ** if the page is overfull. This routine ensures that all cells allocated
52796 ** to the page and its siblings fit into MemPage.aData[] before returning.
52797 **
52798 ** In the course of balancing the page and its siblings, cells may be
52799 ** inserted into or removed from the parent page (pParent). Doing so
52800 ** may cause the parent page to become overfull or underfull. If this
52801 ** happens, it is the responsibility of the caller to invoke the correct
52802 ** balancing routine to fix this problem (see the balance() routine). 
52803 **
52804 ** If this routine fails for any reason, it might leave the database
52805 ** in a corrupted state. So if this routine fails, the database should
52806 ** be rolled back.
52807 **
52808 ** The third argument to this function, aOvflSpace, is a pointer to a
52809 ** buffer big enough to hold one page. If while inserting cells into the parent
52810 ** page (pParent) the parent page becomes overfull, this buffer is
52811 ** used to store the parent's overflow cells. Because this function inserts
52812 ** a maximum of four divider cells into the parent page, and the maximum
52813 ** size of a cell stored within an internal node is always less than 1/4
52814 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
52815 ** enough for all overflow cells.
52816 **
52817 ** If aOvflSpace is set to a null pointer, this function returns 
52818 ** SQLITE_NOMEM.
52819 */
52820 static int balance_nonroot(
52821   MemPage *pParent,               /* Parent page of siblings being balanced */
52822   int iParentIdx,                 /* Index of "the page" in pParent */
52823   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
52824   int isRoot                      /* True if pParent is a root-page */
52825 ){
52826   BtShared *pBt;               /* The whole database */
52827   int nCell = 0;               /* Number of cells in apCell[] */
52828   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
52829   int nNew = 0;                /* Number of pages in apNew[] */
52830   int nOld;                    /* Number of pages in apOld[] */
52831   int i, j, k;                 /* Loop counters */
52832   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
52833   int rc = SQLITE_OK;          /* The return code */
52834   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
52835   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
52836   int usableSpace;             /* Bytes in pPage beyond the header */
52837   int pageFlags;               /* Value of pPage->aData[0] */
52838   int subtotal;                /* Subtotal of bytes in cells on one page */
52839   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
52840   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
52841   int szScratch;               /* Size of scratch memory requested */
52842   MemPage *apOld[NB];          /* pPage and up to two siblings */
52843   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
52844   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
52845   u8 *pRight;                  /* Location in parent of right-sibling pointer */
52846   u8 *apDiv[NB-1];             /* Divider cells in pParent */
52847   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
52848   int szNew[NB+2];             /* Combined size of cells place on i-th page */
52849   u8 **apCell = 0;             /* All cells begin balanced */
52850   u16 *szCell;                 /* Local size of all cells in apCell[] */
52851   u8 *aSpace1;                 /* Space for copies of dividers cells */
52852   Pgno pgno;                   /* Temp var to store a page number in */
52853
52854   pBt = pParent->pBt;
52855   assert( sqlite3_mutex_held(pBt->mutex) );
52856   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52857
52858 #if 0
52859   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
52860 #endif
52861
52862   /* At this point pParent may have at most one overflow cell. And if
52863   ** this overflow cell is present, it must be the cell with 
52864   ** index iParentIdx. This scenario comes about when this function
52865   ** is called (indirectly) from sqlite3BtreeDelete().
52866   */
52867   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
52868   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
52869
52870   if( !aOvflSpace ){
52871     return SQLITE_NOMEM;
52872   }
52873
52874   /* Find the sibling pages to balance. Also locate the cells in pParent 
52875   ** that divide the siblings. An attempt is made to find NN siblings on 
52876   ** either side of pPage. More siblings are taken from one side, however, 
52877   ** if there are fewer than NN siblings on the other side. If pParent
52878   ** has NB or fewer children then all children of pParent are taken.  
52879   **
52880   ** This loop also drops the divider cells from the parent page. This
52881   ** way, the remainder of the function does not have to deal with any
52882   ** overflow cells in the parent page, since if any existed they will
52883   ** have already been removed.
52884   */
52885   i = pParent->nOverflow + pParent->nCell;
52886   if( i<2 ){
52887     nxDiv = 0;
52888     nOld = i+1;
52889   }else{
52890     nOld = 3;
52891     if( iParentIdx==0 ){                 
52892       nxDiv = 0;
52893     }else if( iParentIdx==i ){
52894       nxDiv = i-2;
52895     }else{
52896       nxDiv = iParentIdx-1;
52897     }
52898     i = 2;
52899   }
52900   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
52901     pRight = &pParent->aData[pParent->hdrOffset+8];
52902   }else{
52903     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
52904   }
52905   pgno = get4byte(pRight);
52906   while( 1 ){
52907     rc = getAndInitPage(pBt, pgno, &apOld[i]);
52908     if( rc ){
52909       memset(apOld, 0, (i+1)*sizeof(MemPage*));
52910       goto balance_cleanup;
52911     }
52912     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
52913     if( (i--)==0 ) break;
52914
52915     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
52916       apDiv[i] = pParent->aOvfl[0].pCell;
52917       pgno = get4byte(apDiv[i]);
52918       szNew[i] = cellSizePtr(pParent, apDiv[i]);
52919       pParent->nOverflow = 0;
52920     }else{
52921       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
52922       pgno = get4byte(apDiv[i]);
52923       szNew[i] = cellSizePtr(pParent, apDiv[i]);
52924
52925       /* Drop the cell from the parent page. apDiv[i] still points to
52926       ** the cell within the parent, even though it has been dropped.
52927       ** This is safe because dropping a cell only overwrites the first
52928       ** four bytes of it, and this function does not need the first
52929       ** four bytes of the divider cell. So the pointer is safe to use
52930       ** later on.  
52931       **
52932       ** Unless SQLite is compiled in secure-delete mode. In this case,
52933       ** the dropCell() routine will overwrite the entire cell with zeroes.
52934       ** In this case, temporarily copy the cell into the aOvflSpace[]
52935       ** buffer. It will be copied out again as soon as the aSpace[] buffer
52936       ** is allocated.  */
52937       if( pBt->secureDelete ){
52938         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
52939         if( (iOff+szNew[i])>(int)pBt->usableSize ){
52940           rc = SQLITE_CORRUPT_BKPT;
52941           memset(apOld, 0, (i+1)*sizeof(MemPage*));
52942           goto balance_cleanup;
52943         }else{
52944           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
52945           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
52946         }
52947       }
52948       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
52949     }
52950   }
52951
52952   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
52953   ** alignment */
52954   nMaxCells = (nMaxCells + 3)&~3;
52955
52956   /*
52957   ** Allocate space for memory structures
52958   */
52959   k = pBt->pageSize + ROUND8(sizeof(MemPage));
52960   szScratch =
52961        nMaxCells*sizeof(u8*)                       /* apCell */
52962      + nMaxCells*sizeof(u16)                       /* szCell */
52963      + pBt->pageSize                               /* aSpace1 */
52964      + k*nOld;                                     /* Page copies (apCopy) */
52965   apCell = sqlite3ScratchMalloc( szScratch ); 
52966   if( apCell==0 ){
52967     rc = SQLITE_NOMEM;
52968     goto balance_cleanup;
52969   }
52970   szCell = (u16*)&apCell[nMaxCells];
52971   aSpace1 = (u8*)&szCell[nMaxCells];
52972   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
52973
52974   /*
52975   ** Load pointers to all cells on sibling pages and the divider cells
52976   ** into the local apCell[] array.  Make copies of the divider cells
52977   ** into space obtained from aSpace1[] and remove the the divider Cells
52978   ** from pParent.
52979   **
52980   ** If the siblings are on leaf pages, then the child pointers of the
52981   ** divider cells are stripped from the cells before they are copied
52982   ** into aSpace1[].  In this way, all cells in apCell[] are without
52983   ** child pointers.  If siblings are not leaves, then all cell in
52984   ** apCell[] include child pointers.  Either way, all cells in apCell[]
52985   ** are alike.
52986   **
52987   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
52988   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
52989   */
52990   leafCorrection = apOld[0]->leaf*4;
52991   leafData = apOld[0]->hasData;
52992   for(i=0; i<nOld; i++){
52993     int limit;
52994     
52995     /* Before doing anything else, take a copy of the i'th original sibling
52996     ** The rest of this function will use data from the copies rather
52997     ** that the original pages since the original pages will be in the
52998     ** process of being overwritten.  */
52999     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
53000     memcpy(pOld, apOld[i], sizeof(MemPage));
53001     pOld->aData = (void*)&pOld[1];
53002     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
53003
53004     limit = pOld->nCell+pOld->nOverflow;
53005     for(j=0; j<limit; j++){
53006       assert( nCell<nMaxCells );
53007       apCell[nCell] = findOverflowCell(pOld, j);
53008       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53009       nCell++;
53010     }
53011     if( i<nOld-1 && !leafData){
53012       u16 sz = (u16)szNew[i];
53013       u8 *pTemp;
53014       assert( nCell<nMaxCells );
53015       szCell[nCell] = sz;
53016       pTemp = &aSpace1[iSpace1];
53017       iSpace1 += sz;
53018       assert( sz<=pBt->maxLocal+23 );
53019       assert( iSpace1 <= (int)pBt->pageSize );
53020       memcpy(pTemp, apDiv[i], sz);
53021       apCell[nCell] = pTemp+leafCorrection;
53022       assert( leafCorrection==0 || leafCorrection==4 );
53023       szCell[nCell] = szCell[nCell] - leafCorrection;
53024       if( !pOld->leaf ){
53025         assert( leafCorrection==0 );
53026         assert( pOld->hdrOffset==0 );
53027         /* The right pointer of the child page pOld becomes the left
53028         ** pointer of the divider cell */
53029         memcpy(apCell[nCell], &pOld->aData[8], 4);
53030       }else{
53031         assert( leafCorrection==4 );
53032         if( szCell[nCell]<4 ){
53033           /* Do not allow any cells smaller than 4 bytes. */
53034           szCell[nCell] = 4;
53035         }
53036       }
53037       nCell++;
53038     }
53039   }
53040
53041   /*
53042   ** Figure out the number of pages needed to hold all nCell cells.
53043   ** Store this number in "k".  Also compute szNew[] which is the total
53044   ** size of all cells on the i-th page and cntNew[] which is the index
53045   ** in apCell[] of the cell that divides page i from page i+1.  
53046   ** cntNew[k] should equal nCell.
53047   **
53048   ** Values computed by this block:
53049   **
53050   **           k: The total number of sibling pages
53051   **    szNew[i]: Spaced used on the i-th sibling page.
53052   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53053   **              the right of the i-th sibling page.
53054   ** usableSpace: Number of bytes of space available on each sibling.
53055   ** 
53056   */
53057   usableSpace = pBt->usableSize - 12 + leafCorrection;
53058   for(subtotal=k=i=0; i<nCell; i++){
53059     assert( i<nMaxCells );
53060     subtotal += szCell[i] + 2;
53061     if( subtotal > usableSpace ){
53062       szNew[k] = subtotal - szCell[i];
53063       cntNew[k] = i;
53064       if( leafData ){ i--; }
53065       subtotal = 0;
53066       k++;
53067       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53068     }
53069   }
53070   szNew[k] = subtotal;
53071   cntNew[k] = nCell;
53072   k++;
53073
53074   /*
53075   ** The packing computed by the previous block is biased toward the siblings
53076   ** on the left side.  The left siblings are always nearly full, while the
53077   ** right-most sibling might be nearly empty.  This block of code attempts
53078   ** to adjust the packing of siblings to get a better balance.
53079   **
53080   ** This adjustment is more than an optimization.  The packing above might
53081   ** be so out of balance as to be illegal.  For example, the right-most
53082   ** sibling might be completely empty.  This adjustment is not optional.
53083   */
53084   for(i=k-1; i>0; i--){
53085     int szRight = szNew[i];  /* Size of sibling on the right */
53086     int szLeft = szNew[i-1]; /* Size of sibling on the left */
53087     int r;              /* Index of right-most cell in left sibling */
53088     int d;              /* Index of first cell to the left of right sibling */
53089
53090     r = cntNew[i-1] - 1;
53091     d = r + 1 - leafData;
53092     assert( d<nMaxCells );
53093     assert( r<nMaxCells );
53094     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53095       szRight += szCell[d] + 2;
53096       szLeft -= szCell[r] + 2;
53097       cntNew[i-1]--;
53098       r = cntNew[i-1] - 1;
53099       d = r + 1 - leafData;
53100     }
53101     szNew[i] = szRight;
53102     szNew[i-1] = szLeft;
53103   }
53104
53105   /* Either we found one or more cells (cntnew[0])>0) or pPage is
53106   ** a virtual root page.  A virtual root page is when the real root
53107   ** page is page 1 and we are the only child of that page.
53108   */
53109   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53110
53111   TRACE(("BALANCE: old: %d %d %d  ",
53112     apOld[0]->pgno, 
53113     nOld>=2 ? apOld[1]->pgno : 0,
53114     nOld>=3 ? apOld[2]->pgno : 0
53115   ));
53116
53117   /*
53118   ** Allocate k new pages.  Reuse old pages where possible.
53119   */
53120   if( apOld[0]->pgno<=1 ){
53121     rc = SQLITE_CORRUPT_BKPT;
53122     goto balance_cleanup;
53123   }
53124   pageFlags = apOld[0]->aData[0];
53125   for(i=0; i<k; i++){
53126     MemPage *pNew;
53127     if( i<nOld ){
53128       pNew = apNew[i] = apOld[i];
53129       apOld[i] = 0;
53130       rc = sqlite3PagerWrite(pNew->pDbPage);
53131       nNew++;
53132       if( rc ) goto balance_cleanup;
53133     }else{
53134       assert( i>0 );
53135       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53136       if( rc ) goto balance_cleanup;
53137       apNew[i] = pNew;
53138       nNew++;
53139
53140       /* Set the pointer-map entry for the new sibling page. */
53141       if( ISAUTOVACUUM ){
53142         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53143         if( rc!=SQLITE_OK ){
53144           goto balance_cleanup;
53145         }
53146       }
53147     }
53148   }
53149
53150   /* Free any old pages that were not reused as new pages.
53151   */
53152   while( i<nOld ){
53153     freePage(apOld[i], &rc);
53154     if( rc ) goto balance_cleanup;
53155     releasePage(apOld[i]);
53156     apOld[i] = 0;
53157     i++;
53158   }
53159
53160   /*
53161   ** Put the new pages in accending order.  This helps to
53162   ** keep entries in the disk file in order so that a scan
53163   ** of the table is a linear scan through the file.  That
53164   ** in turn helps the operating system to deliver pages
53165   ** from the disk more rapidly.
53166   **
53167   ** An O(n^2) insertion sort algorithm is used, but since
53168   ** n is never more than NB (a small constant), that should
53169   ** not be a problem.
53170   **
53171   ** When NB==3, this one optimization makes the database
53172   ** about 25% faster for large insertions and deletions.
53173   */
53174   for(i=0; i<k-1; i++){
53175     int minV = apNew[i]->pgno;
53176     int minI = i;
53177     for(j=i+1; j<k; j++){
53178       if( apNew[j]->pgno<(unsigned)minV ){
53179         minI = j;
53180         minV = apNew[j]->pgno;
53181       }
53182     }
53183     if( minI>i ){
53184       MemPage *pT;
53185       pT = apNew[i];
53186       apNew[i] = apNew[minI];
53187       apNew[minI] = pT;
53188     }
53189   }
53190   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53191     apNew[0]->pgno, szNew[0],
53192     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53193     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53194     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53195     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53196
53197   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53198   put4byte(pRight, apNew[nNew-1]->pgno);
53199
53200   /*
53201   ** Evenly distribute the data in apCell[] across the new pages.
53202   ** Insert divider cells into pParent as necessary.
53203   */
53204   j = 0;
53205   for(i=0; i<nNew; i++){
53206     /* Assemble the new sibling page. */
53207     MemPage *pNew = apNew[i];
53208     assert( j<nMaxCells );
53209     zeroPage(pNew, pageFlags);
53210     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53211     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53212     assert( pNew->nOverflow==0 );
53213
53214     j = cntNew[i];
53215
53216     /* If the sibling page assembled above was not the right-most sibling,
53217     ** insert a divider cell into the parent page.
53218     */
53219     assert( i<nNew-1 || j==nCell );
53220     if( j<nCell ){
53221       u8 *pCell;
53222       u8 *pTemp;
53223       int sz;
53224
53225       assert( j<nMaxCells );
53226       pCell = apCell[j];
53227       sz = szCell[j] + leafCorrection;
53228       pTemp = &aOvflSpace[iOvflSpace];
53229       if( !pNew->leaf ){
53230         memcpy(&pNew->aData[8], pCell, 4);
53231       }else if( leafData ){
53232         /* If the tree is a leaf-data tree, and the siblings are leaves, 
53233         ** then there is no divider cell in apCell[]. Instead, the divider 
53234         ** cell consists of the integer key for the right-most cell of 
53235         ** the sibling-page assembled above only.
53236         */
53237         CellInfo info;
53238         j--;
53239         btreeParseCellPtr(pNew, apCell[j], &info);
53240         pCell = pTemp;
53241         sz = 4 + putVarint(&pCell[4], info.nKey);
53242         pTemp = 0;
53243       }else{
53244         pCell -= 4;
53245         /* Obscure case for non-leaf-data trees: If the cell at pCell was
53246         ** previously stored on a leaf node, and its reported size was 4
53247         ** bytes, then it may actually be smaller than this 
53248         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53249         ** any cell). But it is important to pass the correct size to 
53250         ** insertCell(), so reparse the cell now.
53251         **
53252         ** Note that this can never happen in an SQLite data file, as all
53253         ** cells are at least 4 bytes. It only happens in b-trees used
53254         ** to evaluate "IN (SELECT ...)" and similar clauses.
53255         */
53256         if( szCell[j]==4 ){
53257           assert(leafCorrection==4);
53258           sz = cellSizePtr(pParent, pCell);
53259         }
53260       }
53261       iOvflSpace += sz;
53262       assert( sz<=pBt->maxLocal+23 );
53263       assert( iOvflSpace <= (int)pBt->pageSize );
53264       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53265       if( rc!=SQLITE_OK ) goto balance_cleanup;
53266       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53267
53268       j++;
53269       nxDiv++;
53270     }
53271   }
53272   assert( j==nCell );
53273   assert( nOld>0 );
53274   assert( nNew>0 );
53275   if( (pageFlags & PTF_LEAF)==0 ){
53276     u8 *zChild = &apCopy[nOld-1]->aData[8];
53277     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53278   }
53279
53280   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53281     /* The root page of the b-tree now contains no cells. The only sibling
53282     ** page is the right-child of the parent. Copy the contents of the
53283     ** child page into the parent, decreasing the overall height of the
53284     ** b-tree structure by one. This is described as the "balance-shallower"
53285     ** sub-algorithm in some documentation.
53286     **
53287     ** If this is an auto-vacuum database, the call to copyNodeContent() 
53288     ** sets all pointer-map entries corresponding to database image pages 
53289     ** for which the pointer is stored within the content being copied.
53290     **
53291     ** The second assert below verifies that the child page is defragmented
53292     ** (it must be, as it was just reconstructed using assemblePage()). This
53293     ** is important if the parent page happens to be page 1 of the database
53294     ** image.  */
53295     assert( nNew==1 );
53296     assert( apNew[0]->nFree == 
53297         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
53298     );
53299     copyNodeContent(apNew[0], pParent, &rc);
53300     freePage(apNew[0], &rc);
53301   }else if( ISAUTOVACUUM ){
53302     /* Fix the pointer-map entries for all the cells that were shifted around. 
53303     ** There are several different types of pointer-map entries that need to
53304     ** be dealt with by this routine. Some of these have been set already, but
53305     ** many have not. The following is a summary:
53306     **
53307     **   1) The entries associated with new sibling pages that were not
53308     **      siblings when this function was called. These have already
53309     **      been set. We don't need to worry about old siblings that were
53310     **      moved to the free-list - the freePage() code has taken care
53311     **      of those.
53312     **
53313     **   2) The pointer-map entries associated with the first overflow
53314     **      page in any overflow chains used by new divider cells. These 
53315     **      have also already been taken care of by the insertCell() code.
53316     **
53317     **   3) If the sibling pages are not leaves, then the child pages of
53318     **      cells stored on the sibling pages may need to be updated.
53319     **
53320     **   4) If the sibling pages are not internal intkey nodes, then any
53321     **      overflow pages used by these cells may need to be updated
53322     **      (internal intkey nodes never contain pointers to overflow pages).
53323     **
53324     **   5) If the sibling pages are not leaves, then the pointer-map
53325     **      entries for the right-child pages of each sibling may need
53326     **      to be updated.
53327     **
53328     ** Cases 1 and 2 are dealt with above by other code. The next
53329     ** block deals with cases 3 and 4 and the one after that, case 5. Since
53330     ** setting a pointer map entry is a relatively expensive operation, this
53331     ** code only sets pointer map entries for child or overflow pages that have
53332     ** actually moved between pages.  */
53333     MemPage *pNew = apNew[0];
53334     MemPage *pOld = apCopy[0];
53335     int nOverflow = pOld->nOverflow;
53336     int iNextOld = pOld->nCell + nOverflow;
53337     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53338     j = 0;                             /* Current 'old' sibling page */
53339     k = 0;                             /* Current 'new' sibling page */
53340     for(i=0; i<nCell; i++){
53341       int isDivider = 0;
53342       while( i==iNextOld ){
53343         /* Cell i is the cell immediately following the last cell on old
53344         ** sibling page j. If the siblings are not leaf pages of an
53345         ** intkey b-tree, then cell i was a divider cell. */
53346         pOld = apCopy[++j];
53347         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53348         if( pOld->nOverflow ){
53349           nOverflow = pOld->nOverflow;
53350           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53351         }
53352         isDivider = !leafData;  
53353       }
53354
53355       assert(nOverflow>0 || iOverflow<i );
53356       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53357       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53358       if( i==iOverflow ){
53359         isDivider = 1;
53360         if( (--nOverflow)>0 ){
53361           iOverflow++;
53362         }
53363       }
53364
53365       if( i==cntNew[k] ){
53366         /* Cell i is the cell immediately following the last cell on new
53367         ** sibling page k. If the siblings are not leaf pages of an
53368         ** intkey b-tree, then cell i is a divider cell.  */
53369         pNew = apNew[++k];
53370         if( !leafData ) continue;
53371       }
53372       assert( j<nOld );
53373       assert( k<nNew );
53374
53375       /* If the cell was originally divider cell (and is not now) or
53376       ** an overflow cell, or if the cell was located on a different sibling
53377       ** page before the balancing, then the pointer map entries associated
53378       ** with any child or overflow pages need to be updated.  */
53379       if( isDivider || pOld->pgno!=pNew->pgno ){
53380         if( !leafCorrection ){
53381           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53382         }
53383         if( szCell[i]>pNew->minLocal ){
53384           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53385         }
53386       }
53387     }
53388
53389     if( !leafCorrection ){
53390       for(i=0; i<nNew; i++){
53391         u32 key = get4byte(&apNew[i]->aData[8]);
53392         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53393       }
53394     }
53395
53396 #if 0
53397     /* The ptrmapCheckPages() contains assert() statements that verify that
53398     ** all pointer map pages are set correctly. This is helpful while 
53399     ** debugging. This is usually disabled because a corrupt database may
53400     ** cause an assert() statement to fail.  */
53401     ptrmapCheckPages(apNew, nNew);
53402     ptrmapCheckPages(&pParent, 1);
53403 #endif
53404   }
53405
53406   assert( pParent->isInit );
53407   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53408           nOld, nNew, nCell));
53409
53410   /*
53411   ** Cleanup before returning.
53412   */
53413 balance_cleanup:
53414   sqlite3ScratchFree(apCell);
53415   for(i=0; i<nOld; i++){
53416     releasePage(apOld[i]);
53417   }
53418   for(i=0; i<nNew; i++){
53419     releasePage(apNew[i]);
53420   }
53421
53422   return rc;
53423 }
53424
53425
53426 /*
53427 ** This function is called when the root page of a b-tree structure is
53428 ** overfull (has one or more overflow pages).
53429 **
53430 ** A new child page is allocated and the contents of the current root
53431 ** page, including overflow cells, are copied into the child. The root
53432 ** page is then overwritten to make it an empty page with the right-child 
53433 ** pointer pointing to the new page.
53434 **
53435 ** Before returning, all pointer-map entries corresponding to pages 
53436 ** that the new child-page now contains pointers to are updated. The
53437 ** entry corresponding to the new right-child pointer of the root
53438 ** page is also updated.
53439 **
53440 ** If successful, *ppChild is set to contain a reference to the child 
53441 ** page and SQLITE_OK is returned. In this case the caller is required
53442 ** to call releasePage() on *ppChild exactly once. If an error occurs,
53443 ** an error code is returned and *ppChild is set to 0.
53444 */
53445 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53446   int rc;                        /* Return value from subprocedures */
53447   MemPage *pChild = 0;           /* Pointer to a new child page */
53448   Pgno pgnoChild = 0;            /* Page number of the new child page */
53449   BtShared *pBt = pRoot->pBt;    /* The BTree */
53450
53451   assert( pRoot->nOverflow>0 );
53452   assert( sqlite3_mutex_held(pBt->mutex) );
53453
53454   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
53455   ** page that will become the new right-child of pPage. Copy the contents
53456   ** of the node stored on pRoot into the new child page.
53457   */
53458   rc = sqlite3PagerWrite(pRoot->pDbPage);
53459   if( rc==SQLITE_OK ){
53460     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
53461     copyNodeContent(pRoot, pChild, &rc);
53462     if( ISAUTOVACUUM ){
53463       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
53464     }
53465   }
53466   if( rc ){
53467     *ppChild = 0;
53468     releasePage(pChild);
53469     return rc;
53470   }
53471   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
53472   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
53473   assert( pChild->nCell==pRoot->nCell );
53474
53475   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
53476
53477   /* Copy the overflow cells from pRoot to pChild */
53478   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
53479   pChild->nOverflow = pRoot->nOverflow;
53480
53481   /* Zero the contents of pRoot. Then install pChild as the right-child. */
53482   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
53483   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
53484
53485   *ppChild = pChild;
53486   return SQLITE_OK;
53487 }
53488
53489 /*
53490 ** The page that pCur currently points to has just been modified in
53491 ** some way. This function figures out if this modification means the
53492 ** tree needs to be balanced, and if so calls the appropriate balancing 
53493 ** routine. Balancing routines are:
53494 **
53495 **   balance_quick()
53496 **   balance_deeper()
53497 **   balance_nonroot()
53498 */
53499 static int balance(BtCursor *pCur){
53500   int rc = SQLITE_OK;
53501   const int nMin = pCur->pBt->usableSize * 2 / 3;
53502   u8 aBalanceQuickSpace[13];
53503   u8 *pFree = 0;
53504
53505   TESTONLY( int balance_quick_called = 0 );
53506   TESTONLY( int balance_deeper_called = 0 );
53507
53508   do {
53509     int iPage = pCur->iPage;
53510     MemPage *pPage = pCur->apPage[iPage];
53511
53512     if( iPage==0 ){
53513       if( pPage->nOverflow ){
53514         /* The root page of the b-tree is overfull. In this case call the
53515         ** balance_deeper() function to create a new child for the root-page
53516         ** and copy the current contents of the root-page to it. The
53517         ** next iteration of the do-loop will balance the child page.
53518         */ 
53519         assert( (balance_deeper_called++)==0 );
53520         rc = balance_deeper(pPage, &pCur->apPage[1]);
53521         if( rc==SQLITE_OK ){
53522           pCur->iPage = 1;
53523           pCur->aiIdx[0] = 0;
53524           pCur->aiIdx[1] = 0;
53525           assert( pCur->apPage[1]->nOverflow );
53526         }
53527       }else{
53528         break;
53529       }
53530     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
53531       break;
53532     }else{
53533       MemPage * const pParent = pCur->apPage[iPage-1];
53534       int const iIdx = pCur->aiIdx[iPage-1];
53535
53536       rc = sqlite3PagerWrite(pParent->pDbPage);
53537       if( rc==SQLITE_OK ){
53538 #ifndef SQLITE_OMIT_QUICKBALANCE
53539         if( pPage->hasData
53540          && pPage->nOverflow==1
53541          && pPage->aOvfl[0].idx==pPage->nCell
53542          && pParent->pgno!=1
53543          && pParent->nCell==iIdx
53544         ){
53545           /* Call balance_quick() to create a new sibling of pPage on which
53546           ** to store the overflow cell. balance_quick() inserts a new cell
53547           ** into pParent, which may cause pParent overflow. If this
53548           ** happens, the next interation of the do-loop will balance pParent 
53549           ** use either balance_nonroot() or balance_deeper(). Until this
53550           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
53551           ** buffer. 
53552           **
53553           ** The purpose of the following assert() is to check that only a
53554           ** single call to balance_quick() is made for each call to this
53555           ** function. If this were not verified, a subtle bug involving reuse
53556           ** of the aBalanceQuickSpace[] might sneak in.
53557           */
53558           assert( (balance_quick_called++)==0 );
53559           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
53560         }else
53561 #endif
53562         {
53563           /* In this case, call balance_nonroot() to redistribute cells
53564           ** between pPage and up to 2 of its sibling pages. This involves
53565           ** modifying the contents of pParent, which may cause pParent to
53566           ** become overfull or underfull. The next iteration of the do-loop
53567           ** will balance the parent page to correct this.
53568           ** 
53569           ** If the parent page becomes overfull, the overflow cell or cells
53570           ** are stored in the pSpace buffer allocated immediately below. 
53571           ** A subsequent iteration of the do-loop will deal with this by
53572           ** calling balance_nonroot() (balance_deeper() may be called first,
53573           ** but it doesn't deal with overflow cells - just moves them to a
53574           ** different page). Once this subsequent call to balance_nonroot() 
53575           ** has completed, it is safe to release the pSpace buffer used by
53576           ** the previous call, as the overflow cell data will have been 
53577           ** copied either into the body of a database page or into the new
53578           ** pSpace buffer passed to the latter call to balance_nonroot().
53579           */
53580           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
53581           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
53582           if( pFree ){
53583             /* If pFree is not NULL, it points to the pSpace buffer used 
53584             ** by a previous call to balance_nonroot(). Its contents are
53585             ** now stored either on real database pages or within the 
53586             ** new pSpace buffer, so it may be safely freed here. */
53587             sqlite3PageFree(pFree);
53588           }
53589
53590           /* The pSpace buffer will be freed after the next call to
53591           ** balance_nonroot(), or just before this function returns, whichever
53592           ** comes first. */
53593           pFree = pSpace;
53594         }
53595       }
53596
53597       pPage->nOverflow = 0;
53598
53599       /* The next iteration of the do-loop balances the parent page. */
53600       releasePage(pPage);
53601       pCur->iPage--;
53602     }
53603   }while( rc==SQLITE_OK );
53604
53605   if( pFree ){
53606     sqlite3PageFree(pFree);
53607   }
53608   return rc;
53609 }
53610
53611
53612 /*
53613 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
53614 ** and the data is given by (pData,nData).  The cursor is used only to
53615 ** define what table the record should be inserted into.  The cursor
53616 ** is left pointing at a random location.
53617 **
53618 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
53619 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
53620 **
53621 ** If the seekResult parameter is non-zero, then a successful call to
53622 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
53623 ** been performed. seekResult is the search result returned (a negative
53624 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
53625 ** a positive value if pCur points at an etry that is larger than 
53626 ** (pKey, nKey)). 
53627 **
53628 ** If the seekResult parameter is non-zero, then the caller guarantees that
53629 ** cursor pCur is pointing at the existing copy of a row that is to be
53630 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
53631 ** point to any entry or to no entry at all and so this function has to seek
53632 ** the cursor before the new key can be inserted.
53633 */
53634 SQLITE_PRIVATE int sqlite3BtreeInsert(
53635   BtCursor *pCur,                /* Insert data into the table of this cursor */
53636   const void *pKey, i64 nKey,    /* The key of the new record */
53637   const void *pData, int nData,  /* The data of the new record */
53638   int nZero,                     /* Number of extra 0 bytes to append to data */
53639   int appendBias,                /* True if this is likely an append */
53640   int seekResult                 /* Result of prior MovetoUnpacked() call */
53641 ){
53642   int rc;
53643   int loc = seekResult;          /* -1: before desired location  +1: after */
53644   int szNew = 0;
53645   int idx;
53646   MemPage *pPage;
53647   Btree *p = pCur->pBtree;
53648   BtShared *pBt = p->pBt;
53649   unsigned char *oldCell;
53650   unsigned char *newCell = 0;
53651
53652   if( pCur->eState==CURSOR_FAULT ){
53653     assert( pCur->skipNext!=SQLITE_OK );
53654     return pCur->skipNext;
53655   }
53656
53657   assert( cursorHoldsMutex(pCur) );
53658   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
53659   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53660
53661   /* Assert that the caller has been consistent. If this cursor was opened
53662   ** expecting an index b-tree, then the caller should be inserting blob
53663   ** keys with no associated data. If the cursor was opened expecting an
53664   ** intkey table, the caller should be inserting integer keys with a
53665   ** blob of associated data.  */
53666   assert( (pKey==0)==(pCur->pKeyInfo==0) );
53667
53668   /* If this is an insert into a table b-tree, invalidate any incrblob 
53669   ** cursors open on the row being replaced (assuming this is a replace
53670   ** operation - if it is not, the following is a no-op).  */
53671   if( pCur->pKeyInfo==0 ){
53672     invalidateIncrblobCursors(p, nKey, 0);
53673   }
53674
53675   /* Save the positions of any other cursors open on this table.
53676   **
53677   ** In some cases, the call to btreeMoveto() below is a no-op. For
53678   ** example, when inserting data into a table with auto-generated integer
53679   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
53680   ** integer key to use. It then calls this function to actually insert the 
53681   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
53682   ** that the cursor is already where it needs to be and returns without
53683   ** doing any work. To avoid thwarting these optimizations, it is important
53684   ** not to clear the cursor here.
53685   */
53686   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53687   if( rc ) return rc;
53688   if( !loc ){
53689     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
53690     if( rc ) return rc;
53691   }
53692   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
53693
53694   pPage = pCur->apPage[pCur->iPage];
53695   assert( pPage->intKey || nKey>=0 );
53696   assert( pPage->leaf || !pPage->intKey );
53697
53698   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
53699           pCur->pgnoRoot, nKey, nData, pPage->pgno,
53700           loc==0 ? "overwrite" : "new entry"));
53701   assert( pPage->isInit );
53702   allocateTempSpace(pBt);
53703   newCell = pBt->pTmpSpace;
53704   if( newCell==0 ) return SQLITE_NOMEM;
53705   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
53706   if( rc ) goto end_insert;
53707   assert( szNew==cellSizePtr(pPage, newCell) );
53708   assert( szNew <= MX_CELL_SIZE(pBt) );
53709   idx = pCur->aiIdx[pCur->iPage];
53710   if( loc==0 ){
53711     u16 szOld;
53712     assert( idx<pPage->nCell );
53713     rc = sqlite3PagerWrite(pPage->pDbPage);
53714     if( rc ){
53715       goto end_insert;
53716     }
53717     oldCell = findCell(pPage, idx);
53718     if( !pPage->leaf ){
53719       memcpy(newCell, oldCell, 4);
53720     }
53721     szOld = cellSizePtr(pPage, oldCell);
53722     rc = clearCell(pPage, oldCell);
53723     dropCell(pPage, idx, szOld, &rc);
53724     if( rc ) goto end_insert;
53725   }else if( loc<0 && pPage->nCell>0 ){
53726     assert( pPage->leaf );
53727     idx = ++pCur->aiIdx[pCur->iPage];
53728   }else{
53729     assert( pPage->leaf );
53730   }
53731   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
53732   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
53733
53734   /* If no error has occured and pPage has an overflow cell, call balance() 
53735   ** to redistribute the cells within the tree. Since balance() may move
53736   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
53737   ** variables.
53738   **
53739   ** Previous versions of SQLite called moveToRoot() to move the cursor
53740   ** back to the root page as balance() used to invalidate the contents
53741   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
53742   ** set the cursor state to "invalid". This makes common insert operations
53743   ** slightly faster.
53744   **
53745   ** There is a subtle but important optimization here too. When inserting
53746   ** multiple records into an intkey b-tree using a single cursor (as can
53747   ** happen while processing an "INSERT INTO ... SELECT" statement), it
53748   ** is advantageous to leave the cursor pointing to the last entry in
53749   ** the b-tree if possible. If the cursor is left pointing to the last
53750   ** entry in the table, and the next row inserted has an integer key
53751   ** larger than the largest existing key, it is possible to insert the
53752   ** row without seeking the cursor. This can be a big performance boost.
53753   */
53754   pCur->info.nSize = 0;
53755   pCur->validNKey = 0;
53756   if( rc==SQLITE_OK && pPage->nOverflow ){
53757     rc = balance(pCur);
53758
53759     /* Must make sure nOverflow is reset to zero even if the balance()
53760     ** fails. Internal data structure corruption will result otherwise. 
53761     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
53762     ** from trying to save the current position of the cursor.  */
53763     pCur->apPage[pCur->iPage]->nOverflow = 0;
53764     pCur->eState = CURSOR_INVALID;
53765   }
53766   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
53767
53768 end_insert:
53769   return rc;
53770 }
53771
53772 /*
53773 ** Delete the entry that the cursor is pointing to.  The cursor
53774 ** is left pointing at a arbitrary location.
53775 */
53776 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
53777   Btree *p = pCur->pBtree;
53778   BtShared *pBt = p->pBt;              
53779   int rc;                              /* Return code */
53780   MemPage *pPage;                      /* Page to delete cell from */
53781   unsigned char *pCell;                /* Pointer to cell to delete */
53782   int iCellIdx;                        /* Index of cell to delete */
53783   int iCellDepth;                      /* Depth of node containing pCell */ 
53784
53785   assert( cursorHoldsMutex(pCur) );
53786   assert( pBt->inTransaction==TRANS_WRITE );
53787   assert( !pBt->readOnly );
53788   assert( pCur->wrFlag );
53789   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53790   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
53791
53792   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
53793    || NEVER(pCur->eState!=CURSOR_VALID)
53794   ){
53795     return SQLITE_ERROR;  /* Something has gone awry. */
53796   }
53797
53798   /* If this is a delete operation to remove a row from a table b-tree,
53799   ** invalidate any incrblob cursors open on the row being deleted.  */
53800   if( pCur->pKeyInfo==0 ){
53801     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
53802   }
53803
53804   iCellDepth = pCur->iPage;
53805   iCellIdx = pCur->aiIdx[iCellDepth];
53806   pPage = pCur->apPage[iCellDepth];
53807   pCell = findCell(pPage, iCellIdx);
53808
53809   /* If the page containing the entry to delete is not a leaf page, move
53810   ** the cursor to the largest entry in the tree that is smaller than
53811   ** the entry being deleted. This cell will replace the cell being deleted
53812   ** from the internal node. The 'previous' entry is used for this instead
53813   ** of the 'next' entry, as the previous entry is always a part of the
53814   ** sub-tree headed by the child page of the cell being deleted. This makes
53815   ** balancing the tree following the delete operation easier.  */
53816   if( !pPage->leaf ){
53817     int notUsed;
53818     rc = sqlite3BtreePrevious(pCur, &notUsed);
53819     if( rc ) return rc;
53820   }
53821
53822   /* Save the positions of any other cursors open on this table before
53823   ** making any modifications. Make the page containing the entry to be 
53824   ** deleted writable. Then free any overflow pages associated with the 
53825   ** entry and finally remove the cell itself from within the page.  
53826   */
53827   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53828   if( rc ) return rc;
53829   rc = sqlite3PagerWrite(pPage->pDbPage);
53830   if( rc ) return rc;
53831   rc = clearCell(pPage, pCell);
53832   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
53833   if( rc ) return rc;
53834
53835   /* If the cell deleted was not located on a leaf page, then the cursor
53836   ** is currently pointing to the largest entry in the sub-tree headed
53837   ** by the child-page of the cell that was just deleted from an internal
53838   ** node. The cell from the leaf node needs to be moved to the internal
53839   ** node to replace the deleted cell.  */
53840   if( !pPage->leaf ){
53841     MemPage *pLeaf = pCur->apPage[pCur->iPage];
53842     int nCell;
53843     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
53844     unsigned char *pTmp;
53845
53846     pCell = findCell(pLeaf, pLeaf->nCell-1);
53847     nCell = cellSizePtr(pLeaf, pCell);
53848     assert( MX_CELL_SIZE(pBt) >= nCell );
53849
53850     allocateTempSpace(pBt);
53851     pTmp = pBt->pTmpSpace;
53852
53853     rc = sqlite3PagerWrite(pLeaf->pDbPage);
53854     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
53855     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
53856     if( rc ) return rc;
53857   }
53858
53859   /* Balance the tree. If the entry deleted was located on a leaf page,
53860   ** then the cursor still points to that page. In this case the first
53861   ** call to balance() repairs the tree, and the if(...) condition is
53862   ** never true.
53863   **
53864   ** Otherwise, if the entry deleted was on an internal node page, then
53865   ** pCur is pointing to the leaf page from which a cell was removed to
53866   ** replace the cell deleted from the internal node. This is slightly
53867   ** tricky as the leaf node may be underfull, and the internal node may
53868   ** be either under or overfull. In this case run the balancing algorithm
53869   ** on the leaf node first. If the balance proceeds far enough up the
53870   ** tree that we can be sure that any problem in the internal node has
53871   ** been corrected, so be it. Otherwise, after balancing the leaf node,
53872   ** walk the cursor up the tree to the internal node and balance it as 
53873   ** well.  */
53874   rc = balance(pCur);
53875   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
53876     while( pCur->iPage>iCellDepth ){
53877       releasePage(pCur->apPage[pCur->iPage--]);
53878     }
53879     rc = balance(pCur);
53880   }
53881
53882   if( rc==SQLITE_OK ){
53883     moveToRoot(pCur);
53884   }
53885   return rc;
53886 }
53887
53888 /*
53889 ** Create a new BTree table.  Write into *piTable the page
53890 ** number for the root page of the new table.
53891 **
53892 ** The type of type is determined by the flags parameter.  Only the
53893 ** following values of flags are currently in use.  Other values for
53894 ** flags might not work:
53895 **
53896 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
53897 **     BTREE_ZERODATA                  Used for SQL indices
53898 */
53899 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
53900   BtShared *pBt = p->pBt;
53901   MemPage *pRoot;
53902   Pgno pgnoRoot;
53903   int rc;
53904   int ptfFlags;          /* Page-type flage for the root page of new table */
53905
53906   assert( sqlite3BtreeHoldsMutex(p) );
53907   assert( pBt->inTransaction==TRANS_WRITE );
53908   assert( !pBt->readOnly );
53909
53910 #ifdef SQLITE_OMIT_AUTOVACUUM
53911   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
53912   if( rc ){
53913     return rc;
53914   }
53915 #else
53916   if( pBt->autoVacuum ){
53917     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
53918     MemPage *pPageMove; /* The page to move to. */
53919
53920     /* Creating a new table may probably require moving an existing database
53921     ** to make room for the new tables root page. In case this page turns
53922     ** out to be an overflow page, delete all overflow page-map caches
53923     ** held by open cursors.
53924     */
53925     invalidateAllOverflowCache(pBt);
53926
53927     /* Read the value of meta[3] from the database to determine where the
53928     ** root page of the new table should go. meta[3] is the largest root-page
53929     ** created so far, so the new root-page is (meta[3]+1).
53930     */
53931     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
53932     pgnoRoot++;
53933
53934     /* The new root-page may not be allocated on a pointer-map page, or the
53935     ** PENDING_BYTE page.
53936     */
53937     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
53938         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
53939       pgnoRoot++;
53940     }
53941     assert( pgnoRoot>=3 );
53942
53943     /* Allocate a page. The page that currently resides at pgnoRoot will
53944     ** be moved to the allocated page (unless the allocated page happens
53945     ** to reside at pgnoRoot).
53946     */
53947     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
53948     if( rc!=SQLITE_OK ){
53949       return rc;
53950     }
53951
53952     if( pgnoMove!=pgnoRoot ){
53953       /* pgnoRoot is the page that will be used for the root-page of
53954       ** the new table (assuming an error did not occur). But we were
53955       ** allocated pgnoMove. If required (i.e. if it was not allocated
53956       ** by extending the file), the current page at position pgnoMove
53957       ** is already journaled.
53958       */
53959       u8 eType = 0;
53960       Pgno iPtrPage = 0;
53961
53962       releasePage(pPageMove);
53963
53964       /* Move the page currently at pgnoRoot to pgnoMove. */
53965       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
53966       if( rc!=SQLITE_OK ){
53967         return rc;
53968       }
53969       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
53970       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
53971         rc = SQLITE_CORRUPT_BKPT;
53972       }
53973       if( rc!=SQLITE_OK ){
53974         releasePage(pRoot);
53975         return rc;
53976       }
53977       assert( eType!=PTRMAP_ROOTPAGE );
53978       assert( eType!=PTRMAP_FREEPAGE );
53979       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
53980       releasePage(pRoot);
53981
53982       /* Obtain the page at pgnoRoot */
53983       if( rc!=SQLITE_OK ){
53984         return rc;
53985       }
53986       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
53987       if( rc!=SQLITE_OK ){
53988         return rc;
53989       }
53990       rc = sqlite3PagerWrite(pRoot->pDbPage);
53991       if( rc!=SQLITE_OK ){
53992         releasePage(pRoot);
53993         return rc;
53994       }
53995     }else{
53996       pRoot = pPageMove;
53997     } 
53998
53999     /* Update the pointer-map and meta-data with the new root-page number. */
54000     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
54001     if( rc ){
54002       releasePage(pRoot);
54003       return rc;
54004     }
54005
54006     /* When the new root page was allocated, page 1 was made writable in
54007     ** order either to increase the database filesize, or to decrement the
54008     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
54009     */
54010     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54011     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54012     if( NEVER(rc) ){
54013       releasePage(pRoot);
54014       return rc;
54015     }
54016
54017   }else{
54018     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54019     if( rc ) return rc;
54020   }
54021 #endif
54022   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54023   if( createTabFlags & BTREE_INTKEY ){
54024     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54025   }else{
54026     ptfFlags = PTF_ZERODATA | PTF_LEAF;
54027   }
54028   zeroPage(pRoot, ptfFlags);
54029   sqlite3PagerUnref(pRoot->pDbPage);
54030   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54031   *piTable = (int)pgnoRoot;
54032   return SQLITE_OK;
54033 }
54034 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54035   int rc;
54036   sqlite3BtreeEnter(p);
54037   rc = btreeCreateTable(p, piTable, flags);
54038   sqlite3BtreeLeave(p);
54039   return rc;
54040 }
54041
54042 /*
54043 ** Erase the given database page and all its children.  Return
54044 ** the page to the freelist.
54045 */
54046 static int clearDatabasePage(
54047   BtShared *pBt,           /* The BTree that contains the table */
54048   Pgno pgno,               /* Page number to clear */
54049   int freePageFlag,        /* Deallocate page if true */
54050   int *pnChange            /* Add number of Cells freed to this counter */
54051 ){
54052   MemPage *pPage;
54053   int rc;
54054   unsigned char *pCell;
54055   int i;
54056
54057   assert( sqlite3_mutex_held(pBt->mutex) );
54058   if( pgno>btreePagecount(pBt) ){
54059     return SQLITE_CORRUPT_BKPT;
54060   }
54061
54062   rc = getAndInitPage(pBt, pgno, &pPage);
54063   if( rc ) return rc;
54064   for(i=0; i<pPage->nCell; i++){
54065     pCell = findCell(pPage, i);
54066     if( !pPage->leaf ){
54067       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54068       if( rc ) goto cleardatabasepage_out;
54069     }
54070     rc = clearCell(pPage, pCell);
54071     if( rc ) goto cleardatabasepage_out;
54072   }
54073   if( !pPage->leaf ){
54074     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54075     if( rc ) goto cleardatabasepage_out;
54076   }else if( pnChange ){
54077     assert( pPage->intKey );
54078     *pnChange += pPage->nCell;
54079   }
54080   if( freePageFlag ){
54081     freePage(pPage, &rc);
54082   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54083     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54084   }
54085
54086 cleardatabasepage_out:
54087   releasePage(pPage);
54088   return rc;
54089 }
54090
54091 /*
54092 ** Delete all information from a single table in the database.  iTable is
54093 ** the page number of the root of the table.  After this routine returns,
54094 ** the root page is empty, but still exists.
54095 **
54096 ** This routine will fail with SQLITE_LOCKED if there are any open
54097 ** read cursors on the table.  Open write cursors are moved to the
54098 ** root of the table.
54099 **
54100 ** If pnChange is not NULL, then table iTable must be an intkey table. The
54101 ** integer value pointed to by pnChange is incremented by the number of
54102 ** entries in the table.
54103 */
54104 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54105   int rc;
54106   BtShared *pBt = p->pBt;
54107   sqlite3BtreeEnter(p);
54108   assert( p->inTrans==TRANS_WRITE );
54109
54110   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54111   ** is the root of a table b-tree - if it is not, the following call is
54112   ** a no-op).  */
54113   invalidateIncrblobCursors(p, 0, 1);
54114
54115   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54116   if( SQLITE_OK==rc ){
54117     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54118   }
54119   sqlite3BtreeLeave(p);
54120   return rc;
54121 }
54122
54123 /*
54124 ** Erase all information in a table and add the root of the table to
54125 ** the freelist.  Except, the root of the principle table (the one on
54126 ** page 1) is never added to the freelist.
54127 **
54128 ** This routine will fail with SQLITE_LOCKED if there are any open
54129 ** cursors on the table.
54130 **
54131 ** If AUTOVACUUM is enabled and the page at iTable is not the last
54132 ** root page in the database file, then the last root page 
54133 ** in the database file is moved into the slot formerly occupied by
54134 ** iTable and that last slot formerly occupied by the last root page
54135 ** is added to the freelist instead of iTable.  In this say, all
54136 ** root pages are kept at the beginning of the database file, which
54137 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
54138 ** page number that used to be the last root page in the file before
54139 ** the move.  If no page gets moved, *piMoved is set to 0.
54140 ** The last root page is recorded in meta[3] and the value of
54141 ** meta[3] is updated by this procedure.
54142 */
54143 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54144   int rc;
54145   MemPage *pPage = 0;
54146   BtShared *pBt = p->pBt;
54147
54148   assert( sqlite3BtreeHoldsMutex(p) );
54149   assert( p->inTrans==TRANS_WRITE );
54150
54151   /* It is illegal to drop a table if any cursors are open on the
54152   ** database. This is because in auto-vacuum mode the backend may
54153   ** need to move another root-page to fill a gap left by the deleted
54154   ** root page. If an open cursor was using this page a problem would 
54155   ** occur.
54156   **
54157   ** This error is caught long before control reaches this point.
54158   */
54159   if( NEVER(pBt->pCursor) ){
54160     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54161     return SQLITE_LOCKED_SHAREDCACHE;
54162   }
54163
54164   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54165   if( rc ) return rc;
54166   rc = sqlite3BtreeClearTable(p, iTable, 0);
54167   if( rc ){
54168     releasePage(pPage);
54169     return rc;
54170   }
54171
54172   *piMoved = 0;
54173
54174   if( iTable>1 ){
54175 #ifdef SQLITE_OMIT_AUTOVACUUM
54176     freePage(pPage, &rc);
54177     releasePage(pPage);
54178 #else
54179     if( pBt->autoVacuum ){
54180       Pgno maxRootPgno;
54181       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54182
54183       if( iTable==maxRootPgno ){
54184         /* If the table being dropped is the table with the largest root-page
54185         ** number in the database, put the root page on the free list. 
54186         */
54187         freePage(pPage, &rc);
54188         releasePage(pPage);
54189         if( rc!=SQLITE_OK ){
54190           return rc;
54191         }
54192       }else{
54193         /* The table being dropped does not have the largest root-page
54194         ** number in the database. So move the page that does into the 
54195         ** gap left by the deleted root-page.
54196         */
54197         MemPage *pMove;
54198         releasePage(pPage);
54199         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54200         if( rc!=SQLITE_OK ){
54201           return rc;
54202         }
54203         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54204         releasePage(pMove);
54205         if( rc!=SQLITE_OK ){
54206           return rc;
54207         }
54208         pMove = 0;
54209         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54210         freePage(pMove, &rc);
54211         releasePage(pMove);
54212         if( rc!=SQLITE_OK ){
54213           return rc;
54214         }
54215         *piMoved = maxRootPgno;
54216       }
54217
54218       /* Set the new 'max-root-page' value in the database header. This
54219       ** is the old value less one, less one more if that happens to
54220       ** be a root-page number, less one again if that is the
54221       ** PENDING_BYTE_PAGE.
54222       */
54223       maxRootPgno--;
54224       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54225              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54226         maxRootPgno--;
54227       }
54228       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54229
54230       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54231     }else{
54232       freePage(pPage, &rc);
54233       releasePage(pPage);
54234     }
54235 #endif
54236   }else{
54237     /* If sqlite3BtreeDropTable was called on page 1.
54238     ** This really never should happen except in a corrupt
54239     ** database. 
54240     */
54241     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54242     releasePage(pPage);
54243   }
54244   return rc;  
54245 }
54246 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54247   int rc;
54248   sqlite3BtreeEnter(p);
54249   rc = btreeDropTable(p, iTable, piMoved);
54250   sqlite3BtreeLeave(p);
54251   return rc;
54252 }
54253
54254
54255 /*
54256 ** This function may only be called if the b-tree connection already
54257 ** has a read or write transaction open on the database.
54258 **
54259 ** Read the meta-information out of a database file.  Meta[0]
54260 ** is the number of free pages currently in the database.  Meta[1]
54261 ** through meta[15] are available for use by higher layers.  Meta[0]
54262 ** is read-only, the others are read/write.
54263 ** 
54264 ** The schema layer numbers meta values differently.  At the schema
54265 ** layer (and the SetCookie and ReadCookie opcodes) the number of
54266 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
54267 */
54268 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54269   BtShared *pBt = p->pBt;
54270
54271   sqlite3BtreeEnter(p);
54272   assert( p->inTrans>TRANS_NONE );
54273   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54274   assert( pBt->pPage1 );
54275   assert( idx>=0 && idx<=15 );
54276
54277   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54278
54279   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54280   ** database, mark the database as read-only.  */
54281 #ifdef SQLITE_OMIT_AUTOVACUUM
54282   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54283 #endif
54284
54285   sqlite3BtreeLeave(p);
54286 }
54287
54288 /*
54289 ** Write meta-information back into the database.  Meta[0] is
54290 ** read-only and may not be written.
54291 */
54292 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54293   BtShared *pBt = p->pBt;
54294   unsigned char *pP1;
54295   int rc;
54296   assert( idx>=1 && idx<=15 );
54297   sqlite3BtreeEnter(p);
54298   assert( p->inTrans==TRANS_WRITE );
54299   assert( pBt->pPage1!=0 );
54300   pP1 = pBt->pPage1->aData;
54301   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54302   if( rc==SQLITE_OK ){
54303     put4byte(&pP1[36 + idx*4], iMeta);
54304 #ifndef SQLITE_OMIT_AUTOVACUUM
54305     if( idx==BTREE_INCR_VACUUM ){
54306       assert( pBt->autoVacuum || iMeta==0 );
54307       assert( iMeta==0 || iMeta==1 );
54308       pBt->incrVacuum = (u8)iMeta;
54309     }
54310 #endif
54311   }
54312   sqlite3BtreeLeave(p);
54313   return rc;
54314 }
54315
54316 #ifndef SQLITE_OMIT_BTREECOUNT
54317 /*
54318 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
54319 ** number of entries in the b-tree and write the result to *pnEntry.
54320 **
54321 ** SQLITE_OK is returned if the operation is successfully executed. 
54322 ** Otherwise, if an error is encountered (i.e. an IO error or database
54323 ** corruption) an SQLite error code is returned.
54324 */
54325 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54326   i64 nEntry = 0;                      /* Value to return in *pnEntry */
54327   int rc;                              /* Return code */
54328   rc = moveToRoot(pCur);
54329
54330   /* Unless an error occurs, the following loop runs one iteration for each
54331   ** page in the B-Tree structure (not including overflow pages). 
54332   */
54333   while( rc==SQLITE_OK ){
54334     int iIdx;                          /* Index of child node in parent */
54335     MemPage *pPage;                    /* Current page of the b-tree */
54336
54337     /* If this is a leaf page or the tree is not an int-key tree, then 
54338     ** this page contains countable entries. Increment the entry counter
54339     ** accordingly.
54340     */
54341     pPage = pCur->apPage[pCur->iPage];
54342     if( pPage->leaf || !pPage->intKey ){
54343       nEntry += pPage->nCell;
54344     }
54345
54346     /* pPage is a leaf node. This loop navigates the cursor so that it 
54347     ** points to the first interior cell that it points to the parent of
54348     ** the next page in the tree that has not yet been visited. The
54349     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54350     ** of the page, or to the number of cells in the page if the next page
54351     ** to visit is the right-child of its parent.
54352     **
54353     ** If all pages in the tree have been visited, return SQLITE_OK to the
54354     ** caller.
54355     */
54356     if( pPage->leaf ){
54357       do {
54358         if( pCur->iPage==0 ){
54359           /* All pages of the b-tree have been visited. Return successfully. */
54360           *pnEntry = nEntry;
54361           return SQLITE_OK;
54362         }
54363         moveToParent(pCur);
54364       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54365
54366       pCur->aiIdx[pCur->iPage]++;
54367       pPage = pCur->apPage[pCur->iPage];
54368     }
54369
54370     /* Descend to the child node of the cell that the cursor currently 
54371     ** points at. This is the right-child if (iIdx==pPage->nCell).
54372     */
54373     iIdx = pCur->aiIdx[pCur->iPage];
54374     if( iIdx==pPage->nCell ){
54375       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54376     }else{
54377       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54378     }
54379   }
54380
54381   /* An error has occurred. Return an error code. */
54382   return rc;
54383 }
54384 #endif
54385
54386 /*
54387 ** Return the pager associated with a BTree.  This routine is used for
54388 ** testing and debugging only.
54389 */
54390 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54391   return p->pBt->pPager;
54392 }
54393
54394 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54395 /*
54396 ** Append a message to the error message string.
54397 */
54398 static void checkAppendMsg(
54399   IntegrityCk *pCheck,
54400   char *zMsg1,
54401   const char *zFormat,
54402   ...
54403 ){
54404   va_list ap;
54405   if( !pCheck->mxErr ) return;
54406   pCheck->mxErr--;
54407   pCheck->nErr++;
54408   va_start(ap, zFormat);
54409   if( pCheck->errMsg.nChar ){
54410     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54411   }
54412   if( zMsg1 ){
54413     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54414   }
54415   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54416   va_end(ap);
54417   if( pCheck->errMsg.mallocFailed ){
54418     pCheck->mallocFailed = 1;
54419   }
54420 }
54421 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54422
54423 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54424 /*
54425 ** Add 1 to the reference count for page iPage.  If this is the second
54426 ** reference to the page, add an error message to pCheck->zErrMsg.
54427 ** Return 1 if there are 2 ore more references to the page and 0 if
54428 ** if this is the first reference to the page.
54429 **
54430 ** Also check that the page number is in bounds.
54431 */
54432 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54433   if( iPage==0 ) return 1;
54434   if( iPage>pCheck->nPage ){
54435     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54436     return 1;
54437   }
54438   if( pCheck->anRef[iPage]==1 ){
54439     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54440     return 1;
54441   }
54442   return  (pCheck->anRef[iPage]++)>1;
54443 }
54444
54445 #ifndef SQLITE_OMIT_AUTOVACUUM
54446 /*
54447 ** Check that the entry in the pointer-map for page iChild maps to 
54448 ** page iParent, pointer type ptrType. If not, append an error message
54449 ** to pCheck.
54450 */
54451 static void checkPtrmap(
54452   IntegrityCk *pCheck,   /* Integrity check context */
54453   Pgno iChild,           /* Child page number */
54454   u8 eType,              /* Expected pointer map type */
54455   Pgno iParent,          /* Expected pointer map parent page number */
54456   char *zContext         /* Context description (used for error msg) */
54457 ){
54458   int rc;
54459   u8 ePtrmapType;
54460   Pgno iPtrmapParent;
54461
54462   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
54463   if( rc!=SQLITE_OK ){
54464     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
54465     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
54466     return;
54467   }
54468
54469   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
54470     checkAppendMsg(pCheck, zContext, 
54471       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
54472       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
54473   }
54474 }
54475 #endif
54476
54477 /*
54478 ** Check the integrity of the freelist or of an overflow page list.
54479 ** Verify that the number of pages on the list is N.
54480 */
54481 static void checkList(
54482   IntegrityCk *pCheck,  /* Integrity checking context */
54483   int isFreeList,       /* True for a freelist.  False for overflow page list */
54484   int iPage,            /* Page number for first page in the list */
54485   int N,                /* Expected number of pages in the list */
54486   char *zContext        /* Context for error messages */
54487 ){
54488   int i;
54489   int expected = N;
54490   int iFirst = iPage;
54491   while( N-- > 0 && pCheck->mxErr ){
54492     DbPage *pOvflPage;
54493     unsigned char *pOvflData;
54494     if( iPage<1 ){
54495       checkAppendMsg(pCheck, zContext,
54496          "%d of %d pages missing from overflow list starting at %d",
54497           N+1, expected, iFirst);
54498       break;
54499     }
54500     if( checkRef(pCheck, iPage, zContext) ) break;
54501     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
54502       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
54503       break;
54504     }
54505     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
54506     if( isFreeList ){
54507       int n = get4byte(&pOvflData[4]);
54508 #ifndef SQLITE_OMIT_AUTOVACUUM
54509       if( pCheck->pBt->autoVacuum ){
54510         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
54511       }
54512 #endif
54513       if( n>(int)pCheck->pBt->usableSize/4-2 ){
54514         checkAppendMsg(pCheck, zContext,
54515            "freelist leaf count too big on page %d", iPage);
54516         N--;
54517       }else{
54518         for(i=0; i<n; i++){
54519           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
54520 #ifndef SQLITE_OMIT_AUTOVACUUM
54521           if( pCheck->pBt->autoVacuum ){
54522             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
54523           }
54524 #endif
54525           checkRef(pCheck, iFreePage, zContext);
54526         }
54527         N -= n;
54528       }
54529     }
54530 #ifndef SQLITE_OMIT_AUTOVACUUM
54531     else{
54532       /* If this database supports auto-vacuum and iPage is not the last
54533       ** page in this overflow list, check that the pointer-map entry for
54534       ** the following page matches iPage.
54535       */
54536       if( pCheck->pBt->autoVacuum && N>0 ){
54537         i = get4byte(pOvflData);
54538         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
54539       }
54540     }
54541 #endif
54542     iPage = get4byte(pOvflData);
54543     sqlite3PagerUnref(pOvflPage);
54544   }
54545 }
54546 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54547
54548 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54549 /*
54550 ** Do various sanity checks on a single page of a tree.  Return
54551 ** the tree depth.  Root pages return 0.  Parents of root pages
54552 ** return 1, and so forth.
54553 ** 
54554 ** These checks are done:
54555 **
54556 **      1.  Make sure that cells and freeblocks do not overlap
54557 **          but combine to completely cover the page.
54558 **  NO  2.  Make sure cell keys are in order.
54559 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
54560 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
54561 **      5.  Check the integrity of overflow pages.
54562 **      6.  Recursively call checkTreePage on all children.
54563 **      7.  Verify that the depth of all children is the same.
54564 **      8.  Make sure this page is at least 33% full or else it is
54565 **          the root of the tree.
54566 */
54567 static int checkTreePage(
54568   IntegrityCk *pCheck,  /* Context for the sanity check */
54569   int iPage,            /* Page number of the page to check */
54570   char *zParentContext, /* Parent context */
54571   i64 *pnParentMinKey, 
54572   i64 *pnParentMaxKey
54573 ){
54574   MemPage *pPage;
54575   int i, rc, depth, d2, pgno, cnt;
54576   int hdr, cellStart;
54577   int nCell;
54578   u8 *data;
54579   BtShared *pBt;
54580   int usableSize;
54581   char zContext[100];
54582   char *hit = 0;
54583   i64 nMinKey = 0;
54584   i64 nMaxKey = 0;
54585
54586   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
54587
54588   /* Check that the page exists
54589   */
54590   pBt = pCheck->pBt;
54591   usableSize = pBt->usableSize;
54592   if( iPage==0 ) return 0;
54593   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
54594   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
54595     checkAppendMsg(pCheck, zContext,
54596        "unable to get the page. error code=%d", rc);
54597     return 0;
54598   }
54599
54600   /* Clear MemPage.isInit to make sure the corruption detection code in
54601   ** btreeInitPage() is executed.  */
54602   pPage->isInit = 0;
54603   if( (rc = btreeInitPage(pPage))!=0 ){
54604     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
54605     checkAppendMsg(pCheck, zContext, 
54606                    "btreeInitPage() returns error code %d", rc);
54607     releasePage(pPage);
54608     return 0;
54609   }
54610
54611   /* Check out all the cells.
54612   */
54613   depth = 0;
54614   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
54615     u8 *pCell;
54616     u32 sz;
54617     CellInfo info;
54618
54619     /* Check payload overflow pages
54620     */
54621     sqlite3_snprintf(sizeof(zContext), zContext,
54622              "On tree page %d cell %d: ", iPage, i);
54623     pCell = findCell(pPage,i);
54624     btreeParseCellPtr(pPage, pCell, &info);
54625     sz = info.nData;
54626     if( !pPage->intKey ) sz += (int)info.nKey;
54627     /* For intKey pages, check that the keys are in order.
54628     */
54629     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
54630     else{
54631       if( info.nKey <= nMaxKey ){
54632         checkAppendMsg(pCheck, zContext, 
54633             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
54634       }
54635       nMaxKey = info.nKey;
54636     }
54637     assert( sz==info.nPayload );
54638     if( (sz>info.nLocal) 
54639      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
54640     ){
54641       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
54642       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
54643 #ifndef SQLITE_OMIT_AUTOVACUUM
54644       if( pBt->autoVacuum ){
54645         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
54646       }
54647 #endif
54648       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
54649     }
54650
54651     /* Check sanity of left child page.
54652     */
54653     if( !pPage->leaf ){
54654       pgno = get4byte(pCell);
54655 #ifndef SQLITE_OMIT_AUTOVACUUM
54656       if( pBt->autoVacuum ){
54657         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54658       }
54659 #endif
54660       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
54661       if( i>0 && d2!=depth ){
54662         checkAppendMsg(pCheck, zContext, "Child page depth differs");
54663       }
54664       depth = d2;
54665     }
54666   }
54667
54668   if( !pPage->leaf ){
54669     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54670     sqlite3_snprintf(sizeof(zContext), zContext, 
54671                      "On page %d at right child: ", iPage);
54672 #ifndef SQLITE_OMIT_AUTOVACUUM
54673     if( pBt->autoVacuum ){
54674       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54675     }
54676 #endif
54677     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
54678   }
54679  
54680   /* For intKey leaf pages, check that the min/max keys are in order
54681   ** with any left/parent/right pages.
54682   */
54683   if( pPage->leaf && pPage->intKey ){
54684     /* if we are a left child page */
54685     if( pnParentMinKey ){
54686       /* if we are the left most child page */
54687       if( !pnParentMaxKey ){
54688         if( nMaxKey > *pnParentMinKey ){
54689           checkAppendMsg(pCheck, zContext, 
54690               "Rowid %lld out of order (max larger than parent min of %lld)",
54691               nMaxKey, *pnParentMinKey);
54692         }
54693       }else{
54694         if( nMinKey <= *pnParentMinKey ){
54695           checkAppendMsg(pCheck, zContext, 
54696               "Rowid %lld out of order (min less than parent min of %lld)",
54697               nMinKey, *pnParentMinKey);
54698         }
54699         if( nMaxKey > *pnParentMaxKey ){
54700           checkAppendMsg(pCheck, zContext, 
54701               "Rowid %lld out of order (max larger than parent max of %lld)",
54702               nMaxKey, *pnParentMaxKey);
54703         }
54704         *pnParentMinKey = nMaxKey;
54705       }
54706     /* else if we're a right child page */
54707     } else if( pnParentMaxKey ){
54708       if( nMinKey <= *pnParentMaxKey ){
54709         checkAppendMsg(pCheck, zContext, 
54710             "Rowid %lld out of order (min less than parent max of %lld)",
54711             nMinKey, *pnParentMaxKey);
54712       }
54713     }
54714   }
54715
54716   /* Check for complete coverage of the page
54717   */
54718   data = pPage->aData;
54719   hdr = pPage->hdrOffset;
54720   hit = sqlite3PageMalloc( pBt->pageSize );
54721   if( hit==0 ){
54722     pCheck->mallocFailed = 1;
54723   }else{
54724     int contentOffset = get2byteNotZero(&data[hdr+5]);
54725     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
54726     memset(hit+contentOffset, 0, usableSize-contentOffset);
54727     memset(hit, 1, contentOffset);
54728     nCell = get2byte(&data[hdr+3]);
54729     cellStart = hdr + 12 - 4*pPage->leaf;
54730     for(i=0; i<nCell; i++){
54731       int pc = get2byte(&data[cellStart+i*2]);
54732       u32 size = 65536;
54733       int j;
54734       if( pc<=usableSize-4 ){
54735         size = cellSizePtr(pPage, &data[pc]);
54736       }
54737       if( (int)(pc+size-1)>=usableSize ){
54738         checkAppendMsg(pCheck, 0, 
54739             "Corruption detected in cell %d on page %d",i,iPage);
54740       }else{
54741         for(j=pc+size-1; j>=pc; j--) hit[j]++;
54742       }
54743     }
54744     i = get2byte(&data[hdr+1]);
54745     while( i>0 ){
54746       int size, j;
54747       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
54748       size = get2byte(&data[i+2]);
54749       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
54750       for(j=i+size-1; j>=i; j--) hit[j]++;
54751       j = get2byte(&data[i]);
54752       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
54753       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
54754       i = j;
54755     }
54756     for(i=cnt=0; i<usableSize; i++){
54757       if( hit[i]==0 ){
54758         cnt++;
54759       }else if( hit[i]>1 ){
54760         checkAppendMsg(pCheck, 0,
54761           "Multiple uses for byte %d of page %d", i, iPage);
54762         break;
54763       }
54764     }
54765     if( cnt!=data[hdr+7] ){
54766       checkAppendMsg(pCheck, 0, 
54767           "Fragmentation of %d bytes reported as %d on page %d",
54768           cnt, data[hdr+7], iPage);
54769     }
54770   }
54771   sqlite3PageFree(hit);
54772   releasePage(pPage);
54773   return depth+1;
54774 }
54775 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54776
54777 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54778 /*
54779 ** This routine does a complete check of the given BTree file.  aRoot[] is
54780 ** an array of pages numbers were each page number is the root page of
54781 ** a table.  nRoot is the number of entries in aRoot.
54782 **
54783 ** A read-only or read-write transaction must be opened before calling
54784 ** this function.
54785 **
54786 ** Write the number of error seen in *pnErr.  Except for some memory
54787 ** allocation errors,  an error message held in memory obtained from
54788 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
54789 ** returned.  If a memory allocation error occurs, NULL is returned.
54790 */
54791 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
54792   Btree *p,     /* The btree to be checked */
54793   int *aRoot,   /* An array of root pages numbers for individual trees */
54794   int nRoot,    /* Number of entries in aRoot[] */
54795   int mxErr,    /* Stop reporting errors after this many */
54796   int *pnErr    /* Write number of errors seen to this variable */
54797 ){
54798   Pgno i;
54799   int nRef;
54800   IntegrityCk sCheck;
54801   BtShared *pBt = p->pBt;
54802   char zErr[100];
54803
54804   sqlite3BtreeEnter(p);
54805   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
54806   nRef = sqlite3PagerRefcount(pBt->pPager);
54807   sCheck.pBt = pBt;
54808   sCheck.pPager = pBt->pPager;
54809   sCheck.nPage = btreePagecount(sCheck.pBt);
54810   sCheck.mxErr = mxErr;
54811   sCheck.nErr = 0;
54812   sCheck.mallocFailed = 0;
54813   *pnErr = 0;
54814   if( sCheck.nPage==0 ){
54815     sqlite3BtreeLeave(p);
54816     return 0;
54817   }
54818   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
54819   if( !sCheck.anRef ){
54820     *pnErr = 1;
54821     sqlite3BtreeLeave(p);
54822     return 0;
54823   }
54824   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
54825   i = PENDING_BYTE_PAGE(pBt);
54826   if( i<=sCheck.nPage ){
54827     sCheck.anRef[i] = 1;
54828   }
54829   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
54830   sCheck.errMsg.useMalloc = 2;
54831
54832   /* Check the integrity of the freelist
54833   */
54834   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
54835             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
54836
54837   /* Check all the tables.
54838   */
54839   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
54840     if( aRoot[i]==0 ) continue;
54841 #ifndef SQLITE_OMIT_AUTOVACUUM
54842     if( pBt->autoVacuum && aRoot[i]>1 ){
54843       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
54844     }
54845 #endif
54846     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
54847   }
54848
54849   /* Make sure every page in the file is referenced
54850   */
54851   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
54852 #ifdef SQLITE_OMIT_AUTOVACUUM
54853     if( sCheck.anRef[i]==0 ){
54854       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54855     }
54856 #else
54857     /* If the database supports auto-vacuum, make sure no tables contain
54858     ** references to pointer-map pages.
54859     */
54860     if( sCheck.anRef[i]==0 && 
54861        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
54862       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
54863     }
54864     if( sCheck.anRef[i]!=0 && 
54865        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
54866       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
54867     }
54868 #endif
54869   }
54870
54871   /* Make sure this analysis did not leave any unref() pages.
54872   ** This is an internal consistency check; an integrity check
54873   ** of the integrity check.
54874   */
54875   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
54876     checkAppendMsg(&sCheck, 0, 
54877       "Outstanding page count goes from %d to %d during this analysis",
54878       nRef, sqlite3PagerRefcount(pBt->pPager)
54879     );
54880   }
54881
54882   /* Clean  up and report errors.
54883   */
54884   sqlite3BtreeLeave(p);
54885   sqlite3_free(sCheck.anRef);
54886   if( sCheck.mallocFailed ){
54887     sqlite3StrAccumReset(&sCheck.errMsg);
54888     *pnErr = sCheck.nErr+1;
54889     return 0;
54890   }
54891   *pnErr = sCheck.nErr;
54892   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
54893   return sqlite3StrAccumFinish(&sCheck.errMsg);
54894 }
54895 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54896
54897 /*
54898 ** Return the full pathname of the underlying database file.
54899 **
54900 ** The pager filename is invariant as long as the pager is
54901 ** open so it is safe to access without the BtShared mutex.
54902 */
54903 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
54904   assert( p->pBt->pPager!=0 );
54905   return sqlite3PagerFilename(p->pBt->pPager);
54906 }
54907
54908 /*
54909 ** Return the pathname of the journal file for this database. The return
54910 ** value of this routine is the same regardless of whether the journal file
54911 ** has been created or not.
54912 **
54913 ** The pager journal filename is invariant as long as the pager is
54914 ** open so it is safe to access without the BtShared mutex.
54915 */
54916 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
54917   assert( p->pBt->pPager!=0 );
54918   return sqlite3PagerJournalname(p->pBt->pPager);
54919 }
54920
54921 /*
54922 ** Return non-zero if a transaction is active.
54923 */
54924 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
54925   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
54926   return (p && (p->inTrans==TRANS_WRITE));
54927 }
54928
54929 #ifndef SQLITE_OMIT_WAL
54930 /*
54931 ** Run a checkpoint on the Btree passed as the first argument.
54932 **
54933 ** Return SQLITE_LOCKED if this or any other connection has an open 
54934 ** transaction on the shared-cache the argument Btree is connected to.
54935 **
54936 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
54937 */
54938 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
54939   int rc = SQLITE_OK;
54940   if( p ){
54941     BtShared *pBt = p->pBt;
54942     sqlite3BtreeEnter(p);
54943     if( pBt->inTransaction!=TRANS_NONE ){
54944       rc = SQLITE_LOCKED;
54945     }else{
54946       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
54947     }
54948     sqlite3BtreeLeave(p);
54949   }
54950   return rc;
54951 }
54952 #endif
54953
54954 /*
54955 ** Return non-zero if a read (or write) transaction is active.
54956 */
54957 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
54958   assert( p );
54959   assert( sqlite3_mutex_held(p->db->mutex) );
54960   return p->inTrans!=TRANS_NONE;
54961 }
54962
54963 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
54964   assert( p );
54965   assert( sqlite3_mutex_held(p->db->mutex) );
54966   return p->nBackup!=0;
54967 }
54968
54969 /*
54970 ** This function returns a pointer to a blob of memory associated with
54971 ** a single shared-btree. The memory is used by client code for its own
54972 ** purposes (for example, to store a high-level schema associated with 
54973 ** the shared-btree). The btree layer manages reference counting issues.
54974 **
54975 ** The first time this is called on a shared-btree, nBytes bytes of memory
54976 ** are allocated, zeroed, and returned to the caller. For each subsequent 
54977 ** call the nBytes parameter is ignored and a pointer to the same blob
54978 ** of memory returned. 
54979 **
54980 ** If the nBytes parameter is 0 and the blob of memory has not yet been
54981 ** allocated, a null pointer is returned. If the blob has already been
54982 ** allocated, it is returned as normal.
54983 **
54984 ** Just before the shared-btree is closed, the function passed as the 
54985 ** xFree argument when the memory allocation was made is invoked on the 
54986 ** blob of allocated memory. The xFree function should not call sqlite3_free()
54987 ** on the memory, the btree layer does that.
54988 */
54989 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
54990   BtShared *pBt = p->pBt;
54991   sqlite3BtreeEnter(p);
54992   if( !pBt->pSchema && nBytes ){
54993     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
54994     pBt->xFreeSchema = xFree;
54995   }
54996   sqlite3BtreeLeave(p);
54997   return pBt->pSchema;
54998 }
54999
55000 /*
55001 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
55002 ** btree as the argument handle holds an exclusive lock on the 
55003 ** sqlite_master table. Otherwise SQLITE_OK.
55004 */
55005 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
55006   int rc;
55007   assert( sqlite3_mutex_held(p->db->mutex) );
55008   sqlite3BtreeEnter(p);
55009   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55010   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55011   sqlite3BtreeLeave(p);
55012   return rc;
55013 }
55014
55015
55016 #ifndef SQLITE_OMIT_SHARED_CACHE
55017 /*
55018 ** Obtain a lock on the table whose root page is iTab.  The
55019 ** lock is a write lock if isWritelock is true or a read lock
55020 ** if it is false.
55021 */
55022 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55023   int rc = SQLITE_OK;
55024   assert( p->inTrans!=TRANS_NONE );
55025   if( p->sharable ){
55026     u8 lockType = READ_LOCK + isWriteLock;
55027     assert( READ_LOCK+1==WRITE_LOCK );
55028     assert( isWriteLock==0 || isWriteLock==1 );
55029
55030     sqlite3BtreeEnter(p);
55031     rc = querySharedCacheTableLock(p, iTab, lockType);
55032     if( rc==SQLITE_OK ){
55033       rc = setSharedCacheTableLock(p, iTab, lockType);
55034     }
55035     sqlite3BtreeLeave(p);
55036   }
55037   return rc;
55038 }
55039 #endif
55040
55041 #ifndef SQLITE_OMIT_INCRBLOB
55042 /*
55043 ** Argument pCsr must be a cursor opened for writing on an 
55044 ** INTKEY table currently pointing at a valid table entry. 
55045 ** This function modifies the data stored as part of that entry.
55046 **
55047 ** Only the data content may only be modified, it is not possible to 
55048 ** change the length of the data stored. If this function is called with
55049 ** parameters that attempt to write past the end of the existing data,
55050 ** no modifications are made and SQLITE_CORRUPT is returned.
55051 */
55052 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55053   int rc;
55054   assert( cursorHoldsMutex(pCsr) );
55055   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55056   assert( pCsr->isIncrblobHandle );
55057
55058   rc = restoreCursorPosition(pCsr);
55059   if( rc!=SQLITE_OK ){
55060     return rc;
55061   }
55062   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55063   if( pCsr->eState!=CURSOR_VALID ){
55064     return SQLITE_ABORT;
55065   }
55066
55067   /* Check some assumptions: 
55068   **   (a) the cursor is open for writing,
55069   **   (b) there is a read/write transaction open,
55070   **   (c) the connection holds a write-lock on the table (if required),
55071   **   (d) there are no conflicting read-locks, and
55072   **   (e) the cursor points at a valid row of an intKey table.
55073   */
55074   if( !pCsr->wrFlag ){
55075     return SQLITE_READONLY;
55076   }
55077   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55078   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55079   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55080   assert( pCsr->apPage[pCsr->iPage]->intKey );
55081
55082   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55083 }
55084
55085 /* 
55086 ** Set a flag on this cursor to cache the locations of pages from the 
55087 ** overflow list for the current row. This is used by cursors opened
55088 ** for incremental blob IO only.
55089 **
55090 ** This function sets a flag only. The actual page location cache
55091 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
55092 ** accessPayload() (the worker function for sqlite3BtreeData() and
55093 ** sqlite3BtreePutData()).
55094 */
55095 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55096   assert( cursorHoldsMutex(pCur) );
55097   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55098   invalidateOverflowCache(pCur);
55099   pCur->isIncrblobHandle = 1;
55100 }
55101 #endif
55102
55103 /*
55104 ** Set both the "read version" (single byte at byte offset 18) and 
55105 ** "write version" (single byte at byte offset 19) fields in the database
55106 ** header to iVersion.
55107 */
55108 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55109   BtShared *pBt = pBtree->pBt;
55110   int rc;                         /* Return code */
55111  
55112   assert( pBtree->inTrans==TRANS_NONE );
55113   assert( iVersion==1 || iVersion==2 );
55114
55115   /* If setting the version fields to 1, do not automatically open the
55116   ** WAL connection, even if the version fields are currently set to 2.
55117   */
55118   pBt->doNotUseWAL = (u8)(iVersion==1);
55119
55120   rc = sqlite3BtreeBeginTrans(pBtree, 0);
55121   if( rc==SQLITE_OK ){
55122     u8 *aData = pBt->pPage1->aData;
55123     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55124       rc = sqlite3BtreeBeginTrans(pBtree, 2);
55125       if( rc==SQLITE_OK ){
55126         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55127         if( rc==SQLITE_OK ){
55128           aData[18] = (u8)iVersion;
55129           aData[19] = (u8)iVersion;
55130         }
55131       }
55132     }
55133   }
55134
55135   pBt->doNotUseWAL = 0;
55136   return rc;
55137 }
55138
55139 /************** End of btree.c ***********************************************/
55140 /************** Begin file backup.c ******************************************/
55141 /*
55142 ** 2009 January 28
55143 **
55144 ** The author disclaims copyright to this source code.  In place of
55145 ** a legal notice, here is a blessing:
55146 **
55147 **    May you do good and not evil.
55148 **    May you find forgiveness for yourself and forgive others.
55149 **    May you share freely, never taking more than you give.
55150 **
55151 *************************************************************************
55152 ** This file contains the implementation of the sqlite3_backup_XXX() 
55153 ** API functions and the related features.
55154 */
55155
55156 /* Macro to find the minimum of two numeric values.
55157 */
55158 #ifndef MIN
55159 # define MIN(x,y) ((x)<(y)?(x):(y))
55160 #endif
55161
55162 /*
55163 ** Structure allocated for each backup operation.
55164 */
55165 struct sqlite3_backup {
55166   sqlite3* pDestDb;        /* Destination database handle */
55167   Btree *pDest;            /* Destination b-tree file */
55168   u32 iDestSchema;         /* Original schema cookie in destination */
55169   int bDestLocked;         /* True once a write-transaction is open on pDest */
55170
55171   Pgno iNext;              /* Page number of the next source page to copy */
55172   sqlite3* pSrcDb;         /* Source database handle */
55173   Btree *pSrc;             /* Source b-tree file */
55174
55175   int rc;                  /* Backup process error code */
55176
55177   /* These two variables are set by every call to backup_step(). They are
55178   ** read by calls to backup_remaining() and backup_pagecount().
55179   */
55180   Pgno nRemaining;         /* Number of pages left to copy */
55181   Pgno nPagecount;         /* Total number of pages to copy */
55182
55183   int isAttached;          /* True once backup has been registered with pager */
55184   sqlite3_backup *pNext;   /* Next backup associated with source pager */
55185 };
55186
55187 /*
55188 ** THREAD SAFETY NOTES:
55189 **
55190 **   Once it has been created using backup_init(), a single sqlite3_backup
55191 **   structure may be accessed via two groups of thread-safe entry points:
55192 **
55193 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
55194 **       backup_finish(). Both these functions obtain the source database
55195 **       handle mutex and the mutex associated with the source BtShared 
55196 **       structure, in that order.
55197 **
55198 **     * Via the BackupUpdate() and BackupRestart() functions, which are
55199 **       invoked by the pager layer to report various state changes in
55200 **       the page cache associated with the source database. The mutex
55201 **       associated with the source database BtShared structure will always 
55202 **       be held when either of these functions are invoked.
55203 **
55204 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
55205 **   backup_pagecount() are not thread-safe functions. If they are called
55206 **   while some other thread is calling backup_step() or backup_finish(),
55207 **   the values returned may be invalid. There is no way for a call to
55208 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55209 **   or backup_pagecount().
55210 **
55211 **   Depending on the SQLite configuration, the database handles and/or
55212 **   the Btree objects may have their own mutexes that require locking.
55213 **   Non-sharable Btrees (in-memory databases for example), do not have
55214 **   associated mutexes.
55215 */
55216
55217 /*
55218 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55219 ** in connection handle pDb. If such a database cannot be found, return
55220 ** a NULL pointer and write an error message to pErrorDb.
55221 **
55222 ** If the "temp" database is requested, it may need to be opened by this 
55223 ** function. If an error occurs while doing so, return 0 and write an 
55224 ** error message to pErrorDb.
55225 */
55226 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55227   int i = sqlite3FindDbName(pDb, zDb);
55228
55229   if( i==1 ){
55230     Parse *pParse;
55231     int rc = 0;
55232     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55233     if( pParse==0 ){
55234       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55235       rc = SQLITE_NOMEM;
55236     }else{
55237       pParse->db = pDb;
55238       if( sqlite3OpenTempDatabase(pParse) ){
55239         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55240         rc = SQLITE_ERROR;
55241       }
55242       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55243       sqlite3StackFree(pErrorDb, pParse);
55244     }
55245     if( rc ){
55246       return 0;
55247     }
55248   }
55249
55250   if( i<0 ){
55251     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55252     return 0;
55253   }
55254
55255   return pDb->aDb[i].pBt;
55256 }
55257
55258 /*
55259 ** Attempt to set the page size of the destination to match the page size
55260 ** of the source.
55261 */
55262 static int setDestPgsz(sqlite3_backup *p){
55263   int rc;
55264   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55265   return rc;
55266 }
55267
55268 /*
55269 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
55270 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55271 ** a pointer to the new sqlite3_backup object.
55272 **
55273 ** If an error occurs, NULL is returned and an error code and error message
55274 ** stored in database handle pDestDb.
55275 */
55276 SQLITE_API sqlite3_backup *sqlite3_backup_init(
55277   sqlite3* pDestDb,                     /* Database to write to */
55278   const char *zDestDb,                  /* Name of database within pDestDb */
55279   sqlite3* pSrcDb,                      /* Database connection to read from */
55280   const char *zSrcDb                    /* Name of database within pSrcDb */
55281 ){
55282   sqlite3_backup *p;                    /* Value to return */
55283
55284   /* Lock the source database handle. The destination database
55285   ** handle is not locked in this routine, but it is locked in
55286   ** sqlite3_backup_step(). The user is required to ensure that no
55287   ** other thread accesses the destination handle for the duration
55288   ** of the backup operation.  Any attempt to use the destination
55289   ** database connection while a backup is in progress may cause
55290   ** a malfunction or a deadlock.
55291   */
55292   sqlite3_mutex_enter(pSrcDb->mutex);
55293   sqlite3_mutex_enter(pDestDb->mutex);
55294
55295   if( pSrcDb==pDestDb ){
55296     sqlite3Error(
55297         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55298     );
55299     p = 0;
55300   }else {
55301     /* Allocate space for a new sqlite3_backup object...
55302     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55303     ** call to sqlite3_backup_init() and is destroyed by a call to
55304     ** sqlite3_backup_finish(). */
55305     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55306     if( !p ){
55307       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55308     }
55309   }
55310
55311   /* If the allocation succeeded, populate the new object. */
55312   if( p ){
55313     memset(p, 0, sizeof(sqlite3_backup));
55314     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55315     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55316     p->pDestDb = pDestDb;
55317     p->pSrcDb = pSrcDb;
55318     p->iNext = 1;
55319     p->isAttached = 0;
55320
55321     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55322       /* One (or both) of the named databases did not exist or an OOM
55323       ** error was hit.  The error has already been written into the
55324       ** pDestDb handle.  All that is left to do here is free the
55325       ** sqlite3_backup structure.
55326       */
55327       sqlite3_free(p);
55328       p = 0;
55329     }
55330   }
55331   if( p ){
55332     p->pSrc->nBackup++;
55333   }
55334
55335   sqlite3_mutex_leave(pDestDb->mutex);
55336   sqlite3_mutex_leave(pSrcDb->mutex);
55337   return p;
55338 }
55339
55340 /*
55341 ** Argument rc is an SQLite error code. Return true if this error is 
55342 ** considered fatal if encountered during a backup operation. All errors
55343 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55344 */
55345 static int isFatalError(int rc){
55346   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55347 }
55348
55349 /*
55350 ** Parameter zSrcData points to a buffer containing the data for 
55351 ** page iSrcPg from the source database. Copy this data into the 
55352 ** destination database.
55353 */
55354 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55355   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55356   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55357   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55358   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55359   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55360 #ifdef SQLITE_HAS_CODEC
55361   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55362   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55363 #endif
55364
55365   int rc = SQLITE_OK;
55366   i64 iOff;
55367
55368   assert( p->bDestLocked );
55369   assert( !isFatalError(p->rc) );
55370   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55371   assert( zSrcData );
55372
55373   /* Catch the case where the destination is an in-memory database and the
55374   ** page sizes of the source and destination differ. 
55375   */
55376   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55377     rc = SQLITE_READONLY;
55378   }
55379
55380 #ifdef SQLITE_HAS_CODEC
55381   /* Backup is not possible if the page size of the destination is changing
55382   ** and a codec is in use.
55383   */
55384   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55385     rc = SQLITE_READONLY;
55386   }
55387
55388   /* Backup is not possible if the number of bytes of reserve space differ
55389   ** between source and destination.  If there is a difference, try to
55390   ** fix the destination to agree with the source.  If that is not possible,
55391   ** then the backup cannot proceed.
55392   */
55393   if( nSrcReserve!=nDestReserve ){
55394     u32 newPgsz = nSrcPgsz;
55395     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55396     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55397   }
55398 #endif
55399
55400   /* This loop runs once for each destination page spanned by the source 
55401   ** page. For each iteration, variable iOff is set to the byte offset
55402   ** of the destination page.
55403   */
55404   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55405     DbPage *pDestPg = 0;
55406     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55407     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55408     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55409      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55410     ){
55411       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55412       u8 *zDestData = sqlite3PagerGetData(pDestPg);
55413       u8 *zOut = &zDestData[iOff%nDestPgsz];
55414
55415       /* Copy the data from the source page into the destination page.
55416       ** Then clear the Btree layer MemPage.isInit flag. Both this module
55417       ** and the pager code use this trick (clearing the first byte
55418       ** of the page 'extra' space to invalidate the Btree layers
55419       ** cached parse of the page). MemPage.isInit is marked 
55420       ** "MUST BE FIRST" for this purpose.
55421       */
55422       memcpy(zOut, zIn, nCopy);
55423       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55424     }
55425     sqlite3PagerUnref(pDestPg);
55426   }
55427
55428   return rc;
55429 }
55430
55431 /*
55432 ** If pFile is currently larger than iSize bytes, then truncate it to
55433 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55434 ** this function is a no-op.
55435 **
55436 ** Return SQLITE_OK if everything is successful, or an SQLite error 
55437 ** code if an error occurs.
55438 */
55439 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55440   i64 iCurrent;
55441   int rc = sqlite3OsFileSize(pFile, &iCurrent);
55442   if( rc==SQLITE_OK && iCurrent>iSize ){
55443     rc = sqlite3OsTruncate(pFile, iSize);
55444   }
55445   return rc;
55446 }
55447
55448 /*
55449 ** Register this backup object with the associated source pager for
55450 ** callbacks when pages are changed or the cache invalidated.
55451 */
55452 static void attachBackupObject(sqlite3_backup *p){
55453   sqlite3_backup **pp;
55454   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55455   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55456   p->pNext = *pp;
55457   *pp = p;
55458   p->isAttached = 1;
55459 }
55460
55461 /*
55462 ** Copy nPage pages from the source b-tree to the destination.
55463 */
55464 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
55465   int rc;
55466   int destMode;       /* Destination journal mode */
55467   int pgszSrc = 0;    /* Source page size */
55468   int pgszDest = 0;   /* Destination page size */
55469
55470   sqlite3_mutex_enter(p->pSrcDb->mutex);
55471   sqlite3BtreeEnter(p->pSrc);
55472   if( p->pDestDb ){
55473     sqlite3_mutex_enter(p->pDestDb->mutex);
55474   }
55475
55476   rc = p->rc;
55477   if( !isFatalError(rc) ){
55478     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
55479     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
55480     int ii;                            /* Iterator variable */
55481     int nSrcPage = -1;                 /* Size of source db in pages */
55482     int bCloseTrans = 0;               /* True if src db requires unlocking */
55483
55484     /* If the source pager is currently in a write-transaction, return
55485     ** SQLITE_BUSY immediately.
55486     */
55487     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
55488       rc = SQLITE_BUSY;
55489     }else{
55490       rc = SQLITE_OK;
55491     }
55492
55493     /* Lock the destination database, if it is not locked already. */
55494     if( SQLITE_OK==rc && p->bDestLocked==0
55495      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
55496     ){
55497       p->bDestLocked = 1;
55498       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
55499     }
55500
55501     /* If there is no open read-transaction on the source database, open
55502     ** one now. If a transaction is opened here, then it will be closed
55503     ** before this function exits.
55504     */
55505     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
55506       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
55507       bCloseTrans = 1;
55508     }
55509
55510     /* Do not allow backup if the destination database is in WAL mode
55511     ** and the page sizes are different between source and destination */
55512     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
55513     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
55514     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
55515     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
55516       rc = SQLITE_READONLY;
55517     }
55518   
55519     /* Now that there is a read-lock on the source database, query the
55520     ** source pager for the number of pages in the database.
55521     */
55522     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
55523     assert( nSrcPage>=0 );
55524     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
55525       const Pgno iSrcPg = p->iNext;                 /* Source page number */
55526       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
55527         DbPage *pSrcPg;                             /* Source page object */
55528         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55529         if( rc==SQLITE_OK ){
55530           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
55531           sqlite3PagerUnref(pSrcPg);
55532         }
55533       }
55534       p->iNext++;
55535     }
55536     if( rc==SQLITE_OK ){
55537       p->nPagecount = nSrcPage;
55538       p->nRemaining = nSrcPage+1-p->iNext;
55539       if( p->iNext>(Pgno)nSrcPage ){
55540         rc = SQLITE_DONE;
55541       }else if( !p->isAttached ){
55542         attachBackupObject(p);
55543       }
55544     }
55545   
55546     /* Update the schema version field in the destination database. This
55547     ** is to make sure that the schema-version really does change in
55548     ** the case where the source and destination databases have the
55549     ** same schema version.
55550     */
55551     if( rc==SQLITE_DONE 
55552      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
55553     ){
55554       int nDestTruncate;
55555   
55556       if( p->pDestDb ){
55557         sqlite3ResetInternalSchema(p->pDestDb, -1);
55558       }
55559
55560       /* Set nDestTruncate to the final number of pages in the destination
55561       ** database. The complication here is that the destination page
55562       ** size may be different to the source page size. 
55563       **
55564       ** If the source page size is smaller than the destination page size, 
55565       ** round up. In this case the call to sqlite3OsTruncate() below will
55566       ** fix the size of the file. However it is important to call
55567       ** sqlite3PagerTruncateImage() here so that any pages in the 
55568       ** destination file that lie beyond the nDestTruncate page mark are
55569       ** journalled by PagerCommitPhaseOne() before they are destroyed
55570       ** by the file truncation.
55571       */
55572       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
55573       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
55574       if( pgszSrc<pgszDest ){
55575         int ratio = pgszDest/pgszSrc;
55576         nDestTruncate = (nSrcPage+ratio-1)/ratio;
55577         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
55578           nDestTruncate--;
55579         }
55580       }else{
55581         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
55582       }
55583       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
55584
55585       if( pgszSrc<pgszDest ){
55586         /* If the source page-size is smaller than the destination page-size,
55587         ** two extra things may need to happen:
55588         **
55589         **   * The destination may need to be truncated, and
55590         **
55591         **   * Data stored on the pages immediately following the 
55592         **     pending-byte page in the source database may need to be
55593         **     copied into the destination database.
55594         */
55595         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
55596         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
55597         i64 iOff;
55598         i64 iEnd;
55599
55600         assert( pFile );
55601         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
55602               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
55603            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
55604         ));
55605
55606         /* This call ensures that all data required to recreate the original
55607         ** database has been stored in the journal for pDestPager and the
55608         ** journal synced to disk. So at this point we may safely modify
55609         ** the database file in any way, knowing that if a power failure
55610         ** occurs, the original database will be reconstructed from the 
55611         ** journal file.  */
55612         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
55613
55614         /* Write the extra pages and truncate the database file as required. */
55615         iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
55616         for(
55617           iOff=PENDING_BYTE+pgszSrc; 
55618           rc==SQLITE_OK && iOff<iEnd; 
55619           iOff+=pgszSrc
55620         ){
55621           PgHdr *pSrcPg = 0;
55622           const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
55623           rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55624           if( rc==SQLITE_OK ){
55625             u8 *zData = sqlite3PagerGetData(pSrcPg);
55626             rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
55627           }
55628           sqlite3PagerUnref(pSrcPg);
55629         }
55630         if( rc==SQLITE_OK ){
55631           rc = backupTruncateFile(pFile, iSize);
55632         }
55633
55634         /* Sync the database file to disk. */
55635         if( rc==SQLITE_OK ){
55636           rc = sqlite3PagerSync(pDestPager);
55637         }
55638       }else{
55639         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
55640       }
55641   
55642       /* Finish committing the transaction to the destination database. */
55643       if( SQLITE_OK==rc
55644        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
55645       ){
55646         rc = SQLITE_DONE;
55647       }
55648     }
55649   
55650     /* If bCloseTrans is true, then this function opened a read transaction
55651     ** on the source database. Close the read transaction here. There is
55652     ** no need to check the return values of the btree methods here, as
55653     ** "committing" a read-only transaction cannot fail.
55654     */
55655     if( bCloseTrans ){
55656       TESTONLY( int rc2 );
55657       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
55658       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
55659       assert( rc2==SQLITE_OK );
55660     }
55661   
55662     if( rc==SQLITE_IOERR_NOMEM ){
55663       rc = SQLITE_NOMEM;
55664     }
55665     p->rc = rc;
55666   }
55667   if( p->pDestDb ){
55668     sqlite3_mutex_leave(p->pDestDb->mutex);
55669   }
55670   sqlite3BtreeLeave(p->pSrc);
55671   sqlite3_mutex_leave(p->pSrcDb->mutex);
55672   return rc;
55673 }
55674
55675 /*
55676 ** Release all resources associated with an sqlite3_backup* handle.
55677 */
55678 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
55679   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
55680   sqlite3_mutex *mutex;                /* Mutex to protect source database */
55681   int rc;                              /* Value to return */
55682
55683   /* Enter the mutexes */
55684   if( p==0 ) return SQLITE_OK;
55685   sqlite3_mutex_enter(p->pSrcDb->mutex);
55686   sqlite3BtreeEnter(p->pSrc);
55687   mutex = p->pSrcDb->mutex;
55688   if( p->pDestDb ){
55689     sqlite3_mutex_enter(p->pDestDb->mutex);
55690   }
55691
55692   /* Detach this backup from the source pager. */
55693   if( p->pDestDb ){
55694     p->pSrc->nBackup--;
55695   }
55696   if( p->isAttached ){
55697     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55698     while( *pp!=p ){
55699       pp = &(*pp)->pNext;
55700     }
55701     *pp = p->pNext;
55702   }
55703
55704   /* If a transaction is still open on the Btree, roll it back. */
55705   sqlite3BtreeRollback(p->pDest);
55706
55707   /* Set the error code of the destination database handle. */
55708   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
55709   sqlite3Error(p->pDestDb, rc, 0);
55710
55711   /* Exit the mutexes and free the backup context structure. */
55712   if( p->pDestDb ){
55713     sqlite3_mutex_leave(p->pDestDb->mutex);
55714   }
55715   sqlite3BtreeLeave(p->pSrc);
55716   if( p->pDestDb ){
55717     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55718     ** call to sqlite3_backup_init() and is destroyed by a call to
55719     ** sqlite3_backup_finish(). */
55720     sqlite3_free(p);
55721   }
55722   sqlite3_mutex_leave(mutex);
55723   return rc;
55724 }
55725
55726 /*
55727 ** Return the number of pages still to be backed up as of the most recent
55728 ** call to sqlite3_backup_step().
55729 */
55730 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
55731   return p->nRemaining;
55732 }
55733
55734 /*
55735 ** Return the total number of pages in the source database as of the most 
55736 ** recent call to sqlite3_backup_step().
55737 */
55738 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
55739   return p->nPagecount;
55740 }
55741
55742 /*
55743 ** This function is called after the contents of page iPage of the
55744 ** source database have been modified. If page iPage has already been 
55745 ** copied into the destination database, then the data written to the
55746 ** destination is now invalidated. The destination copy of iPage needs
55747 ** to be updated with the new data before the backup operation is
55748 ** complete.
55749 **
55750 ** It is assumed that the mutex associated with the BtShared object
55751 ** corresponding to the source database is held when this function is
55752 ** called.
55753 */
55754 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
55755   sqlite3_backup *p;                   /* Iterator variable */
55756   for(p=pBackup; p; p=p->pNext){
55757     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55758     if( !isFatalError(p->rc) && iPage<p->iNext ){
55759       /* The backup process p has already copied page iPage. But now it
55760       ** has been modified by a transaction on the source pager. Copy
55761       ** the new data into the backup.
55762       */
55763       int rc;
55764       assert( p->pDestDb );
55765       sqlite3_mutex_enter(p->pDestDb->mutex);
55766       rc = backupOnePage(p, iPage, aData);
55767       sqlite3_mutex_leave(p->pDestDb->mutex);
55768       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
55769       if( rc!=SQLITE_OK ){
55770         p->rc = rc;
55771       }
55772     }
55773   }
55774 }
55775
55776 /*
55777 ** Restart the backup process. This is called when the pager layer
55778 ** detects that the database has been modified by an external database
55779 ** connection. In this case there is no way of knowing which of the
55780 ** pages that have been copied into the destination database are still 
55781 ** valid and which are not, so the entire process needs to be restarted.
55782 **
55783 ** It is assumed that the mutex associated with the BtShared object
55784 ** corresponding to the source database is held when this function is
55785 ** called.
55786 */
55787 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
55788   sqlite3_backup *p;                   /* Iterator variable */
55789   for(p=pBackup; p; p=p->pNext){
55790     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
55791     p->iNext = 1;
55792   }
55793 }
55794
55795 #ifndef SQLITE_OMIT_VACUUM
55796 /*
55797 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
55798 ** must be active for both files.
55799 **
55800 ** The size of file pTo may be reduced by this operation. If anything 
55801 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
55802 ** transaction is committed before returning.
55803 */
55804 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
55805   int rc;
55806   sqlite3_backup b;
55807   sqlite3BtreeEnter(pTo);
55808   sqlite3BtreeEnter(pFrom);
55809
55810   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
55811   ** to 0. This is used by the implementations of sqlite3_backup_step()
55812   ** and sqlite3_backup_finish() to detect that they are being called
55813   ** from this function, not directly by the user.
55814   */
55815   memset(&b, 0, sizeof(b));
55816   b.pSrcDb = pFrom->db;
55817   b.pSrc = pFrom;
55818   b.pDest = pTo;
55819   b.iNext = 1;
55820
55821   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
55822   ** file. By passing this as the number of pages to copy to
55823   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
55824   ** within a single call (unless an error occurs). The assert() statement
55825   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
55826   ** or an error code.
55827   */
55828   sqlite3_backup_step(&b, 0x7FFFFFFF);
55829   assert( b.rc!=SQLITE_OK );
55830   rc = sqlite3_backup_finish(&b);
55831   if( rc==SQLITE_OK ){
55832     pTo->pBt->pageSizeFixed = 0;
55833   }
55834
55835   sqlite3BtreeLeave(pFrom);
55836   sqlite3BtreeLeave(pTo);
55837   return rc;
55838 }
55839 #endif /* SQLITE_OMIT_VACUUM */
55840
55841 /************** End of backup.c **********************************************/
55842 /************** Begin file vdbemem.c *****************************************/
55843 /*
55844 ** 2004 May 26
55845 **
55846 ** The author disclaims copyright to this source code.  In place of
55847 ** a legal notice, here is a blessing:
55848 **
55849 **    May you do good and not evil.
55850 **    May you find forgiveness for yourself and forgive others.
55851 **    May you share freely, never taking more than you give.
55852 **
55853 *************************************************************************
55854 **
55855 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
55856 ** stores a single value in the VDBE.  Mem is an opaque structure visible
55857 ** only within the VDBE.  Interface routines refer to a Mem using the
55858 ** name sqlite_value
55859 */
55860
55861 /*
55862 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
55863 ** P if required.
55864 */
55865 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
55866
55867 /*
55868 ** If pMem is an object with a valid string representation, this routine
55869 ** ensures the internal encoding for the string representation is
55870 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
55871 **
55872 ** If pMem is not a string object, or the encoding of the string
55873 ** representation is already stored using the requested encoding, then this
55874 ** routine is a no-op.
55875 **
55876 ** SQLITE_OK is returned if the conversion is successful (or not required).
55877 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
55878 ** between formats.
55879 */
55880 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
55881   int rc;
55882   assert( (pMem->flags&MEM_RowSet)==0 );
55883   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
55884            || desiredEnc==SQLITE_UTF16BE );
55885   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
55886     return SQLITE_OK;
55887   }
55888   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55889 #ifdef SQLITE_OMIT_UTF16
55890   return SQLITE_ERROR;
55891 #else
55892
55893   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
55894   ** then the encoding of the value may not have changed.
55895   */
55896   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
55897   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
55898   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
55899   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
55900   return rc;
55901 #endif
55902 }
55903
55904 /*
55905 ** Make sure pMem->z points to a writable allocation of at least 
55906 ** n bytes.
55907 **
55908 ** If the memory cell currently contains string or blob data
55909 ** and the third argument passed to this function is true, the 
55910 ** current content of the cell is preserved. Otherwise, it may
55911 ** be discarded.  
55912 **
55913 ** This function sets the MEM_Dyn flag and clears any xDel callback.
55914 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
55915 ** not set, Mem.n is zeroed.
55916 */
55917 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
55918   assert( 1 >=
55919     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
55920     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
55921     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
55922     ((pMem->flags&MEM_Static) ? 1 : 0)
55923   );
55924   assert( (pMem->flags&MEM_RowSet)==0 );
55925
55926   if( n<32 ) n = 32;
55927   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
55928     if( preserve && pMem->z==pMem->zMalloc ){
55929       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
55930       preserve = 0;
55931     }else{
55932       sqlite3DbFree(pMem->db, pMem->zMalloc);
55933       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
55934     }
55935   }
55936
55937   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
55938     memcpy(pMem->zMalloc, pMem->z, pMem->n);
55939   }
55940   if( pMem->flags&MEM_Dyn && pMem->xDel ){
55941     pMem->xDel((void *)(pMem->z));
55942   }
55943
55944   pMem->z = pMem->zMalloc;
55945   if( pMem->z==0 ){
55946     pMem->flags = MEM_Null;
55947   }else{
55948     pMem->flags &= ~(MEM_Ephem|MEM_Static);
55949   }
55950   pMem->xDel = 0;
55951   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
55952 }
55953
55954 /*
55955 ** Make the given Mem object MEM_Dyn.  In other words, make it so
55956 ** that any TEXT or BLOB content is stored in memory obtained from
55957 ** malloc().  In this way, we know that the memory is safe to be
55958 ** overwritten or altered.
55959 **
55960 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
55961 */
55962 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
55963   int f;
55964   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55965   assert( (pMem->flags&MEM_RowSet)==0 );
55966   expandBlob(pMem);
55967   f = pMem->flags;
55968   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
55969     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
55970       return SQLITE_NOMEM;
55971     }
55972     pMem->z[pMem->n] = 0;
55973     pMem->z[pMem->n+1] = 0;
55974     pMem->flags |= MEM_Term;
55975 #ifdef SQLITE_DEBUG
55976     pMem->pScopyFrom = 0;
55977 #endif
55978   }
55979
55980   return SQLITE_OK;
55981 }
55982
55983 /*
55984 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
55985 ** blob stored in dynamically allocated space.
55986 */
55987 #ifndef SQLITE_OMIT_INCRBLOB
55988 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
55989   if( pMem->flags & MEM_Zero ){
55990     int nByte;
55991     assert( pMem->flags&MEM_Blob );
55992     assert( (pMem->flags&MEM_RowSet)==0 );
55993     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55994
55995     /* Set nByte to the number of bytes required to store the expanded blob. */
55996     nByte = pMem->n + pMem->u.nZero;
55997     if( nByte<=0 ){
55998       nByte = 1;
55999     }
56000     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
56001       return SQLITE_NOMEM;
56002     }
56003
56004     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
56005     pMem->n += pMem->u.nZero;
56006     pMem->flags &= ~(MEM_Zero|MEM_Term);
56007   }
56008   return SQLITE_OK;
56009 }
56010 #endif
56011
56012
56013 /*
56014 ** Make sure the given Mem is \u0000 terminated.
56015 */
56016 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56017   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56018   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56019     return SQLITE_OK;   /* Nothing to do */
56020   }
56021   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56022     return SQLITE_NOMEM;
56023   }
56024   pMem->z[pMem->n] = 0;
56025   pMem->z[pMem->n+1] = 0;
56026   pMem->flags |= MEM_Term;
56027   return SQLITE_OK;
56028 }
56029
56030 /*
56031 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
56032 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
56033 ** is a no-op.
56034 **
56035 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56036 **
56037 ** A MEM_Null value will never be passed to this function. This function is
56038 ** used for converting values to text for returning to the user (i.e. via
56039 ** sqlite3_value_text()), or for ensuring that values to be used as btree
56040 ** keys are strings. In the former case a NULL pointer is returned the
56041 ** user and the later is an internal programming error.
56042 */
56043 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56044   int rc = SQLITE_OK;
56045   int fg = pMem->flags;
56046   const int nByte = 32;
56047
56048   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56049   assert( !(fg&MEM_Zero) );
56050   assert( !(fg&(MEM_Str|MEM_Blob)) );
56051   assert( fg&(MEM_Int|MEM_Real) );
56052   assert( (pMem->flags&MEM_RowSet)==0 );
56053   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56054
56055
56056   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56057     return SQLITE_NOMEM;
56058   }
56059
56060   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56061   ** string representation of the value. Then, if the required encoding
56062   ** is UTF-16le or UTF-16be do a translation.
56063   ** 
56064   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56065   */
56066   if( fg & MEM_Int ){
56067     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56068   }else{
56069     assert( fg & MEM_Real );
56070     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56071   }
56072   pMem->n = sqlite3Strlen30(pMem->z);
56073   pMem->enc = SQLITE_UTF8;
56074   pMem->flags |= MEM_Str|MEM_Term;
56075   sqlite3VdbeChangeEncoding(pMem, enc);
56076   return rc;
56077 }
56078
56079 /*
56080 ** Memory cell pMem contains the context of an aggregate function.
56081 ** This routine calls the finalize method for that function.  The
56082 ** result of the aggregate is stored back into pMem.
56083 **
56084 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
56085 ** otherwise.
56086 */
56087 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56088   int rc = SQLITE_OK;
56089   if( ALWAYS(pFunc && pFunc->xFinalize) ){
56090     sqlite3_context ctx;
56091     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56092     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56093     memset(&ctx, 0, sizeof(ctx));
56094     ctx.s.flags = MEM_Null;
56095     ctx.s.db = pMem->db;
56096     ctx.pMem = pMem;
56097     ctx.pFunc = pFunc;
56098     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56099     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56100     sqlite3DbFree(pMem->db, pMem->zMalloc);
56101     memcpy(pMem, &ctx.s, sizeof(ctx.s));
56102     rc = ctx.isError;
56103   }
56104   return rc;
56105 }
56106
56107 /*
56108 ** If the memory cell contains a string value that must be freed by
56109 ** invoking an external callback, free it now. Calling this function
56110 ** does not free any Mem.zMalloc buffer.
56111 */
56112 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56113   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56114   testcase( p->flags & MEM_Agg );
56115   testcase( p->flags & MEM_Dyn );
56116   testcase( p->flags & MEM_RowSet );
56117   testcase( p->flags & MEM_Frame );
56118   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56119     if( p->flags&MEM_Agg ){
56120       sqlite3VdbeMemFinalize(p, p->u.pDef);
56121       assert( (p->flags & MEM_Agg)==0 );
56122       sqlite3VdbeMemRelease(p);
56123     }else if( p->flags&MEM_Dyn && p->xDel ){
56124       assert( (p->flags&MEM_RowSet)==0 );
56125       p->xDel((void *)p->z);
56126       p->xDel = 0;
56127     }else if( p->flags&MEM_RowSet ){
56128       sqlite3RowSetClear(p->u.pRowSet);
56129     }else if( p->flags&MEM_Frame ){
56130       sqlite3VdbeMemSetNull(p);
56131     }
56132   }
56133 }
56134
56135 /*
56136 ** Release any memory held by the Mem. This may leave the Mem in an
56137 ** inconsistent state, for example with (Mem.z==0) and
56138 ** (Mem.type==SQLITE_TEXT).
56139 */
56140 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56141   sqlite3VdbeMemReleaseExternal(p);
56142   sqlite3DbFree(p->db, p->zMalloc);
56143   p->z = 0;
56144   p->zMalloc = 0;
56145   p->xDel = 0;
56146 }
56147
56148 /*
56149 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
56150 ** If the double is too large, return 0x8000000000000000.
56151 **
56152 ** Most systems appear to do this simply by assigning
56153 ** variables and without the extra range tests.  But
56154 ** there are reports that windows throws an expection
56155 ** if the floating point value is out of range. (See ticket #2880.)
56156 ** Because we do not completely understand the problem, we will
56157 ** take the conservative approach and always do range tests
56158 ** before attempting the conversion.
56159 */
56160 static i64 doubleToInt64(double r){
56161 #ifdef SQLITE_OMIT_FLOATING_POINT
56162   /* When floating-point is omitted, double and int64 are the same thing */
56163   return r;
56164 #else
56165   /*
56166   ** Many compilers we encounter do not define constants for the
56167   ** minimum and maximum 64-bit integers, or they define them
56168   ** inconsistently.  And many do not understand the "LL" notation.
56169   ** So we define our own static constants here using nothing
56170   ** larger than a 32-bit integer constant.
56171   */
56172   static const i64 maxInt = LARGEST_INT64;
56173   static const i64 minInt = SMALLEST_INT64;
56174
56175   if( r<(double)minInt ){
56176     return minInt;
56177   }else if( r>(double)maxInt ){
56178     /* minInt is correct here - not maxInt.  It turns out that assigning
56179     ** a very large positive number to an integer results in a very large
56180     ** negative integer.  This makes no sense, but it is what x86 hardware
56181     ** does so for compatibility we will do the same in software. */
56182     return minInt;
56183   }else{
56184     return (i64)r;
56185   }
56186 #endif
56187 }
56188
56189 /*
56190 ** Return some kind of integer value which is the best we can do
56191 ** at representing the value that *pMem describes as an integer.
56192 ** If pMem is an integer, then the value is exact.  If pMem is
56193 ** a floating-point then the value returned is the integer part.
56194 ** If pMem is a string or blob, then we make an attempt to convert
56195 ** it into a integer and return that.  If pMem represents an
56196 ** an SQL-NULL value, return 0.
56197 **
56198 ** If pMem represents a string value, its encoding might be changed.
56199 */
56200 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56201   int flags;
56202   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56203   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56204   flags = pMem->flags;
56205   if( flags & MEM_Int ){
56206     return pMem->u.i;
56207   }else if( flags & MEM_Real ){
56208     return doubleToInt64(pMem->r);
56209   }else if( flags & (MEM_Str|MEM_Blob) ){
56210     i64 value = 0;
56211     assert( pMem->z || pMem->n==0 );
56212     testcase( pMem->z==0 );
56213     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56214     return value;
56215   }else{
56216     return 0;
56217   }
56218 }
56219
56220 /*
56221 ** Return the best representation of pMem that we can get into a
56222 ** double.  If pMem is already a double or an integer, return its
56223 ** value.  If it is a string or blob, try to convert it to a double.
56224 ** If it is a NULL, return 0.0.
56225 */
56226 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56227   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56228   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56229   if( pMem->flags & MEM_Real ){
56230     return pMem->r;
56231   }else if( pMem->flags & MEM_Int ){
56232     return (double)pMem->u.i;
56233   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56234     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56235     double val = (double)0;
56236     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56237     return val;
56238   }else{
56239     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56240     return (double)0;
56241   }
56242 }
56243
56244 /*
56245 ** The MEM structure is already a MEM_Real.  Try to also make it a
56246 ** MEM_Int if we can.
56247 */
56248 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56249   assert( pMem->flags & MEM_Real );
56250   assert( (pMem->flags & MEM_RowSet)==0 );
56251   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56252   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56253
56254   pMem->u.i = doubleToInt64(pMem->r);
56255
56256   /* Only mark the value as an integer if
56257   **
56258   **    (1) the round-trip conversion real->int->real is a no-op, and
56259   **    (2) The integer is neither the largest nor the smallest
56260   **        possible integer (ticket #3922)
56261   **
56262   ** The second and third terms in the following conditional enforces
56263   ** the second condition under the assumption that addition overflow causes
56264   ** values to wrap around.  On x86 hardware, the third term is always
56265   ** true and could be omitted.  But we leave it in because other
56266   ** architectures might behave differently.
56267   */
56268   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56269       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56270     pMem->flags |= MEM_Int;
56271   }
56272 }
56273
56274 /*
56275 ** Convert pMem to type integer.  Invalidate any prior representations.
56276 */
56277 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56278   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56279   assert( (pMem->flags & MEM_RowSet)==0 );
56280   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56281
56282   pMem->u.i = sqlite3VdbeIntValue(pMem);
56283   MemSetTypeFlag(pMem, MEM_Int);
56284   return SQLITE_OK;
56285 }
56286
56287 /*
56288 ** Convert pMem so that it is of type MEM_Real.
56289 ** Invalidate any prior representations.
56290 */
56291 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56292   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56293   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56294
56295   pMem->r = sqlite3VdbeRealValue(pMem);
56296   MemSetTypeFlag(pMem, MEM_Real);
56297   return SQLITE_OK;
56298 }
56299
56300 /*
56301 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56302 ** Invalidate any prior representations.
56303 **
56304 ** Every effort is made to force the conversion, even if the input
56305 ** is a string that does not look completely like a number.  Convert
56306 ** as much of the string as we can and ignore the rest.
56307 */
56308 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56309   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56310     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56311     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56312     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56313       MemSetTypeFlag(pMem, MEM_Int);
56314     }else{
56315       pMem->r = sqlite3VdbeRealValue(pMem);
56316       MemSetTypeFlag(pMem, MEM_Real);
56317       sqlite3VdbeIntegerAffinity(pMem);
56318     }
56319   }
56320   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56321   pMem->flags &= ~(MEM_Str|MEM_Blob);
56322   return SQLITE_OK;
56323 }
56324
56325 /*
56326 ** Delete any previous value and set the value stored in *pMem to NULL.
56327 */
56328 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56329   if( pMem->flags & MEM_Frame ){
56330     VdbeFrame *pFrame = pMem->u.pFrame;
56331     pFrame->pParent = pFrame->v->pDelFrame;
56332     pFrame->v->pDelFrame = pFrame;
56333   }
56334   if( pMem->flags & MEM_RowSet ){
56335     sqlite3RowSetClear(pMem->u.pRowSet);
56336   }
56337   MemSetTypeFlag(pMem, MEM_Null);
56338   pMem->type = SQLITE_NULL;
56339 }
56340
56341 /*
56342 ** Delete any previous value and set the value to be a BLOB of length
56343 ** n containing all zeros.
56344 */
56345 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56346   sqlite3VdbeMemRelease(pMem);
56347   pMem->flags = MEM_Blob|MEM_Zero;
56348   pMem->type = SQLITE_BLOB;
56349   pMem->n = 0;
56350   if( n<0 ) n = 0;
56351   pMem->u.nZero = n;
56352   pMem->enc = SQLITE_UTF8;
56353
56354 #ifdef SQLITE_OMIT_INCRBLOB
56355   sqlite3VdbeMemGrow(pMem, n, 0);
56356   if( pMem->z ){
56357     pMem->n = n;
56358     memset(pMem->z, 0, n);
56359   }
56360 #endif
56361 }
56362
56363 /*
56364 ** Delete any previous value and set the value stored in *pMem to val,
56365 ** manifest type INTEGER.
56366 */
56367 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56368   sqlite3VdbeMemRelease(pMem);
56369   pMem->u.i = val;
56370   pMem->flags = MEM_Int;
56371   pMem->type = SQLITE_INTEGER;
56372 }
56373
56374 #ifndef SQLITE_OMIT_FLOATING_POINT
56375 /*
56376 ** Delete any previous value and set the value stored in *pMem to val,
56377 ** manifest type REAL.
56378 */
56379 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56380   if( sqlite3IsNaN(val) ){
56381     sqlite3VdbeMemSetNull(pMem);
56382   }else{
56383     sqlite3VdbeMemRelease(pMem);
56384     pMem->r = val;
56385     pMem->flags = MEM_Real;
56386     pMem->type = SQLITE_FLOAT;
56387   }
56388 }
56389 #endif
56390
56391 /*
56392 ** Delete any previous value and set the value of pMem to be an
56393 ** empty boolean index.
56394 */
56395 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56396   sqlite3 *db = pMem->db;
56397   assert( db!=0 );
56398   assert( (pMem->flags & MEM_RowSet)==0 );
56399   sqlite3VdbeMemRelease(pMem);
56400   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56401   if( db->mallocFailed ){
56402     pMem->flags = MEM_Null;
56403   }else{
56404     assert( pMem->zMalloc );
56405     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
56406                                        sqlite3DbMallocSize(db, pMem->zMalloc));
56407     assert( pMem->u.pRowSet!=0 );
56408     pMem->flags = MEM_RowSet;
56409   }
56410 }
56411
56412 /*
56413 ** Return true if the Mem object contains a TEXT or BLOB that is
56414 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
56415 */
56416 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56417   assert( p->db!=0 );
56418   if( p->flags & (MEM_Str|MEM_Blob) ){
56419     int n = p->n;
56420     if( p->flags & MEM_Zero ){
56421       n += p->u.nZero;
56422     }
56423     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56424   }
56425   return 0; 
56426 }
56427
56428 #ifdef SQLITE_DEBUG
56429 /*
56430 ** This routine prepares a memory cell for modication by breaking
56431 ** its link to a shallow copy and by marking any current shallow
56432 ** copies of this cell as invalid.
56433 **
56434 ** This is used for testing and debugging only - to make sure shallow
56435 ** copies are not misused.
56436 */
56437 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56438   int i;
56439   Mem *pX;
56440   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56441     if( pX->pScopyFrom==pMem ){
56442       pX->flags |= MEM_Invalid;
56443       pX->pScopyFrom = 0;
56444     }
56445   }
56446   pMem->pScopyFrom = 0;
56447 }
56448 #endif /* SQLITE_DEBUG */
56449
56450 /*
56451 ** Size of struct Mem not including the Mem.zMalloc member.
56452 */
56453 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56454
56455 /*
56456 ** Make an shallow copy of pFrom into pTo.  Prior contents of
56457 ** pTo are freed.  The pFrom->z field is not duplicated.  If
56458 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
56459 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
56460 */
56461 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
56462   assert( (pFrom->flags & MEM_RowSet)==0 );
56463   sqlite3VdbeMemReleaseExternal(pTo);
56464   memcpy(pTo, pFrom, MEMCELLSIZE);
56465   pTo->xDel = 0;
56466   if( (pFrom->flags&MEM_Static)==0 ){
56467     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
56468     assert( srcType==MEM_Ephem || srcType==MEM_Static );
56469     pTo->flags |= srcType;
56470   }
56471 }
56472
56473 /*
56474 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
56475 ** freed before the copy is made.
56476 */
56477 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
56478   int rc = SQLITE_OK;
56479
56480   assert( (pFrom->flags & MEM_RowSet)==0 );
56481   sqlite3VdbeMemReleaseExternal(pTo);
56482   memcpy(pTo, pFrom, MEMCELLSIZE);
56483   pTo->flags &= ~MEM_Dyn;
56484
56485   if( pTo->flags&(MEM_Str|MEM_Blob) ){
56486     if( 0==(pFrom->flags&MEM_Static) ){
56487       pTo->flags |= MEM_Ephem;
56488       rc = sqlite3VdbeMemMakeWriteable(pTo);
56489     }
56490   }
56491
56492   return rc;
56493 }
56494
56495 /*
56496 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
56497 ** freed. If pFrom contains ephemeral data, a copy is made.
56498 **
56499 ** pFrom contains an SQL NULL when this routine returns.
56500 */
56501 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
56502   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
56503   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
56504   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
56505
56506   sqlite3VdbeMemRelease(pTo);
56507   memcpy(pTo, pFrom, sizeof(Mem));
56508   pFrom->flags = MEM_Null;
56509   pFrom->xDel = 0;
56510   pFrom->zMalloc = 0;
56511 }
56512
56513 /*
56514 ** Change the value of a Mem to be a string or a BLOB.
56515 **
56516 ** The memory management strategy depends on the value of the xDel
56517 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
56518 ** string is copied into a (possibly existing) buffer managed by the 
56519 ** Mem structure. Otherwise, any existing buffer is freed and the
56520 ** pointer copied.
56521 **
56522 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
56523 ** size limit) then no memory allocation occurs.  If the string can be
56524 ** stored without allocating memory, then it is.  If a memory allocation
56525 ** is required to store the string, then value of pMem is unchanged.  In
56526 ** either case, SQLITE_TOOBIG is returned.
56527 */
56528 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
56529   Mem *pMem,          /* Memory cell to set to string value */
56530   const char *z,      /* String pointer */
56531   int n,              /* Bytes in string, or negative */
56532   u8 enc,             /* Encoding of z.  0 for BLOBs */
56533   void (*xDel)(void*) /* Destructor function */
56534 ){
56535   int nByte = n;      /* New value for pMem->n */
56536   int iLimit;         /* Maximum allowed string or blob size */
56537   u16 flags = 0;      /* New value for pMem->flags */
56538
56539   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56540   assert( (pMem->flags & MEM_RowSet)==0 );
56541
56542   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
56543   if( !z ){
56544     sqlite3VdbeMemSetNull(pMem);
56545     return SQLITE_OK;
56546   }
56547
56548   if( pMem->db ){
56549     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
56550   }else{
56551     iLimit = SQLITE_MAX_LENGTH;
56552   }
56553   flags = (enc==0?MEM_Blob:MEM_Str);
56554   if( nByte<0 ){
56555     assert( enc!=0 );
56556     if( enc==SQLITE_UTF8 ){
56557       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
56558     }else{
56559       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
56560     }
56561     flags |= MEM_Term;
56562   }
56563
56564   /* The following block sets the new values of Mem.z and Mem.xDel. It
56565   ** also sets a flag in local variable "flags" to indicate the memory
56566   ** management (one of MEM_Dyn or MEM_Static).
56567   */
56568   if( xDel==SQLITE_TRANSIENT ){
56569     int nAlloc = nByte;
56570     if( flags&MEM_Term ){
56571       nAlloc += (enc==SQLITE_UTF8?1:2);
56572     }
56573     if( nByte>iLimit ){
56574       return SQLITE_TOOBIG;
56575     }
56576     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
56577       return SQLITE_NOMEM;
56578     }
56579     memcpy(pMem->z, z, nAlloc);
56580   }else if( xDel==SQLITE_DYNAMIC ){
56581     sqlite3VdbeMemRelease(pMem);
56582     pMem->zMalloc = pMem->z = (char *)z;
56583     pMem->xDel = 0;
56584   }else{
56585     sqlite3VdbeMemRelease(pMem);
56586     pMem->z = (char *)z;
56587     pMem->xDel = xDel;
56588     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
56589   }
56590
56591   pMem->n = nByte;
56592   pMem->flags = flags;
56593   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
56594   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
56595
56596 #ifndef SQLITE_OMIT_UTF16
56597   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
56598     return SQLITE_NOMEM;
56599   }
56600 #endif
56601
56602   if( nByte>iLimit ){
56603     return SQLITE_TOOBIG;
56604   }
56605
56606   return SQLITE_OK;
56607 }
56608
56609 /*
56610 ** Compare the values contained by the two memory cells, returning
56611 ** negative, zero or positive if pMem1 is less than, equal to, or greater
56612 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
56613 ** and reals) sorted numerically, followed by text ordered by the collating
56614 ** sequence pColl and finally blob's ordered by memcmp().
56615 **
56616 ** Two NULL values are considered equal by this function.
56617 */
56618 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
56619   int rc;
56620   int f1, f2;
56621   int combined_flags;
56622
56623   f1 = pMem1->flags;
56624   f2 = pMem2->flags;
56625   combined_flags = f1|f2;
56626   assert( (combined_flags & MEM_RowSet)==0 );
56627  
56628   /* If one value is NULL, it is less than the other. If both values
56629   ** are NULL, return 0.
56630   */
56631   if( combined_flags&MEM_Null ){
56632     return (f2&MEM_Null) - (f1&MEM_Null);
56633   }
56634
56635   /* If one value is a number and the other is not, the number is less.
56636   ** If both are numbers, compare as reals if one is a real, or as integers
56637   ** if both values are integers.
56638   */
56639   if( combined_flags&(MEM_Int|MEM_Real) ){
56640     if( !(f1&(MEM_Int|MEM_Real)) ){
56641       return 1;
56642     }
56643     if( !(f2&(MEM_Int|MEM_Real)) ){
56644       return -1;
56645     }
56646     if( (f1 & f2 & MEM_Int)==0 ){
56647       double r1, r2;
56648       if( (f1&MEM_Real)==0 ){
56649         r1 = (double)pMem1->u.i;
56650       }else{
56651         r1 = pMem1->r;
56652       }
56653       if( (f2&MEM_Real)==0 ){
56654         r2 = (double)pMem2->u.i;
56655       }else{
56656         r2 = pMem2->r;
56657       }
56658       if( r1<r2 ) return -1;
56659       if( r1>r2 ) return 1;
56660       return 0;
56661     }else{
56662       assert( f1&MEM_Int );
56663       assert( f2&MEM_Int );
56664       if( pMem1->u.i < pMem2->u.i ) return -1;
56665       if( pMem1->u.i > pMem2->u.i ) return 1;
56666       return 0;
56667     }
56668   }
56669
56670   /* If one value is a string and the other is a blob, the string is less.
56671   ** If both are strings, compare using the collating functions.
56672   */
56673   if( combined_flags&MEM_Str ){
56674     if( (f1 & MEM_Str)==0 ){
56675       return 1;
56676     }
56677     if( (f2 & MEM_Str)==0 ){
56678       return -1;
56679     }
56680
56681     assert( pMem1->enc==pMem2->enc );
56682     assert( pMem1->enc==SQLITE_UTF8 || 
56683             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
56684
56685     /* The collation sequence must be defined at this point, even if
56686     ** the user deletes the collation sequence after the vdbe program is
56687     ** compiled (this was not always the case).
56688     */
56689     assert( !pColl || pColl->xCmp );
56690
56691     if( pColl ){
56692       if( pMem1->enc==pColl->enc ){
56693         /* The strings are already in the correct encoding.  Call the
56694         ** comparison function directly */
56695         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
56696       }else{
56697         const void *v1, *v2;
56698         int n1, n2;
56699         Mem c1;
56700         Mem c2;
56701         memset(&c1, 0, sizeof(c1));
56702         memset(&c2, 0, sizeof(c2));
56703         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
56704         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
56705         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
56706         n1 = v1==0 ? 0 : c1.n;
56707         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
56708         n2 = v2==0 ? 0 : c2.n;
56709         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
56710         sqlite3VdbeMemRelease(&c1);
56711         sqlite3VdbeMemRelease(&c2);
56712         return rc;
56713       }
56714     }
56715     /* If a NULL pointer was passed as the collate function, fall through
56716     ** to the blob case and use memcmp().  */
56717   }
56718  
56719   /* Both values must be blobs.  Compare using memcmp().  */
56720   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
56721   if( rc==0 ){
56722     rc = pMem1->n - pMem2->n;
56723   }
56724   return rc;
56725 }
56726
56727 /*
56728 ** Move data out of a btree key or data field and into a Mem structure.
56729 ** The data or key is taken from the entry that pCur is currently pointing
56730 ** to.  offset and amt determine what portion of the data or key to retrieve.
56731 ** key is true to get the key or false to get data.  The result is written
56732 ** into the pMem element.
56733 **
56734 ** The pMem structure is assumed to be uninitialized.  Any prior content
56735 ** is overwritten without being freed.
56736 **
56737 ** If this routine fails for any reason (malloc returns NULL or unable
56738 ** to read from the disk) then the pMem is left in an inconsistent state.
56739 */
56740 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
56741   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
56742   int offset,       /* Offset from the start of data to return bytes from. */
56743   int amt,          /* Number of bytes to return. */
56744   int key,          /* If true, retrieve from the btree key, not data. */
56745   Mem *pMem         /* OUT: Return data in this Mem structure. */
56746 ){
56747   char *zData;        /* Data from the btree layer */
56748   int available = 0;  /* Number of bytes available on the local btree page */
56749   int rc = SQLITE_OK; /* Return code */
56750
56751   assert( sqlite3BtreeCursorIsValid(pCur) );
56752
56753   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
56754   ** that both the BtShared and database handle mutexes are held. */
56755   assert( (pMem->flags & MEM_RowSet)==0 );
56756   if( key ){
56757     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
56758   }else{
56759     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
56760   }
56761   assert( zData!=0 );
56762
56763   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
56764     sqlite3VdbeMemRelease(pMem);
56765     pMem->z = &zData[offset];
56766     pMem->flags = MEM_Blob|MEM_Ephem;
56767   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
56768     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
56769     pMem->enc = 0;
56770     pMem->type = SQLITE_BLOB;
56771     if( key ){
56772       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
56773     }else{
56774       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
56775     }
56776     pMem->z[amt] = 0;
56777     pMem->z[amt+1] = 0;
56778     if( rc!=SQLITE_OK ){
56779       sqlite3VdbeMemRelease(pMem);
56780     }
56781   }
56782   pMem->n = amt;
56783
56784   return rc;
56785 }
56786
56787 /* This function is only available internally, it is not part of the
56788 ** external API. It works in a similar way to sqlite3_value_text(),
56789 ** except the data returned is in the encoding specified by the second
56790 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
56791 ** SQLITE_UTF8.
56792 **
56793 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
56794 ** If that is the case, then the result must be aligned on an even byte
56795 ** boundary.
56796 */
56797 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
56798   if( !pVal ) return 0;
56799
56800   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
56801   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
56802   assert( (pVal->flags & MEM_RowSet)==0 );
56803
56804   if( pVal->flags&MEM_Null ){
56805     return 0;
56806   }
56807   assert( (MEM_Blob>>3) == MEM_Str );
56808   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
56809   expandBlob(pVal);
56810   if( pVal->flags&MEM_Str ){
56811     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
56812     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
56813       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
56814       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
56815         return 0;
56816       }
56817     }
56818     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
56819   }else{
56820     assert( (pVal->flags&MEM_Blob)==0 );
56821     sqlite3VdbeMemStringify(pVal, enc);
56822     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
56823   }
56824   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
56825               || pVal->db->mallocFailed );
56826   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
56827     return pVal->z;
56828   }else{
56829     return 0;
56830   }
56831 }
56832
56833 /*
56834 ** Create a new sqlite3_value object.
56835 */
56836 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
56837   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
56838   if( p ){
56839     p->flags = MEM_Null;
56840     p->type = SQLITE_NULL;
56841     p->db = db;
56842   }
56843   return p;
56844 }
56845
56846 /*
56847 ** Create a new sqlite3_value object, containing the value of pExpr.
56848 **
56849 ** This only works for very simple expressions that consist of one constant
56850 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
56851 ** be converted directly into a value, then the value is allocated and
56852 ** a pointer written to *ppVal. The caller is responsible for deallocating
56853 ** the value by passing it to sqlite3ValueFree() later on. If the expression
56854 ** cannot be converted to a value, then *ppVal is set to NULL.
56855 */
56856 SQLITE_PRIVATE int sqlite3ValueFromExpr(
56857   sqlite3 *db,              /* The database connection */
56858   Expr *pExpr,              /* The expression to evaluate */
56859   u8 enc,                   /* Encoding to use */
56860   u8 affinity,              /* Affinity to use */
56861   sqlite3_value **ppVal     /* Write the new value here */
56862 ){
56863   int op;
56864   char *zVal = 0;
56865   sqlite3_value *pVal = 0;
56866   int negInt = 1;
56867   const char *zNeg = "";
56868
56869   if( !pExpr ){
56870     *ppVal = 0;
56871     return SQLITE_OK;
56872   }
56873   op = pExpr->op;
56874
56875   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
56876   ** The ifdef here is to enable us to achieve 100% branch test coverage even
56877   ** when SQLITE_ENABLE_STAT2 is omitted.
56878   */
56879 #ifdef SQLITE_ENABLE_STAT2
56880   if( op==TK_REGISTER ) op = pExpr->op2;
56881 #else
56882   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
56883 #endif
56884
56885   /* Handle negative integers in a single step.  This is needed in the
56886   ** case when the value is -9223372036854775808.
56887   */
56888   if( op==TK_UMINUS
56889    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
56890     pExpr = pExpr->pLeft;
56891     op = pExpr->op;
56892     negInt = -1;
56893     zNeg = "-";
56894   }
56895
56896   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
56897     pVal = sqlite3ValueNew(db);
56898     if( pVal==0 ) goto no_mem;
56899     if( ExprHasProperty(pExpr, EP_IntValue) ){
56900       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
56901     }else{
56902       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
56903       if( zVal==0 ) goto no_mem;
56904       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
56905       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
56906     }
56907     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
56908       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
56909     }else{
56910       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
56911     }
56912     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
56913     if( enc!=SQLITE_UTF8 ){
56914       sqlite3VdbeChangeEncoding(pVal, enc);
56915     }
56916   }else if( op==TK_UMINUS ) {
56917     /* This branch happens for multiple negative signs.  Ex: -(-5) */
56918     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
56919       sqlite3VdbeMemNumerify(pVal);
56920       if( pVal->u.i==SMALLEST_INT64 ){
56921         pVal->flags &= MEM_Int;
56922         pVal->flags |= MEM_Real;
56923         pVal->r = (double)LARGEST_INT64;
56924       }else{
56925         pVal->u.i = -pVal->u.i;
56926       }
56927       pVal->r = -pVal->r;
56928       sqlite3ValueApplyAffinity(pVal, affinity, enc);
56929     }
56930   }else if( op==TK_NULL ){
56931     pVal = sqlite3ValueNew(db);
56932     if( pVal==0 ) goto no_mem;
56933   }
56934 #ifndef SQLITE_OMIT_BLOB_LITERAL
56935   else if( op==TK_BLOB ){
56936     int nVal;
56937     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
56938     assert( pExpr->u.zToken[1]=='\'' );
56939     pVal = sqlite3ValueNew(db);
56940     if( !pVal ) goto no_mem;
56941     zVal = &pExpr->u.zToken[2];
56942     nVal = sqlite3Strlen30(zVal)-1;
56943     assert( zVal[nVal]=='\'' );
56944     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
56945                          0, SQLITE_DYNAMIC);
56946   }
56947 #endif
56948
56949   if( pVal ){
56950     sqlite3VdbeMemStoreType(pVal);
56951   }
56952   *ppVal = pVal;
56953   return SQLITE_OK;
56954
56955 no_mem:
56956   db->mallocFailed = 1;
56957   sqlite3DbFree(db, zVal);
56958   sqlite3ValueFree(pVal);
56959   *ppVal = 0;
56960   return SQLITE_NOMEM;
56961 }
56962
56963 /*
56964 ** Change the string value of an sqlite3_value object
56965 */
56966 SQLITE_PRIVATE void sqlite3ValueSetStr(
56967   sqlite3_value *v,     /* Value to be set */
56968   int n,                /* Length of string z */
56969   const void *z,        /* Text of the new string */
56970   u8 enc,               /* Encoding to use */
56971   void (*xDel)(void*)   /* Destructor for the string */
56972 ){
56973   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
56974 }
56975
56976 /*
56977 ** Free an sqlite3_value object
56978 */
56979 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
56980   if( !v ) return;
56981   sqlite3VdbeMemRelease((Mem *)v);
56982   sqlite3DbFree(((Mem*)v)->db, v);
56983 }
56984
56985 /*
56986 ** Return the number of bytes in the sqlite3_value object assuming
56987 ** that it uses the encoding "enc"
56988 */
56989 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
56990   Mem *p = (Mem*)pVal;
56991   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
56992     if( p->flags & MEM_Zero ){
56993       return p->n + p->u.nZero;
56994     }else{
56995       return p->n;
56996     }
56997   }
56998   return 0;
56999 }
57000
57001 /************** End of vdbemem.c *********************************************/
57002 /************** Begin file vdbeaux.c *****************************************/
57003 /*
57004 ** 2003 September 6
57005 **
57006 ** The author disclaims copyright to this source code.  In place of
57007 ** a legal notice, here is a blessing:
57008 **
57009 **    May you do good and not evil.
57010 **    May you find forgiveness for yourself and forgive others.
57011 **    May you share freely, never taking more than you give.
57012 **
57013 *************************************************************************
57014 ** This file contains code used for creating, destroying, and populating
57015 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
57016 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
57017 ** But that file was getting too big so this subroutines were split out.
57018 */
57019
57020
57021
57022 /*
57023 ** When debugging the code generator in a symbolic debugger, one can
57024 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57025 ** as they are added to the instruction stream.
57026 */
57027 #ifdef SQLITE_DEBUG
57028 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57029 #endif
57030
57031
57032 /*
57033 ** Create a new virtual database engine.
57034 */
57035 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57036   Vdbe *p;
57037   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57038   if( p==0 ) return 0;
57039   p->db = db;
57040   if( db->pVdbe ){
57041     db->pVdbe->pPrev = p;
57042   }
57043   p->pNext = db->pVdbe;
57044   p->pPrev = 0;
57045   db->pVdbe = p;
57046   p->magic = VDBE_MAGIC_INIT;
57047   return p;
57048 }
57049
57050 /*
57051 ** Remember the SQL string for a prepared statement.
57052 */
57053 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57054   assert( isPrepareV2==1 || isPrepareV2==0 );
57055   if( p==0 ) return;
57056 #ifdef SQLITE_OMIT_TRACE
57057   if( !isPrepareV2 ) return;
57058 #endif
57059   assert( p->zSql==0 );
57060   p->zSql = sqlite3DbStrNDup(p->db, z, n);
57061   p->isPrepareV2 = (u8)isPrepareV2;
57062 }
57063
57064 /*
57065 ** Return the SQL associated with a prepared statement
57066 */
57067 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57068   Vdbe *p = (Vdbe *)pStmt;
57069   return (p && p->isPrepareV2) ? p->zSql : 0;
57070 }
57071
57072 /*
57073 ** Swap all content between two VDBE structures.
57074 */
57075 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57076   Vdbe tmp, *pTmp;
57077   char *zTmp;
57078   tmp = *pA;
57079   *pA = *pB;
57080   *pB = tmp;
57081   pTmp = pA->pNext;
57082   pA->pNext = pB->pNext;
57083   pB->pNext = pTmp;
57084   pTmp = pA->pPrev;
57085   pA->pPrev = pB->pPrev;
57086   pB->pPrev = pTmp;
57087   zTmp = pA->zSql;
57088   pA->zSql = pB->zSql;
57089   pB->zSql = zTmp;
57090   pB->isPrepareV2 = pA->isPrepareV2;
57091 }
57092
57093 #ifdef SQLITE_DEBUG
57094 /*
57095 ** Turn tracing on or off
57096 */
57097 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57098   p->trace = trace;
57099 }
57100 #endif
57101
57102 /*
57103 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
57104 ** it was.
57105 **
57106 ** If an out-of-memory error occurs while resizing the array, return
57107 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
57108 ** unchanged (this is so that any opcodes already allocated can be 
57109 ** correctly deallocated along with the rest of the Vdbe).
57110 */
57111 static int growOpArray(Vdbe *p){
57112   VdbeOp *pNew;
57113   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57114   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57115   if( pNew ){
57116     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57117     p->aOp = pNew;
57118   }
57119   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57120 }
57121
57122 /*
57123 ** Add a new instruction to the list of instructions current in the
57124 ** VDBE.  Return the address of the new instruction.
57125 **
57126 ** Parameters:
57127 **
57128 **    p               Pointer to the VDBE
57129 **
57130 **    op              The opcode for this instruction
57131 **
57132 **    p1, p2, p3      Operands
57133 **
57134 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
57135 ** the sqlite3VdbeChangeP4() function to change the value of the P4
57136 ** operand.
57137 */
57138 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57139   int i;
57140   VdbeOp *pOp;
57141
57142   i = p->nOp;
57143   assert( p->magic==VDBE_MAGIC_INIT );
57144   assert( op>0 && op<0xff );
57145   if( p->nOpAlloc<=i ){
57146     if( growOpArray(p) ){
57147       return 1;
57148     }
57149   }
57150   p->nOp++;
57151   pOp = &p->aOp[i];
57152   pOp->opcode = (u8)op;
57153   pOp->p5 = 0;
57154   pOp->p1 = p1;
57155   pOp->p2 = p2;
57156   pOp->p3 = p3;
57157   pOp->p4.p = 0;
57158   pOp->p4type = P4_NOTUSED;
57159   p->expired = 0;
57160   if( op==OP_ParseSchema ){
57161     /* Any program that uses the OP_ParseSchema opcode needs to lock
57162     ** all btrees. */
57163     int j;
57164     for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57165   }
57166 #ifdef SQLITE_DEBUG
57167   pOp->zComment = 0;
57168   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57169 #endif
57170 #ifdef VDBE_PROFILE
57171   pOp->cycles = 0;
57172   pOp->cnt = 0;
57173 #endif
57174   return i;
57175 }
57176 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57177   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57178 }
57179 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57180   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57181 }
57182 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57183   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57184 }
57185
57186
57187 /*
57188 ** Add an opcode that includes the p4 value as a pointer.
57189 */
57190 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57191   Vdbe *p,            /* Add the opcode to this VM */
57192   int op,             /* The new opcode */
57193   int p1,             /* The P1 operand */
57194   int p2,             /* The P2 operand */
57195   int p3,             /* The P3 operand */
57196   const char *zP4,    /* The P4 operand */
57197   int p4type          /* P4 operand type */
57198 ){
57199   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57200   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57201   return addr;
57202 }
57203
57204 /*
57205 ** Add an opcode that includes the p4 value as an integer.
57206 */
57207 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57208   Vdbe *p,            /* Add the opcode to this VM */
57209   int op,             /* The new opcode */
57210   int p1,             /* The P1 operand */
57211   int p2,             /* The P2 operand */
57212   int p3,             /* The P3 operand */
57213   int p4              /* The P4 operand as an integer */
57214 ){
57215   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57216   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57217   return addr;
57218 }
57219
57220 /*
57221 ** Create a new symbolic label for an instruction that has yet to be
57222 ** coded.  The symbolic label is really just a negative number.  The
57223 ** label can be used as the P2 value of an operation.  Later, when
57224 ** the label is resolved to a specific address, the VDBE will scan
57225 ** through its operation list and change all values of P2 which match
57226 ** the label into the resolved address.
57227 **
57228 ** The VDBE knows that a P2 value is a label because labels are
57229 ** always negative and P2 values are suppose to be non-negative.
57230 ** Hence, a negative P2 value is a label that has yet to be resolved.
57231 **
57232 ** Zero is returned if a malloc() fails.
57233 */
57234 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57235   int i;
57236   i = p->nLabel++;
57237   assert( p->magic==VDBE_MAGIC_INIT );
57238   if( i>=p->nLabelAlloc ){
57239     int n = p->nLabelAlloc*2 + 5;
57240     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57241                                        n*sizeof(p->aLabel[0]));
57242     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57243   }
57244   if( p->aLabel ){
57245     p->aLabel[i] = -1;
57246   }
57247   return -1-i;
57248 }
57249
57250 /*
57251 ** Resolve label "x" to be the address of the next instruction to
57252 ** be inserted.  The parameter "x" must have been obtained from
57253 ** a prior call to sqlite3VdbeMakeLabel().
57254 */
57255 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57256   int j = -1-x;
57257   assert( p->magic==VDBE_MAGIC_INIT );
57258   assert( j>=0 && j<p->nLabel );
57259   if( p->aLabel ){
57260     p->aLabel[j] = p->nOp;
57261   }
57262 }
57263
57264 /*
57265 ** Mark the VDBE as one that can only be run one time.
57266 */
57267 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57268   p->runOnlyOnce = 1;
57269 }
57270
57271 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57272
57273 /*
57274 ** The following type and function are used to iterate through all opcodes
57275 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
57276 ** invoke directly or indirectly. It should be used as follows:
57277 **
57278 **   Op *pOp;
57279 **   VdbeOpIter sIter;
57280 **
57281 **   memset(&sIter, 0, sizeof(sIter));
57282 **   sIter.v = v;                            // v is of type Vdbe* 
57283 **   while( (pOp = opIterNext(&sIter)) ){
57284 **     // Do something with pOp
57285 **   }
57286 **   sqlite3DbFree(v->db, sIter.apSub);
57287 ** 
57288 */
57289 typedef struct VdbeOpIter VdbeOpIter;
57290 struct VdbeOpIter {
57291   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
57292   SubProgram **apSub;        /* Array of subprograms */
57293   int nSub;                  /* Number of entries in apSub */
57294   int iAddr;                 /* Address of next instruction to return */
57295   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
57296 };
57297 static Op *opIterNext(VdbeOpIter *p){
57298   Vdbe *v = p->v;
57299   Op *pRet = 0;
57300   Op *aOp;
57301   int nOp;
57302
57303   if( p->iSub<=p->nSub ){
57304
57305     if( p->iSub==0 ){
57306       aOp = v->aOp;
57307       nOp = v->nOp;
57308     }else{
57309       aOp = p->apSub[p->iSub-1]->aOp;
57310       nOp = p->apSub[p->iSub-1]->nOp;
57311     }
57312     assert( p->iAddr<nOp );
57313
57314     pRet = &aOp[p->iAddr];
57315     p->iAddr++;
57316     if( p->iAddr==nOp ){
57317       p->iSub++;
57318       p->iAddr = 0;
57319     }
57320   
57321     if( pRet->p4type==P4_SUBPROGRAM ){
57322       int nByte = (p->nSub+1)*sizeof(SubProgram*);
57323       int j;
57324       for(j=0; j<p->nSub; j++){
57325         if( p->apSub[j]==pRet->p4.pProgram ) break;
57326       }
57327       if( j==p->nSub ){
57328         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57329         if( !p->apSub ){
57330           pRet = 0;
57331         }else{
57332           p->apSub[p->nSub++] = pRet->p4.pProgram;
57333         }
57334       }
57335     }
57336   }
57337
57338   return pRet;
57339 }
57340
57341 /*
57342 ** Check if the program stored in the VM associated with pParse may
57343 ** throw an ABORT exception (causing the statement, but not entire transaction
57344 ** to be rolled back). This condition is true if the main program or any
57345 ** sub-programs contains any of the following:
57346 **
57347 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57348 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57349 **   *  OP_Destroy
57350 **   *  OP_VUpdate
57351 **   *  OP_VRename
57352 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
57353 **
57354 ** Then check that the value of Parse.mayAbort is true if an
57355 ** ABORT may be thrown, or false otherwise. Return true if it does
57356 ** match, or false otherwise. This function is intended to be used as
57357 ** part of an assert statement in the compiler. Similar to:
57358 **
57359 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57360 */
57361 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57362   int hasAbort = 0;
57363   Op *pOp;
57364   VdbeOpIter sIter;
57365   memset(&sIter, 0, sizeof(sIter));
57366   sIter.v = v;
57367
57368   while( (pOp = opIterNext(&sIter))!=0 ){
57369     int opcode = pOp->opcode;
57370     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
57371 #ifndef SQLITE_OMIT_FOREIGN_KEY
57372      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
57373 #endif
57374      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
57375       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57376     ){
57377       hasAbort = 1;
57378       break;
57379     }
57380   }
57381   sqlite3DbFree(v->db, sIter.apSub);
57382
57383   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57384   ** If malloc failed, then the while() loop above may not have iterated
57385   ** through all opcodes and hasAbort may be set incorrectly. Return
57386   ** true for this case to prevent the assert() in the callers frame
57387   ** from failing.  */
57388   return ( v->db->mallocFailed || hasAbort==mayAbort );
57389 }
57390 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57391
57392 /*
57393 ** Loop through the program looking for P2 values that are negative
57394 ** on jump instructions.  Each such value is a label.  Resolve the
57395 ** label by setting the P2 value to its correct non-zero value.
57396 **
57397 ** This routine is called once after all opcodes have been inserted.
57398 **
57399 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
57400 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
57401 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57402 **
57403 ** The Op.opflags field is set on all opcodes.
57404 */
57405 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57406   int i;
57407   int nMaxArgs = *pMaxFuncArgs;
57408   Op *pOp;
57409   int *aLabel = p->aLabel;
57410   p->readOnly = 1;
57411   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57412     u8 opcode = pOp->opcode;
57413
57414     pOp->opflags = sqlite3OpcodeProperty[opcode];
57415     if( opcode==OP_Function || opcode==OP_AggStep ){
57416       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57417     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57418       p->readOnly = 0;
57419 #ifndef SQLITE_OMIT_VIRTUALTABLE
57420     }else if( opcode==OP_VUpdate ){
57421       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57422     }else if( opcode==OP_VFilter ){
57423       int n;
57424       assert( p->nOp - i >= 3 );
57425       assert( pOp[-1].opcode==OP_Integer );
57426       n = pOp[-1].p1;
57427       if( n>nMaxArgs ) nMaxArgs = n;
57428 #endif
57429     }
57430
57431     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57432       assert( -1-pOp->p2<p->nLabel );
57433       pOp->p2 = aLabel[-1-pOp->p2];
57434     }
57435   }
57436   sqlite3DbFree(p->db, p->aLabel);
57437   p->aLabel = 0;
57438
57439   *pMaxFuncArgs = nMaxArgs;
57440 }
57441
57442 /*
57443 ** Return the address of the next instruction to be inserted.
57444 */
57445 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57446   assert( p->magic==VDBE_MAGIC_INIT );
57447   return p->nOp;
57448 }
57449
57450 /*
57451 ** This function returns a pointer to the array of opcodes associated with
57452 ** the Vdbe passed as the first argument. It is the callers responsibility
57453 ** to arrange for the returned array to be eventually freed using the 
57454 ** vdbeFreeOpArray() function.
57455 **
57456 ** Before returning, *pnOp is set to the number of entries in the returned
57457 ** array. Also, *pnMaxArg is set to the larger of its current value and 
57458 ** the number of entries in the Vdbe.apArg[] array required to execute the 
57459 ** returned program.
57460 */
57461 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
57462   VdbeOp *aOp = p->aOp;
57463   assert( aOp && !p->db->mallocFailed );
57464
57465   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
57466   assert( p->btreeMask==0 );
57467
57468   resolveP2Values(p, pnMaxArg);
57469   *pnOp = p->nOp;
57470   p->aOp = 0;
57471   return aOp;
57472 }
57473
57474 /*
57475 ** Add a whole list of operations to the operation stack.  Return the
57476 ** address of the first operation added.
57477 */
57478 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
57479   int addr;
57480   assert( p->magic==VDBE_MAGIC_INIT );
57481   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
57482     return 0;
57483   }
57484   addr = p->nOp;
57485   if( ALWAYS(nOp>0) ){
57486     int i;
57487     VdbeOpList const *pIn = aOp;
57488     for(i=0; i<nOp; i++, pIn++){
57489       int p2 = pIn->p2;
57490       VdbeOp *pOut = &p->aOp[i+addr];
57491       pOut->opcode = pIn->opcode;
57492       pOut->p1 = pIn->p1;
57493       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
57494         pOut->p2 = addr + ADDR(p2);
57495       }else{
57496         pOut->p2 = p2;
57497       }
57498       pOut->p3 = pIn->p3;
57499       pOut->p4type = P4_NOTUSED;
57500       pOut->p4.p = 0;
57501       pOut->p5 = 0;
57502 #ifdef SQLITE_DEBUG
57503       pOut->zComment = 0;
57504       if( sqlite3VdbeAddopTrace ){
57505         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
57506       }
57507 #endif
57508     }
57509     p->nOp += nOp;
57510   }
57511   return addr;
57512 }
57513
57514 /*
57515 ** Change the value of the P1 operand for a specific instruction.
57516 ** This routine is useful when a large program is loaded from a
57517 ** static array using sqlite3VdbeAddOpList but we want to make a
57518 ** few minor changes to the program.
57519 */
57520 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
57521   assert( p!=0 );
57522   assert( addr>=0 );
57523   if( p->nOp>addr ){
57524     p->aOp[addr].p1 = val;
57525   }
57526 }
57527
57528 /*
57529 ** Change the value of the P2 operand for a specific instruction.
57530 ** This routine is useful for setting a jump destination.
57531 */
57532 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
57533   assert( p!=0 );
57534   assert( addr>=0 );
57535   if( p->nOp>addr ){
57536     p->aOp[addr].p2 = val;
57537   }
57538 }
57539
57540 /*
57541 ** Change the value of the P3 operand for a specific instruction.
57542 */
57543 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
57544   assert( p!=0 );
57545   assert( addr>=0 );
57546   if( p->nOp>addr ){
57547     p->aOp[addr].p3 = val;
57548   }
57549 }
57550
57551 /*
57552 ** Change the value of the P5 operand for the most recently
57553 ** added operation.
57554 */
57555 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
57556   assert( p!=0 );
57557   if( p->aOp ){
57558     assert( p->nOp>0 );
57559     p->aOp[p->nOp-1].p5 = val;
57560   }
57561 }
57562
57563 /*
57564 ** Change the P2 operand of instruction addr so that it points to
57565 ** the address of the next instruction to be coded.
57566 */
57567 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
57568   assert( addr>=0 );
57569   sqlite3VdbeChangeP2(p, addr, p->nOp);
57570 }
57571
57572
57573 /*
57574 ** If the input FuncDef structure is ephemeral, then free it.  If
57575 ** the FuncDef is not ephermal, then do nothing.
57576 */
57577 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
57578   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
57579     sqlite3DbFree(db, pDef);
57580   }
57581 }
57582
57583 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
57584
57585 /*
57586 ** Delete a P4 value if necessary.
57587 */
57588 static void freeP4(sqlite3 *db, int p4type, void *p4){
57589   if( p4 ){
57590     assert( db );
57591     switch( p4type ){
57592       case P4_REAL:
57593       case P4_INT64:
57594       case P4_DYNAMIC:
57595       case P4_KEYINFO:
57596       case P4_INTARRAY:
57597       case P4_KEYINFO_HANDOFF: {
57598         sqlite3DbFree(db, p4);
57599         break;
57600       }
57601       case P4_MPRINTF: {
57602         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
57603         break;
57604       }
57605       case P4_VDBEFUNC: {
57606         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
57607         freeEphemeralFunction(db, pVdbeFunc->pFunc);
57608         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
57609         sqlite3DbFree(db, pVdbeFunc);
57610         break;
57611       }
57612       case P4_FUNCDEF: {
57613         freeEphemeralFunction(db, (FuncDef*)p4);
57614         break;
57615       }
57616       case P4_MEM: {
57617         if( db->pnBytesFreed==0 ){
57618           sqlite3ValueFree((sqlite3_value*)p4);
57619         }else{
57620           Mem *p = (Mem*)p4;
57621           sqlite3DbFree(db, p->zMalloc);
57622           sqlite3DbFree(db, p);
57623         }
57624         break;
57625       }
57626       case P4_VTAB : {
57627         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
57628         break;
57629       }
57630     }
57631   }
57632 }
57633
57634 /*
57635 ** Free the space allocated for aOp and any p4 values allocated for the
57636 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
57637 ** nOp entries. 
57638 */
57639 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
57640   if( aOp ){
57641     Op *pOp;
57642     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
57643       freeP4(db, pOp->p4type, pOp->p4.p);
57644 #ifdef SQLITE_DEBUG
57645       sqlite3DbFree(db, pOp->zComment);
57646 #endif     
57647     }
57648   }
57649   sqlite3DbFree(db, aOp);
57650 }
57651
57652 /*
57653 ** Link the SubProgram object passed as the second argument into the linked
57654 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
57655 ** objects when the VM is no longer required.
57656 */
57657 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
57658   p->pNext = pVdbe->pProgram;
57659   pVdbe->pProgram = p;
57660 }
57661
57662 /*
57663 ** Change N opcodes starting at addr to No-ops.
57664 */
57665 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
57666   if( p->aOp ){
57667     VdbeOp *pOp = &p->aOp[addr];
57668     sqlite3 *db = p->db;
57669     while( N-- ){
57670       freeP4(db, pOp->p4type, pOp->p4.p);
57671       memset(pOp, 0, sizeof(pOp[0]));
57672       pOp->opcode = OP_Noop;
57673       pOp++;
57674     }
57675   }
57676 }
57677
57678 /*
57679 ** Change the value of the P4 operand for a specific instruction.
57680 ** This routine is useful when a large program is loaded from a
57681 ** static array using sqlite3VdbeAddOpList but we want to make a
57682 ** few minor changes to the program.
57683 **
57684 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
57685 ** the string is made into memory obtained from sqlite3_malloc().
57686 ** A value of n==0 means copy bytes of zP4 up to and including the
57687 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
57688 **
57689 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
57690 ** A copy is made of the KeyInfo structure into memory obtained from
57691 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
57692 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
57693 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
57694 ** caller should not free the allocation, it will be freed when the Vdbe is
57695 ** finalized.
57696 ** 
57697 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
57698 ** to a string or structure that is guaranteed to exist for the lifetime of
57699 ** the Vdbe. In these cases we can just copy the pointer.
57700 **
57701 ** If addr<0 then change P4 on the most recently inserted instruction.
57702 */
57703 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
57704   Op *pOp;
57705   sqlite3 *db;
57706   assert( p!=0 );
57707   db = p->db;
57708   assert( p->magic==VDBE_MAGIC_INIT );
57709   if( p->aOp==0 || db->mallocFailed ){
57710     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
57711       freeP4(db, n, (void*)*(char**)&zP4);
57712     }
57713     return;
57714   }
57715   assert( p->nOp>0 );
57716   assert( addr<p->nOp );
57717   if( addr<0 ){
57718     addr = p->nOp - 1;
57719   }
57720   pOp = &p->aOp[addr];
57721   freeP4(db, pOp->p4type, pOp->p4.p);
57722   pOp->p4.p = 0;
57723   if( n==P4_INT32 ){
57724     /* Note: this cast is safe, because the origin data point was an int
57725     ** that was cast to a (const char *). */
57726     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
57727     pOp->p4type = P4_INT32;
57728   }else if( zP4==0 ){
57729     pOp->p4.p = 0;
57730     pOp->p4type = P4_NOTUSED;
57731   }else if( n==P4_KEYINFO ){
57732     KeyInfo *pKeyInfo;
57733     int nField, nByte;
57734
57735     nField = ((KeyInfo*)zP4)->nField;
57736     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
57737     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
57738     pOp->p4.pKeyInfo = pKeyInfo;
57739     if( pKeyInfo ){
57740       u8 *aSortOrder;
57741       memcpy((char*)pKeyInfo, zP4, nByte - nField);
57742       aSortOrder = pKeyInfo->aSortOrder;
57743       if( aSortOrder ){
57744         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
57745         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
57746       }
57747       pOp->p4type = P4_KEYINFO;
57748     }else{
57749       p->db->mallocFailed = 1;
57750       pOp->p4type = P4_NOTUSED;
57751     }
57752   }else if( n==P4_KEYINFO_HANDOFF ){
57753     pOp->p4.p = (void*)zP4;
57754     pOp->p4type = P4_KEYINFO;
57755   }else if( n==P4_VTAB ){
57756     pOp->p4.p = (void*)zP4;
57757     pOp->p4type = P4_VTAB;
57758     sqlite3VtabLock((VTable *)zP4);
57759     assert( ((VTable *)zP4)->db==p->db );
57760   }else if( n<0 ){
57761     pOp->p4.p = (void*)zP4;
57762     pOp->p4type = (signed char)n;
57763   }else{
57764     if( n==0 ) n = sqlite3Strlen30(zP4);
57765     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
57766     pOp->p4type = P4_DYNAMIC;
57767   }
57768 }
57769
57770 #ifndef NDEBUG
57771 /*
57772 ** Change the comment on the the most recently coded instruction.  Or
57773 ** insert a No-op and add the comment to that new instruction.  This
57774 ** makes the code easier to read during debugging.  None of this happens
57775 ** in a production build.
57776 */
57777 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
57778   va_list ap;
57779   if( !p ) return;
57780   assert( p->nOp>0 || p->aOp==0 );
57781   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57782   if( p->nOp ){
57783     char **pz = &p->aOp[p->nOp-1].zComment;
57784     va_start(ap, zFormat);
57785     sqlite3DbFree(p->db, *pz);
57786     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57787     va_end(ap);
57788   }
57789 }
57790 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
57791   va_list ap;
57792   if( !p ) return;
57793   sqlite3VdbeAddOp0(p, OP_Noop);
57794   assert( p->nOp>0 || p->aOp==0 );
57795   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
57796   if( p->nOp ){
57797     char **pz = &p->aOp[p->nOp-1].zComment;
57798     va_start(ap, zFormat);
57799     sqlite3DbFree(p->db, *pz);
57800     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
57801     va_end(ap);
57802   }
57803 }
57804 #endif  /* NDEBUG */
57805
57806 /*
57807 ** Return the opcode for a given address.  If the address is -1, then
57808 ** return the most recently inserted opcode.
57809 **
57810 ** If a memory allocation error has occurred prior to the calling of this
57811 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
57812 ** is readable but not writable, though it is cast to a writable value.
57813 ** The return of a dummy opcode allows the call to continue functioning
57814 ** after a OOM fault without having to check to see if the return from 
57815 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
57816 ** dummy will never be written to.  This is verified by code inspection and
57817 ** by running with Valgrind.
57818 **
57819 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
57820 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
57821 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
57822 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
57823 ** having to double-check to make sure that the result is non-negative. But
57824 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
57825 ** check the value of p->nOp-1 before continuing.
57826 */
57827 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
57828   /* C89 specifies that the constant "dummy" will be initialized to all
57829   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
57830   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
57831   assert( p->magic==VDBE_MAGIC_INIT );
57832   if( addr<0 ){
57833 #ifdef SQLITE_OMIT_TRACE
57834     if( p->nOp==0 ) return (VdbeOp*)&dummy;
57835 #endif
57836     addr = p->nOp - 1;
57837   }
57838   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
57839   if( p->db->mallocFailed ){
57840     return (VdbeOp*)&dummy;
57841   }else{
57842     return &p->aOp[addr];
57843   }
57844 }
57845
57846 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
57847      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
57848 /*
57849 ** Compute a string that describes the P4 parameter for an opcode.
57850 ** Use zTemp for any required temporary buffer space.
57851 */
57852 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
57853   char *zP4 = zTemp;
57854   assert( nTemp>=20 );
57855   switch( pOp->p4type ){
57856     case P4_KEYINFO_STATIC:
57857     case P4_KEYINFO: {
57858       int i, j;
57859       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
57860       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
57861       i = sqlite3Strlen30(zTemp);
57862       for(j=0; j<pKeyInfo->nField; j++){
57863         CollSeq *pColl = pKeyInfo->aColl[j];
57864         if( pColl ){
57865           int n = sqlite3Strlen30(pColl->zName);
57866           if( i+n>nTemp-6 ){
57867             memcpy(&zTemp[i],",...",4);
57868             break;
57869           }
57870           zTemp[i++] = ',';
57871           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
57872             zTemp[i++] = '-';
57873           }
57874           memcpy(&zTemp[i], pColl->zName,n+1);
57875           i += n;
57876         }else if( i+4<nTemp-6 ){
57877           memcpy(&zTemp[i],",nil",4);
57878           i += 4;
57879         }
57880       }
57881       zTemp[i++] = ')';
57882       zTemp[i] = 0;
57883       assert( i<nTemp );
57884       break;
57885     }
57886     case P4_COLLSEQ: {
57887       CollSeq *pColl = pOp->p4.pColl;
57888       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
57889       break;
57890     }
57891     case P4_FUNCDEF: {
57892       FuncDef *pDef = pOp->p4.pFunc;
57893       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
57894       break;
57895     }
57896     case P4_INT64: {
57897       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
57898       break;
57899     }
57900     case P4_INT32: {
57901       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
57902       break;
57903     }
57904     case P4_REAL: {
57905       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
57906       break;
57907     }
57908     case P4_MEM: {
57909       Mem *pMem = pOp->p4.pMem;
57910       assert( (pMem->flags & MEM_Null)==0 );
57911       if( pMem->flags & MEM_Str ){
57912         zP4 = pMem->z;
57913       }else if( pMem->flags & MEM_Int ){
57914         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
57915       }else if( pMem->flags & MEM_Real ){
57916         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
57917       }else{
57918         assert( pMem->flags & MEM_Blob );
57919         zP4 = "(blob)";
57920       }
57921       break;
57922     }
57923 #ifndef SQLITE_OMIT_VIRTUALTABLE
57924     case P4_VTAB: {
57925       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
57926       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
57927       break;
57928     }
57929 #endif
57930     case P4_INTARRAY: {
57931       sqlite3_snprintf(nTemp, zTemp, "intarray");
57932       break;
57933     }
57934     case P4_SUBPROGRAM: {
57935       sqlite3_snprintf(nTemp, zTemp, "program");
57936       break;
57937     }
57938     default: {
57939       zP4 = pOp->p4.z;
57940       if( zP4==0 ){
57941         zP4 = zTemp;
57942         zTemp[0] = 0;
57943       }
57944     }
57945   }
57946   assert( zP4!=0 );
57947   return zP4;
57948 }
57949 #endif
57950
57951 /*
57952 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
57953 **
57954 ** The prepared statements need to know in advance the complete set of
57955 ** attached databases that they will be using.  A mask of these databases
57956 ** is maintained in p->btreeMask and is used for locking and other purposes.
57957 */
57958 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
57959   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
57960   assert( i<(int)sizeof(p->btreeMask)*8 );
57961   p->btreeMask |= ((yDbMask)1)<<i;
57962   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
57963     p->lockMask |= ((yDbMask)1)<<i;
57964   }
57965 }
57966
57967 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
57968 /*
57969 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
57970 ** this routine obtains the mutex associated with each BtShared structure
57971 ** that may be accessed by the VM passed as an argument. In doing so it also
57972 ** sets the BtShared.db member of each of the BtShared structures, ensuring
57973 ** that the correct busy-handler callback is invoked if required.
57974 **
57975 ** If SQLite is not threadsafe but does support shared-cache mode, then
57976 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
57977 ** of all of BtShared structures accessible via the database handle 
57978 ** associated with the VM.
57979 **
57980 ** If SQLite is not threadsafe and does not support shared-cache mode, this
57981 ** function is a no-op.
57982 **
57983 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
57984 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
57985 ** corresponding to btrees that use shared cache.  Then the runtime of
57986 ** this routine is N*N.  But as N is rarely more than 1, this should not
57987 ** be a problem.
57988 */
57989 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
57990   int i;
57991   yDbMask mask;
57992   sqlite3 *db;
57993   Db *aDb;
57994   int nDb;
57995   if( p->lockMask==0 ) return;  /* The common case */
57996   db = p->db;
57997   aDb = db->aDb;
57998   nDb = db->nDb;
57999   for(i=0, mask=1; i<nDb; i++, mask += mask){
58000     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58001       sqlite3BtreeEnter(aDb[i].pBt);
58002     }
58003   }
58004 }
58005 #endif
58006
58007 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58008 /*
58009 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58010 */
58011 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58012   int i;
58013   yDbMask mask;
58014   sqlite3 *db;
58015   Db *aDb;
58016   int nDb;
58017   if( p->lockMask==0 ) return;  /* The common case */
58018   db = p->db;
58019   aDb = db->aDb;
58020   nDb = db->nDb;
58021   for(i=0, mask=1; i<nDb; i++, mask += mask){
58022     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58023       sqlite3BtreeLeave(aDb[i].pBt);
58024     }
58025   }
58026 }
58027 #endif
58028
58029 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58030 /*
58031 ** Print a single opcode.  This routine is used for debugging only.
58032 */
58033 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58034   char *zP4;
58035   char zPtr[50];
58036   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58037   if( pOut==0 ) pOut = stdout;
58038   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58039   fprintf(pOut, zFormat1, pc, 
58040       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58041 #ifdef SQLITE_DEBUG
58042       pOp->zComment ? pOp->zComment : ""
58043 #else
58044       ""
58045 #endif
58046   );
58047   fflush(pOut);
58048 }
58049 #endif
58050
58051 /*
58052 ** Release an array of N Mem elements
58053 */
58054 static void releaseMemArray(Mem *p, int N){
58055   if( p && N ){
58056     Mem *pEnd;
58057     sqlite3 *db = p->db;
58058     u8 malloc_failed = db->mallocFailed;
58059     if( db->pnBytesFreed ){
58060       for(pEnd=&p[N]; p<pEnd; p++){
58061         sqlite3DbFree(db, p->zMalloc);
58062       }
58063       return;
58064     }
58065     for(pEnd=&p[N]; p<pEnd; p++){
58066       assert( (&p[1])==pEnd || p[0].db==p[1].db );
58067
58068       /* This block is really an inlined version of sqlite3VdbeMemRelease()
58069       ** that takes advantage of the fact that the memory cell value is 
58070       ** being set to NULL after releasing any dynamic resources.
58071       **
58072       ** The justification for duplicating code is that according to 
58073       ** callgrind, this causes a certain test case to hit the CPU 4.7 
58074       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
58075       ** sqlite3MemRelease() were called from here. With -O2, this jumps
58076       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
58077       ** with no indexes using a single prepared INSERT statement, bind() 
58078       ** and reset(). Inserts are grouped into a transaction.
58079       */
58080       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58081         sqlite3VdbeMemRelease(p);
58082       }else if( p->zMalloc ){
58083         sqlite3DbFree(db, p->zMalloc);
58084         p->zMalloc = 0;
58085       }
58086
58087       p->flags = MEM_Null;
58088     }
58089     db->mallocFailed = malloc_failed;
58090   }
58091 }
58092
58093 /*
58094 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58095 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
58096 */
58097 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58098   int i;
58099   Mem *aMem = VdbeFrameMem(p);
58100   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58101   for(i=0; i<p->nChildCsr; i++){
58102     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58103   }
58104   releaseMemArray(aMem, p->nChildMem);
58105   sqlite3DbFree(p->v->db, p);
58106 }
58107
58108 #ifndef SQLITE_OMIT_EXPLAIN
58109 /*
58110 ** Give a listing of the program in the virtual machine.
58111 **
58112 ** The interface is the same as sqlite3VdbeExec().  But instead of
58113 ** running the code, it invokes the callback once for each instruction.
58114 ** This feature is used to implement "EXPLAIN".
58115 **
58116 ** When p->explain==1, each instruction is listed.  When
58117 ** p->explain==2, only OP_Explain instructions are listed and these
58118 ** are shown in a different format.  p->explain==2 is used to implement
58119 ** EXPLAIN QUERY PLAN.
58120 **
58121 ** When p->explain==1, first the main program is listed, then each of
58122 ** the trigger subprograms are listed one by one.
58123 */
58124 SQLITE_PRIVATE int sqlite3VdbeList(
58125   Vdbe *p                   /* The VDBE */
58126 ){
58127   int nRow;                            /* Stop when row count reaches this */
58128   int nSub = 0;                        /* Number of sub-vdbes seen so far */
58129   SubProgram **apSub = 0;              /* Array of sub-vdbes */
58130   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
58131   sqlite3 *db = p->db;                 /* The database connection */
58132   int i;                               /* Loop counter */
58133   int rc = SQLITE_OK;                  /* Return code */
58134   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
58135
58136   assert( p->explain );
58137   assert( p->magic==VDBE_MAGIC_RUN );
58138   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58139
58140   /* Even though this opcode does not use dynamic strings for
58141   ** the result, result columns may become dynamic if the user calls
58142   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58143   */
58144   releaseMemArray(pMem, 8);
58145
58146   if( p->rc==SQLITE_NOMEM ){
58147     /* This happens if a malloc() inside a call to sqlite3_column_text() or
58148     ** sqlite3_column_text16() failed.  */
58149     db->mallocFailed = 1;
58150     return SQLITE_ERROR;
58151   }
58152
58153   /* When the number of output rows reaches nRow, that means the
58154   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58155   ** nRow is the sum of the number of rows in the main program, plus
58156   ** the sum of the number of rows in all trigger subprograms encountered
58157   ** so far.  The nRow value will increase as new trigger subprograms are
58158   ** encountered, but p->pc will eventually catch up to nRow.
58159   */
58160   nRow = p->nOp;
58161   if( p->explain==1 ){
58162     /* The first 8 memory cells are used for the result set.  So we will
58163     ** commandeer the 9th cell to use as storage for an array of pointers
58164     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
58165     ** cells.  */
58166     assert( p->nMem>9 );
58167     pSub = &p->aMem[9];
58168     if( pSub->flags&MEM_Blob ){
58169       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
58170       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58171       nSub = pSub->n/sizeof(Vdbe*);
58172       apSub = (SubProgram **)pSub->z;
58173     }
58174     for(i=0; i<nSub; i++){
58175       nRow += apSub[i]->nOp;
58176     }
58177   }
58178
58179   do{
58180     i = p->pc++;
58181   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58182   if( i>=nRow ){
58183     p->rc = SQLITE_OK;
58184     rc = SQLITE_DONE;
58185   }else if( db->u1.isInterrupted ){
58186     p->rc = SQLITE_INTERRUPT;
58187     rc = SQLITE_ERROR;
58188     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58189   }else{
58190     char *z;
58191     Op *pOp;
58192     if( i<p->nOp ){
58193       /* The output line number is small enough that we are still in the
58194       ** main program. */
58195       pOp = &p->aOp[i];
58196     }else{
58197       /* We are currently listing subprograms.  Figure out which one and
58198       ** pick up the appropriate opcode. */
58199       int j;
58200       i -= p->nOp;
58201       for(j=0; i>=apSub[j]->nOp; j++){
58202         i -= apSub[j]->nOp;
58203       }
58204       pOp = &apSub[j]->aOp[i];
58205     }
58206     if( p->explain==1 ){
58207       pMem->flags = MEM_Int;
58208       pMem->type = SQLITE_INTEGER;
58209       pMem->u.i = i;                                /* Program counter */
58210       pMem++;
58211   
58212       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58213       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
58214       assert( pMem->z!=0 );
58215       pMem->n = sqlite3Strlen30(pMem->z);
58216       pMem->type = SQLITE_TEXT;
58217       pMem->enc = SQLITE_UTF8;
58218       pMem++;
58219
58220       /* When an OP_Program opcode is encounter (the only opcode that has
58221       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58222       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58223       ** has not already been seen.
58224       */
58225       if( pOp->p4type==P4_SUBPROGRAM ){
58226         int nByte = (nSub+1)*sizeof(SubProgram*);
58227         int j;
58228         for(j=0; j<nSub; j++){
58229           if( apSub[j]==pOp->p4.pProgram ) break;
58230         }
58231         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58232           apSub = (SubProgram **)pSub->z;
58233           apSub[nSub++] = pOp->p4.pProgram;
58234           pSub->flags |= MEM_Blob;
58235           pSub->n = nSub*sizeof(SubProgram*);
58236         }
58237       }
58238     }
58239
58240     pMem->flags = MEM_Int;
58241     pMem->u.i = pOp->p1;                          /* P1 */
58242     pMem->type = SQLITE_INTEGER;
58243     pMem++;
58244
58245     pMem->flags = MEM_Int;
58246     pMem->u.i = pOp->p2;                          /* P2 */
58247     pMem->type = SQLITE_INTEGER;
58248     pMem++;
58249
58250     pMem->flags = MEM_Int;
58251     pMem->u.i = pOp->p3;                          /* P3 */
58252     pMem->type = SQLITE_INTEGER;
58253     pMem++;
58254
58255     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
58256       assert( p->db->mallocFailed );
58257       return SQLITE_ERROR;
58258     }
58259     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58260     z = displayP4(pOp, pMem->z, 32);
58261     if( z!=pMem->z ){
58262       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58263     }else{
58264       assert( pMem->z!=0 );
58265       pMem->n = sqlite3Strlen30(pMem->z);
58266       pMem->enc = SQLITE_UTF8;
58267     }
58268     pMem->type = SQLITE_TEXT;
58269     pMem++;
58270
58271     if( p->explain==1 ){
58272       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58273         assert( p->db->mallocFailed );
58274         return SQLITE_ERROR;
58275       }
58276       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58277       pMem->n = 2;
58278       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
58279       pMem->type = SQLITE_TEXT;
58280       pMem->enc = SQLITE_UTF8;
58281       pMem++;
58282   
58283 #ifdef SQLITE_DEBUG
58284       if( pOp->zComment ){
58285         pMem->flags = MEM_Str|MEM_Term;
58286         pMem->z = pOp->zComment;
58287         pMem->n = sqlite3Strlen30(pMem->z);
58288         pMem->enc = SQLITE_UTF8;
58289         pMem->type = SQLITE_TEXT;
58290       }else
58291 #endif
58292       {
58293         pMem->flags = MEM_Null;                       /* Comment */
58294         pMem->type = SQLITE_NULL;
58295       }
58296     }
58297
58298     p->nResColumn = 8 - 4*(p->explain-1);
58299     p->rc = SQLITE_OK;
58300     rc = SQLITE_ROW;
58301   }
58302   return rc;
58303 }
58304 #endif /* SQLITE_OMIT_EXPLAIN */
58305
58306 #ifdef SQLITE_DEBUG
58307 /*
58308 ** Print the SQL that was used to generate a VDBE program.
58309 */
58310 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58311   int nOp = p->nOp;
58312   VdbeOp *pOp;
58313   if( nOp<1 ) return;
58314   pOp = &p->aOp[0];
58315   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58316     const char *z = pOp->p4.z;
58317     while( sqlite3Isspace(*z) ) z++;
58318     printf("SQL: [%s]\n", z);
58319   }
58320 }
58321 #endif
58322
58323 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58324 /*
58325 ** Print an IOTRACE message showing SQL content.
58326 */
58327 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58328   int nOp = p->nOp;
58329   VdbeOp *pOp;
58330   if( sqlite3IoTrace==0 ) return;
58331   if( nOp<1 ) return;
58332   pOp = &p->aOp[0];
58333   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58334     int i, j;
58335     char z[1000];
58336     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58337     for(i=0; sqlite3Isspace(z[i]); i++){}
58338     for(j=0; z[i]; i++){
58339       if( sqlite3Isspace(z[i]) ){
58340         if( z[i-1]!=' ' ){
58341           z[j++] = ' ';
58342         }
58343       }else{
58344         z[j++] = z[i];
58345       }
58346     }
58347     z[j] = 0;
58348     sqlite3IoTrace("SQL %s\n", z);
58349   }
58350 }
58351 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58352
58353 /*
58354 ** Allocate space from a fixed size buffer and return a pointer to
58355 ** that space.  If insufficient space is available, return NULL.
58356 **
58357 ** The pBuf parameter is the initial value of a pointer which will
58358 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
58359 ** NULL, it means that memory space has already been allocated and that
58360 ** this routine should not allocate any new memory.  When pBuf is not
58361 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
58362 ** is NULL.
58363 **
58364 ** nByte is the number of bytes of space needed.
58365 **
58366 ** *ppFrom points to available space and pEnd points to the end of the
58367 ** available space.  When space is allocated, *ppFrom is advanced past
58368 ** the end of the allocated space.
58369 **
58370 ** *pnByte is a counter of the number of bytes of space that have failed
58371 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
58372 ** request, then increment *pnByte by the amount of the request.
58373 */
58374 static void *allocSpace(
58375   void *pBuf,          /* Where return pointer will be stored */
58376   int nByte,           /* Number of bytes to allocate */
58377   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
58378   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
58379   int *pnByte          /* If allocation cannot be made, increment *pnByte */
58380 ){
58381   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58382   if( pBuf ) return pBuf;
58383   nByte = ROUND8(nByte);
58384   if( &(*ppFrom)[nByte] <= pEnd ){
58385     pBuf = (void*)*ppFrom;
58386     *ppFrom += nByte;
58387   }else{
58388     *pnByte += nByte;
58389   }
58390   return pBuf;
58391 }
58392
58393 /*
58394 ** Prepare a virtual machine for execution.  This involves things such
58395 ** as allocating stack space and initializing the program counter.
58396 ** After the VDBE has be prepped, it can be executed by one or more
58397 ** calls to sqlite3VdbeExec().  
58398 **
58399 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
58400 ** VDBE_MAGIC_RUN.
58401 **
58402 ** This function may be called more than once on a single virtual machine.
58403 ** The first call is made while compiling the SQL statement. Subsequent
58404 ** calls are made as part of the process of resetting a statement to be
58405 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
58406 ** and isExplain parameters are only passed correct values the first time
58407 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
58408 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
58409 */
58410 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
58411   Vdbe *p,                       /* The VDBE */
58412   int nVar,                      /* Number of '?' see in the SQL statement */
58413   int nMem,                      /* Number of memory cells to allocate */
58414   int nCursor,                   /* Number of cursors to allocate */
58415   int nArg,                      /* Maximum number of args in SubPrograms */
58416   int isExplain,                 /* True if the EXPLAIN keywords is present */
58417   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
58418 ){
58419   int n;
58420   sqlite3 *db = p->db;
58421
58422   assert( p!=0 );
58423   assert( p->magic==VDBE_MAGIC_INIT );
58424
58425   /* There should be at least one opcode.
58426   */
58427   assert( p->nOp>0 );
58428
58429   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58430   p->magic = VDBE_MAGIC_RUN;
58431
58432   /* For each cursor required, also allocate a memory cell. Memory
58433   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
58434   ** the vdbe program. Instead they are used to allocate space for
58435   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
58436   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
58437   ** stores the blob of memory associated with cursor 1, etc.
58438   **
58439   ** See also: allocateCursor().
58440   */
58441   nMem += nCursor;
58442
58443   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
58444   ** an array to marshal SQL function arguments in. This is only done the
58445   ** first time this function is called for a given VDBE, not when it is
58446   ** being called from sqlite3_reset() to reset the virtual machine.
58447   */
58448   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
58449     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
58450     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
58451     int nByte;                              /* How much extra memory needed */
58452
58453     resolveP2Values(p, &nArg);
58454     p->usesStmtJournal = (u8)usesStmtJournal;
58455     if( isExplain && nMem<10 ){
58456       nMem = 10;
58457     }
58458     memset(zCsr, 0, zEnd-zCsr);
58459     zCsr += (zCsr - (u8*)0)&7;
58460     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
58461
58462     /* Memory for registers, parameters, cursor, etc, is allocated in two
58463     ** passes.  On the first pass, we try to reuse unused space at the 
58464     ** end of the opcode array.  If we are unable to satisfy all memory
58465     ** requirements by reusing the opcode array tail, then the second
58466     ** pass will fill in the rest using a fresh allocation.  
58467     **
58468     ** This two-pass approach that reuses as much memory as possible from
58469     ** the leftover space at the end of the opcode array can significantly
58470     ** reduce the amount of memory held by a prepared statement.
58471     */
58472     do {
58473       nByte = 0;
58474       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
58475       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
58476       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
58477       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
58478       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
58479                             &zCsr, zEnd, &nByte);
58480       if( nByte ){
58481         p->pFree = sqlite3DbMallocZero(db, nByte);
58482       }
58483       zCsr = p->pFree;
58484       zEnd = &zCsr[nByte];
58485     }while( nByte && !db->mallocFailed );
58486
58487     p->nCursor = (u16)nCursor;
58488     if( p->aVar ){
58489       p->nVar = (ynVar)nVar;
58490       for(n=0; n<nVar; n++){
58491         p->aVar[n].flags = MEM_Null;
58492         p->aVar[n].db = db;
58493       }
58494     }
58495     if( p->aMem ){
58496       p->aMem--;                      /* aMem[] goes from 1..nMem */
58497       p->nMem = nMem;                 /*       not from 0..nMem-1 */
58498       for(n=1; n<=nMem; n++){
58499         p->aMem[n].flags = MEM_Null;
58500         p->aMem[n].db = db;
58501       }
58502     }
58503   }
58504 #ifdef SQLITE_DEBUG
58505   for(n=1; n<p->nMem; n++){
58506     assert( p->aMem[n].db==db );
58507   }
58508 #endif
58509
58510   p->pc = -1;
58511   p->rc = SQLITE_OK;
58512   p->errorAction = OE_Abort;
58513   p->explain |= isExplain;
58514   p->magic = VDBE_MAGIC_RUN;
58515   p->nChange = 0;
58516   p->cacheCtr = 1;
58517   p->minWriteFileFormat = 255;
58518   p->iStatement = 0;
58519   p->nFkConstraint = 0;
58520 #ifdef VDBE_PROFILE
58521   {
58522     int i;
58523     for(i=0; i<p->nOp; i++){
58524       p->aOp[i].cnt = 0;
58525       p->aOp[i].cycles = 0;
58526     }
58527   }
58528 #endif
58529 }
58530
58531 /*
58532 ** Close a VDBE cursor and release all the resources that cursor 
58533 ** happens to hold.
58534 */
58535 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
58536   if( pCx==0 ){
58537     return;
58538   }
58539   if( pCx->pBt ){
58540     sqlite3BtreeClose(pCx->pBt);
58541     /* The pCx->pCursor will be close automatically, if it exists, by
58542     ** the call above. */
58543   }else if( pCx->pCursor ){
58544     sqlite3BtreeCloseCursor(pCx->pCursor);
58545   }
58546 #ifndef SQLITE_OMIT_VIRTUALTABLE
58547   if( pCx->pVtabCursor ){
58548     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
58549     const sqlite3_module *pModule = pCx->pModule;
58550     p->inVtabMethod = 1;
58551     pModule->xClose(pVtabCursor);
58552     p->inVtabMethod = 0;
58553   }
58554 #endif
58555 }
58556
58557 /*
58558 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
58559 ** is used, for example, when a trigger sub-program is halted to restore
58560 ** control to the main program.
58561 */
58562 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
58563   Vdbe *v = pFrame->v;
58564   v->aOp = pFrame->aOp;
58565   v->nOp = pFrame->nOp;
58566   v->aMem = pFrame->aMem;
58567   v->nMem = pFrame->nMem;
58568   v->apCsr = pFrame->apCsr;
58569   v->nCursor = pFrame->nCursor;
58570   v->db->lastRowid = pFrame->lastRowid;
58571   v->nChange = pFrame->nChange;
58572   return pFrame->pc;
58573 }
58574
58575 /*
58576 ** Close all cursors.
58577 **
58578 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
58579 ** cell array. This is necessary as the memory cell array may contain
58580 ** pointers to VdbeFrame objects, which may in turn contain pointers to
58581 ** open cursors.
58582 */
58583 static void closeAllCursors(Vdbe *p){
58584   if( p->pFrame ){
58585     VdbeFrame *pFrame;
58586     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
58587     sqlite3VdbeFrameRestore(pFrame);
58588   }
58589   p->pFrame = 0;
58590   p->nFrame = 0;
58591
58592   if( p->apCsr ){
58593     int i;
58594     for(i=0; i<p->nCursor; i++){
58595       VdbeCursor *pC = p->apCsr[i];
58596       if( pC ){
58597         sqlite3VdbeFreeCursor(p, pC);
58598         p->apCsr[i] = 0;
58599       }
58600     }
58601   }
58602   if( p->aMem ){
58603     releaseMemArray(&p->aMem[1], p->nMem);
58604   }
58605   while( p->pDelFrame ){
58606     VdbeFrame *pDel = p->pDelFrame;
58607     p->pDelFrame = pDel->pParent;
58608     sqlite3VdbeFrameDelete(pDel);
58609   }
58610 }
58611
58612 /*
58613 ** Clean up the VM after execution.
58614 **
58615 ** This routine will automatically close any cursors, lists, and/or
58616 ** sorters that were left open.  It also deletes the values of
58617 ** variables in the aVar[] array.
58618 */
58619 static void Cleanup(Vdbe *p){
58620   sqlite3 *db = p->db;
58621
58622 #ifdef SQLITE_DEBUG
58623   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
58624   ** Vdbe.aMem[] arrays have already been cleaned up.  */
58625   int i;
58626   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
58627   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
58628 #endif
58629
58630   sqlite3DbFree(db, p->zErrMsg);
58631   p->zErrMsg = 0;
58632   p->pResultSet = 0;
58633 }
58634
58635 /*
58636 ** Set the number of result columns that will be returned by this SQL
58637 ** statement. This is now set at compile time, rather than during
58638 ** execution of the vdbe program so that sqlite3_column_count() can
58639 ** be called on an SQL statement before sqlite3_step().
58640 */
58641 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
58642   Mem *pColName;
58643   int n;
58644   sqlite3 *db = p->db;
58645
58646   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
58647   sqlite3DbFree(db, p->aColName);
58648   n = nResColumn*COLNAME_N;
58649   p->nResColumn = (u16)nResColumn;
58650   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
58651   if( p->aColName==0 ) return;
58652   while( n-- > 0 ){
58653     pColName->flags = MEM_Null;
58654     pColName->db = p->db;
58655     pColName++;
58656   }
58657 }
58658
58659 /*
58660 ** Set the name of the idx'th column to be returned by the SQL statement.
58661 ** zName must be a pointer to a nul terminated string.
58662 **
58663 ** This call must be made after a call to sqlite3VdbeSetNumCols().
58664 **
58665 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
58666 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
58667 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
58668 */
58669 SQLITE_PRIVATE int sqlite3VdbeSetColName(
58670   Vdbe *p,                         /* Vdbe being configured */
58671   int idx,                         /* Index of column zName applies to */
58672   int var,                         /* One of the COLNAME_* constants */
58673   const char *zName,               /* Pointer to buffer containing name */
58674   void (*xDel)(void*)              /* Memory management strategy for zName */
58675 ){
58676   int rc;
58677   Mem *pColName;
58678   assert( idx<p->nResColumn );
58679   assert( var<COLNAME_N );
58680   if( p->db->mallocFailed ){
58681     assert( !zName || xDel!=SQLITE_DYNAMIC );
58682     return SQLITE_NOMEM;
58683   }
58684   assert( p->aColName!=0 );
58685   pColName = &(p->aColName[idx+var*p->nResColumn]);
58686   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
58687   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
58688   return rc;
58689 }
58690
58691 /*
58692 ** A read or write transaction may or may not be active on database handle
58693 ** db. If a transaction is active, commit it. If there is a
58694 ** write-transaction spanning more than one database file, this routine
58695 ** takes care of the master journal trickery.
58696 */
58697 static int vdbeCommit(sqlite3 *db, Vdbe *p){
58698   int i;
58699   int nTrans = 0;  /* Number of databases with an active write-transaction */
58700   int rc = SQLITE_OK;
58701   int needXcommit = 0;
58702
58703 #ifdef SQLITE_OMIT_VIRTUALTABLE
58704   /* With this option, sqlite3VtabSync() is defined to be simply 
58705   ** SQLITE_OK so p is not used. 
58706   */
58707   UNUSED_PARAMETER(p);
58708 #endif
58709
58710   /* Before doing anything else, call the xSync() callback for any
58711   ** virtual module tables written in this transaction. This has to
58712   ** be done before determining whether a master journal file is 
58713   ** required, as an xSync() callback may add an attached database
58714   ** to the transaction.
58715   */
58716   rc = sqlite3VtabSync(db, &p->zErrMsg);
58717
58718   /* This loop determines (a) if the commit hook should be invoked and
58719   ** (b) how many database files have open write transactions, not 
58720   ** including the temp database. (b) is important because if more than 
58721   ** one database file has an open write transaction, a master journal
58722   ** file is required for an atomic commit.
58723   */ 
58724   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
58725     Btree *pBt = db->aDb[i].pBt;
58726     if( sqlite3BtreeIsInTrans(pBt) ){
58727       needXcommit = 1;
58728       if( i!=1 ) nTrans++;
58729       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
58730     }
58731   }
58732   if( rc!=SQLITE_OK ){
58733     return rc;
58734   }
58735
58736   /* If there are any write-transactions at all, invoke the commit hook */
58737   if( needXcommit && db->xCommitCallback ){
58738     rc = db->xCommitCallback(db->pCommitArg);
58739     if( rc ){
58740       return SQLITE_CONSTRAINT;
58741     }
58742   }
58743
58744   /* The simple case - no more than one database file (not counting the
58745   ** TEMP database) has a transaction active.   There is no need for the
58746   ** master-journal.
58747   **
58748   ** If the return value of sqlite3BtreeGetFilename() is a zero length
58749   ** string, it means the main database is :memory: or a temp file.  In 
58750   ** that case we do not support atomic multi-file commits, so use the 
58751   ** simple case then too.
58752   */
58753   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
58754    || nTrans<=1
58755   ){
58756     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58757       Btree *pBt = db->aDb[i].pBt;
58758       if( pBt ){
58759         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
58760       }
58761     }
58762
58763     /* Do the commit only if all databases successfully complete phase 1. 
58764     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
58765     ** IO error while deleting or truncating a journal file. It is unlikely,
58766     ** but could happen. In this case abandon processing and return the error.
58767     */
58768     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58769       Btree *pBt = db->aDb[i].pBt;
58770       if( pBt ){
58771         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
58772       }
58773     }
58774     if( rc==SQLITE_OK ){
58775       sqlite3VtabCommit(db);
58776     }
58777   }
58778
58779   /* The complex case - There is a multi-file write-transaction active.
58780   ** This requires a master journal file to ensure the transaction is
58781   ** committed atomicly.
58782   */
58783 #ifndef SQLITE_OMIT_DISKIO
58784   else{
58785     sqlite3_vfs *pVfs = db->pVfs;
58786     int needSync = 0;
58787     char *zMaster = 0;   /* File-name for the master journal */
58788     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
58789     sqlite3_file *pMaster = 0;
58790     i64 offset = 0;
58791     int res;
58792
58793     /* Select a master journal file name */
58794     do {
58795       u32 iRandom;
58796       sqlite3DbFree(db, zMaster);
58797       sqlite3_randomness(sizeof(iRandom), &iRandom);
58798       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
58799       if( !zMaster ){
58800         return SQLITE_NOMEM;
58801       }
58802       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
58803     }while( rc==SQLITE_OK && res );
58804     if( rc==SQLITE_OK ){
58805       /* Open the master journal. */
58806       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
58807           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
58808           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
58809       );
58810     }
58811     if( rc!=SQLITE_OK ){
58812       sqlite3DbFree(db, zMaster);
58813       return rc;
58814     }
58815  
58816     /* Write the name of each database file in the transaction into the new
58817     ** master journal file. If an error occurs at this point close
58818     ** and delete the master journal file. All the individual journal files
58819     ** still have 'null' as the master journal pointer, so they will roll
58820     ** back independently if a failure occurs.
58821     */
58822     for(i=0; i<db->nDb; i++){
58823       Btree *pBt = db->aDb[i].pBt;
58824       if( sqlite3BtreeIsInTrans(pBt) ){
58825         char const *zFile = sqlite3BtreeGetJournalname(pBt);
58826         if( zFile==0 ){
58827           continue;  /* Ignore TEMP and :memory: databases */
58828         }
58829         assert( zFile[0]!=0 );
58830         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
58831           needSync = 1;
58832         }
58833         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
58834         offset += sqlite3Strlen30(zFile)+1;
58835         if( rc!=SQLITE_OK ){
58836           sqlite3OsCloseFree(pMaster);
58837           sqlite3OsDelete(pVfs, zMaster, 0);
58838           sqlite3DbFree(db, zMaster);
58839           return rc;
58840         }
58841       }
58842     }
58843
58844     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
58845     ** flag is set this is not required.
58846     */
58847     if( needSync 
58848      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
58849      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
58850     ){
58851       sqlite3OsCloseFree(pMaster);
58852       sqlite3OsDelete(pVfs, zMaster, 0);
58853       sqlite3DbFree(db, zMaster);
58854       return rc;
58855     }
58856
58857     /* Sync all the db files involved in the transaction. The same call
58858     ** sets the master journal pointer in each individual journal. If
58859     ** an error occurs here, do not delete the master journal file.
58860     **
58861     ** If the error occurs during the first call to
58862     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
58863     ** master journal file will be orphaned. But we cannot delete it,
58864     ** in case the master journal file name was written into the journal
58865     ** file before the failure occurred.
58866     */
58867     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
58868       Btree *pBt = db->aDb[i].pBt;
58869       if( pBt ){
58870         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
58871       }
58872     }
58873     sqlite3OsCloseFree(pMaster);
58874     assert( rc!=SQLITE_BUSY );
58875     if( rc!=SQLITE_OK ){
58876       sqlite3DbFree(db, zMaster);
58877       return rc;
58878     }
58879
58880     /* Delete the master journal file. This commits the transaction. After
58881     ** doing this the directory is synced again before any individual
58882     ** transaction files are deleted.
58883     */
58884     rc = sqlite3OsDelete(pVfs, zMaster, 1);
58885     sqlite3DbFree(db, zMaster);
58886     zMaster = 0;
58887     if( rc ){
58888       return rc;
58889     }
58890
58891     /* All files and directories have already been synced, so the following
58892     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
58893     ** deleting or truncating journals. If something goes wrong while
58894     ** this is happening we don't really care. The integrity of the
58895     ** transaction is already guaranteed, but some stray 'cold' journals
58896     ** may be lying around. Returning an error code won't help matters.
58897     */
58898     disable_simulated_io_errors();
58899     sqlite3BeginBenignMalloc();
58900     for(i=0; i<db->nDb; i++){ 
58901       Btree *pBt = db->aDb[i].pBt;
58902       if( pBt ){
58903         sqlite3BtreeCommitPhaseTwo(pBt, 1);
58904       }
58905     }
58906     sqlite3EndBenignMalloc();
58907     enable_simulated_io_errors();
58908
58909     sqlite3VtabCommit(db);
58910   }
58911 #endif
58912
58913   return rc;
58914 }
58915
58916 /* 
58917 ** This routine checks that the sqlite3.activeVdbeCnt count variable
58918 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
58919 ** currently active. An assertion fails if the two counts do not match.
58920 ** This is an internal self-check only - it is not an essential processing
58921 ** step.
58922 **
58923 ** This is a no-op if NDEBUG is defined.
58924 */
58925 #ifndef NDEBUG
58926 static void checkActiveVdbeCnt(sqlite3 *db){
58927   Vdbe *p;
58928   int cnt = 0;
58929   int nWrite = 0;
58930   p = db->pVdbe;
58931   while( p ){
58932     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
58933       cnt++;
58934       if( p->readOnly==0 ) nWrite++;
58935     }
58936     p = p->pNext;
58937   }
58938   assert( cnt==db->activeVdbeCnt );
58939   assert( nWrite==db->writeVdbeCnt );
58940 }
58941 #else
58942 #define checkActiveVdbeCnt(x)
58943 #endif
58944
58945 /*
58946 ** For every Btree that in database connection db which 
58947 ** has been modified, "trip" or invalidate each cursor in
58948 ** that Btree might have been modified so that the cursor
58949 ** can never be used again.  This happens when a rollback
58950 *** occurs.  We have to trip all the other cursors, even
58951 ** cursor from other VMs in different database connections,
58952 ** so that none of them try to use the data at which they
58953 ** were pointing and which now may have been changed due
58954 ** to the rollback.
58955 **
58956 ** Remember that a rollback can delete tables complete and
58957 ** reorder rootpages.  So it is not sufficient just to save
58958 ** the state of the cursor.  We have to invalidate the cursor
58959 ** so that it is never used again.
58960 */
58961 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
58962   int i;
58963   for(i=0; i<db->nDb; i++){
58964     Btree *p = db->aDb[i].pBt;
58965     if( p && sqlite3BtreeIsInTrans(p) ){
58966       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
58967     }
58968   }
58969 }
58970
58971 /*
58972 ** If the Vdbe passed as the first argument opened a statement-transaction,
58973 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
58974 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
58975 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
58976 ** statement transaction is commtted.
58977 **
58978 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
58979 ** Otherwise SQLITE_OK.
58980 */
58981 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
58982   sqlite3 *const db = p->db;
58983   int rc = SQLITE_OK;
58984
58985   /* If p->iStatement is greater than zero, then this Vdbe opened a 
58986   ** statement transaction that should be closed here. The only exception
58987   ** is that an IO error may have occured, causing an emergency rollback.
58988   ** In this case (db->nStatement==0), and there is nothing to do.
58989   */
58990   if( db->nStatement && p->iStatement ){
58991     int i;
58992     const int iSavepoint = p->iStatement-1;
58993
58994     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
58995     assert( db->nStatement>0 );
58996     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
58997
58998     for(i=0; i<db->nDb; i++){ 
58999       int rc2 = SQLITE_OK;
59000       Btree *pBt = db->aDb[i].pBt;
59001       if( pBt ){
59002         if( eOp==SAVEPOINT_ROLLBACK ){
59003           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
59004         }
59005         if( rc2==SQLITE_OK ){
59006           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
59007         }
59008         if( rc==SQLITE_OK ){
59009           rc = rc2;
59010         }
59011       }
59012     }
59013     db->nStatement--;
59014     p->iStatement = 0;
59015
59016     /* If the statement transaction is being rolled back, also restore the 
59017     ** database handles deferred constraint counter to the value it had when 
59018     ** the statement transaction was opened.  */
59019     if( eOp==SAVEPOINT_ROLLBACK ){
59020       db->nDeferredCons = p->nStmtDefCons;
59021     }
59022   }
59023   return rc;
59024 }
59025
59026 /*
59027 ** This function is called when a transaction opened by the database 
59028 ** handle associated with the VM passed as an argument is about to be 
59029 ** committed. If there are outstanding deferred foreign key constraint
59030 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59031 **
59032 ** If there are outstanding FK violations and this function returns 
59033 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59034 ** an error message to it. Then return SQLITE_ERROR.
59035 */
59036 #ifndef SQLITE_OMIT_FOREIGN_KEY
59037 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59038   sqlite3 *db = p->db;
59039   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59040     p->rc = SQLITE_CONSTRAINT;
59041     p->errorAction = OE_Abort;
59042     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59043     return SQLITE_ERROR;
59044   }
59045   return SQLITE_OK;
59046 }
59047 #endif
59048
59049 /*
59050 ** This routine is called the when a VDBE tries to halt.  If the VDBE
59051 ** has made changes and is in autocommit mode, then commit those
59052 ** changes.  If a rollback is needed, then do the rollback.
59053 **
59054 ** This routine is the only way to move the state of a VM from
59055 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
59056 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59057 **
59058 ** Return an error code.  If the commit could not complete because of
59059 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
59060 ** means the close did not happen and needs to be repeated.
59061 */
59062 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59063   int rc;                         /* Used to store transient return codes */
59064   sqlite3 *db = p->db;
59065
59066   /* This function contains the logic that determines if a statement or
59067   ** transaction will be committed or rolled back as a result of the
59068   ** execution of this virtual machine. 
59069   **
59070   ** If any of the following errors occur:
59071   **
59072   **     SQLITE_NOMEM
59073   **     SQLITE_IOERR
59074   **     SQLITE_FULL
59075   **     SQLITE_INTERRUPT
59076   **
59077   ** Then the internal cache might have been left in an inconsistent
59078   ** state.  We need to rollback the statement transaction, if there is
59079   ** one, or the complete transaction if there is no statement transaction.
59080   */
59081
59082   if( p->db->mallocFailed ){
59083     p->rc = SQLITE_NOMEM;
59084   }
59085   closeAllCursors(p);
59086   if( p->magic!=VDBE_MAGIC_RUN ){
59087     return SQLITE_OK;
59088   }
59089   checkActiveVdbeCnt(db);
59090
59091   /* No commit or rollback needed if the program never started */
59092   if( p->pc>=0 ){
59093     int mrc;   /* Primary error code from p->rc */
59094     int eStatementOp = 0;
59095     int isSpecialError;            /* Set to true if a 'special' error */
59096
59097     /* Lock all btrees used by the statement */
59098     sqlite3VdbeEnter(p);
59099
59100     /* Check for one of the special errors */
59101     mrc = p->rc & 0xff;
59102     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
59103     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59104                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59105     if( isSpecialError ){
59106       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
59107       ** no rollback is necessary. Otherwise, at least a savepoint 
59108       ** transaction must be rolled back to restore the database to a 
59109       ** consistent state.
59110       **
59111       ** Even if the statement is read-only, it is important to perform
59112       ** a statement or transaction rollback operation. If the error 
59113       ** occured while writing to the journal, sub-journal or database
59114       ** file as part of an effort to free up cache space (see function
59115       ** pagerStress() in pager.c), the rollback is required to restore 
59116       ** the pager to a consistent state.
59117       */
59118       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59119         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59120           eStatementOp = SAVEPOINT_ROLLBACK;
59121         }else{
59122           /* We are forced to roll back the active transaction. Before doing
59123           ** so, abort any other statements this handle currently has active.
59124           */
59125           invalidateCursorsOnModifiedBtrees(db);
59126           sqlite3RollbackAll(db);
59127           sqlite3CloseSavepoints(db);
59128           db->autoCommit = 1;
59129         }
59130       }
59131     }
59132
59133     /* Check for immediate foreign key violations. */
59134     if( p->rc==SQLITE_OK ){
59135       sqlite3VdbeCheckFk(p, 0);
59136     }
59137   
59138     /* If the auto-commit flag is set and this is the only active writer 
59139     ** VM, then we do either a commit or rollback of the current transaction. 
59140     **
59141     ** Note: This block also runs if one of the special errors handled 
59142     ** above has occurred. 
59143     */
59144     if( !sqlite3VtabInSync(db) 
59145      && db->autoCommit 
59146      && db->writeVdbeCnt==(p->readOnly==0) 
59147     ){
59148       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59149         rc = sqlite3VdbeCheckFk(p, 1);
59150         if( rc!=SQLITE_OK ){
59151           if( NEVER(p->readOnly) ){
59152             sqlite3VdbeLeave(p);
59153             return SQLITE_ERROR;
59154           }
59155           rc = SQLITE_CONSTRAINT;
59156         }else{ 
59157           /* The auto-commit flag is true, the vdbe program was successful 
59158           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59159           ** key constraints to hold up the transaction. This means a commit 
59160           ** is required. */
59161           rc = vdbeCommit(db, p);
59162         }
59163         if( rc==SQLITE_BUSY && p->readOnly ){
59164           sqlite3VdbeLeave(p);
59165           return SQLITE_BUSY;
59166         }else if( rc!=SQLITE_OK ){
59167           p->rc = rc;
59168           sqlite3RollbackAll(db);
59169         }else{
59170           db->nDeferredCons = 0;
59171           sqlite3CommitInternalChanges(db);
59172         }
59173       }else{
59174         sqlite3RollbackAll(db);
59175       }
59176       db->nStatement = 0;
59177     }else if( eStatementOp==0 ){
59178       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59179         eStatementOp = SAVEPOINT_RELEASE;
59180       }else if( p->errorAction==OE_Abort ){
59181         eStatementOp = SAVEPOINT_ROLLBACK;
59182       }else{
59183         invalidateCursorsOnModifiedBtrees(db);
59184         sqlite3RollbackAll(db);
59185         sqlite3CloseSavepoints(db);
59186         db->autoCommit = 1;
59187       }
59188     }
59189   
59190     /* If eStatementOp is non-zero, then a statement transaction needs to
59191     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59192     ** do so. If this operation returns an error, and the current statement
59193     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59194     ** current statement error code.
59195     **
59196     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
59197     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
59198     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
59199     ** the following code.
59200     */
59201     if( eStatementOp ){
59202       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59203       if( rc ){
59204         assert( eStatementOp==SAVEPOINT_ROLLBACK );
59205         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
59206           p->rc = rc;
59207           sqlite3DbFree(db, p->zErrMsg);
59208           p->zErrMsg = 0;
59209         }
59210         invalidateCursorsOnModifiedBtrees(db);
59211         sqlite3RollbackAll(db);
59212         sqlite3CloseSavepoints(db);
59213         db->autoCommit = 1;
59214       }
59215     }
59216   
59217     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59218     ** has been rolled back, update the database connection change-counter. 
59219     */
59220     if( p->changeCntOn ){
59221       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59222         sqlite3VdbeSetChanges(db, p->nChange);
59223       }else{
59224         sqlite3VdbeSetChanges(db, 0);
59225       }
59226       p->nChange = 0;
59227     }
59228   
59229     /* Rollback or commit any schema changes that occurred. */
59230     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59231       sqlite3ResetInternalSchema(db, -1);
59232       db->flags = (db->flags | SQLITE_InternChanges);
59233     }
59234
59235     /* Release the locks */
59236     sqlite3VdbeLeave(p);
59237   }
59238
59239   /* We have successfully halted and closed the VM.  Record this fact. */
59240   if( p->pc>=0 ){
59241     db->activeVdbeCnt--;
59242     if( !p->readOnly ){
59243       db->writeVdbeCnt--;
59244     }
59245     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59246   }
59247   p->magic = VDBE_MAGIC_HALT;
59248   checkActiveVdbeCnt(db);
59249   if( p->db->mallocFailed ){
59250     p->rc = SQLITE_NOMEM;
59251   }
59252
59253   /* If the auto-commit flag is set to true, then any locks that were held
59254   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
59255   ** to invoke any required unlock-notify callbacks.
59256   */
59257   if( db->autoCommit ){
59258     sqlite3ConnectionUnlocked(db);
59259   }
59260
59261   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59262   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59263 }
59264
59265
59266 /*
59267 ** Each VDBE holds the result of the most recent sqlite3_step() call
59268 ** in p->rc.  This routine sets that result back to SQLITE_OK.
59269 */
59270 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59271   p->rc = SQLITE_OK;
59272 }
59273
59274 /*
59275 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
59276 ** Write any error messages into *pzErrMsg.  Return the result code.
59277 **
59278 ** After this routine is run, the VDBE should be ready to be executed
59279 ** again.
59280 **
59281 ** To look at it another way, this routine resets the state of the
59282 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59283 ** VDBE_MAGIC_INIT.
59284 */
59285 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59286   sqlite3 *db;
59287   db = p->db;
59288
59289   /* If the VM did not run to completion or if it encountered an
59290   ** error, then it might not have been halted properly.  So halt
59291   ** it now.
59292   */
59293   sqlite3VdbeHalt(p);
59294
59295   /* If the VDBE has be run even partially, then transfer the error code
59296   ** and error message from the VDBE into the main database structure.  But
59297   ** if the VDBE has just been set to run but has not actually executed any
59298   ** instructions yet, leave the main database error information unchanged.
59299   */
59300   if( p->pc>=0 ){
59301     if( p->zErrMsg ){
59302       sqlite3BeginBenignMalloc();
59303       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59304       sqlite3EndBenignMalloc();
59305       db->errCode = p->rc;
59306       sqlite3DbFree(db, p->zErrMsg);
59307       p->zErrMsg = 0;
59308     }else if( p->rc ){
59309       sqlite3Error(db, p->rc, 0);
59310     }else{
59311       sqlite3Error(db, SQLITE_OK, 0);
59312     }
59313     if( p->runOnlyOnce ) p->expired = 1;
59314   }else if( p->rc && p->expired ){
59315     /* The expired flag was set on the VDBE before the first call
59316     ** to sqlite3_step(). For consistency (since sqlite3_step() was
59317     ** called), set the database error in this case as well.
59318     */
59319     sqlite3Error(db, p->rc, 0);
59320     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59321     sqlite3DbFree(db, p->zErrMsg);
59322     p->zErrMsg = 0;
59323   }
59324
59325   /* Reclaim all memory used by the VDBE
59326   */
59327   Cleanup(p);
59328
59329   /* Save profiling information from this VDBE run.
59330   */
59331 #ifdef VDBE_PROFILE
59332   {
59333     FILE *out = fopen("vdbe_profile.out", "a");
59334     if( out ){
59335       int i;
59336       fprintf(out, "---- ");
59337       for(i=0; i<p->nOp; i++){
59338         fprintf(out, "%02x", p->aOp[i].opcode);
59339       }
59340       fprintf(out, "\n");
59341       for(i=0; i<p->nOp; i++){
59342         fprintf(out, "%6d %10lld %8lld ",
59343            p->aOp[i].cnt,
59344            p->aOp[i].cycles,
59345            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59346         );
59347         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59348       }
59349       fclose(out);
59350     }
59351   }
59352 #endif
59353   p->magic = VDBE_MAGIC_INIT;
59354   return p->rc & db->errMask;
59355 }
59356  
59357 /*
59358 ** Clean up and delete a VDBE after execution.  Return an integer which is
59359 ** the result code.  Write any error message text into *pzErrMsg.
59360 */
59361 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59362   int rc = SQLITE_OK;
59363   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59364     rc = sqlite3VdbeReset(p);
59365     assert( (rc & p->db->errMask)==rc );
59366   }
59367   sqlite3VdbeDelete(p);
59368   return rc;
59369 }
59370
59371 /*
59372 ** Call the destructor for each auxdata entry in pVdbeFunc for which
59373 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
59374 ** are always destroyed.  To destroy all auxdata entries, call this
59375 ** routine with mask==0.
59376 */
59377 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59378   int i;
59379   for(i=0; i<pVdbeFunc->nAux; i++){
59380     struct AuxData *pAux = &pVdbeFunc->apAux[i];
59381     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59382       if( pAux->xDelete ){
59383         pAux->xDelete(pAux->pAux);
59384       }
59385       pAux->pAux = 0;
59386     }
59387   }
59388 }
59389
59390 /*
59391 ** Free all memory associated with the Vdbe passed as the second argument.
59392 ** The difference between this function and sqlite3VdbeDelete() is that
59393 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59394 ** the database connection.
59395 */
59396 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59397   SubProgram *pSub, *pNext;
59398   assert( p->db==0 || p->db==db );
59399   releaseMemArray(p->aVar, p->nVar);
59400   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59401   for(pSub=p->pProgram; pSub; pSub=pNext){
59402     pNext = pSub->pNext;
59403     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59404     sqlite3DbFree(db, pSub);
59405   }
59406   vdbeFreeOpArray(db, p->aOp, p->nOp);
59407   sqlite3DbFree(db, p->aLabel);
59408   sqlite3DbFree(db, p->aColName);
59409   sqlite3DbFree(db, p->zSql);
59410   sqlite3DbFree(db, p->pFree);
59411   sqlite3DbFree(db, p);
59412 }
59413
59414 /*
59415 ** Delete an entire VDBE.
59416 */
59417 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59418   sqlite3 *db;
59419
59420   if( NEVER(p==0) ) return;
59421   db = p->db;
59422   if( p->pPrev ){
59423     p->pPrev->pNext = p->pNext;
59424   }else{
59425     assert( db->pVdbe==p );
59426     db->pVdbe = p->pNext;
59427   }
59428   if( p->pNext ){
59429     p->pNext->pPrev = p->pPrev;
59430   }
59431   p->magic = VDBE_MAGIC_DEAD;
59432   p->db = 0;
59433   sqlite3VdbeDeleteObject(db, p);
59434 }
59435
59436 /*
59437 ** Make sure the cursor p is ready to read or write the row to which it
59438 ** was last positioned.  Return an error code if an OOM fault or I/O error
59439 ** prevents us from positioning the cursor to its correct position.
59440 **
59441 ** If a MoveTo operation is pending on the given cursor, then do that
59442 ** MoveTo now.  If no move is pending, check to see if the row has been
59443 ** deleted out from under the cursor and if it has, mark the row as
59444 ** a NULL row.
59445 **
59446 ** If the cursor is already pointing to the correct row and that row has
59447 ** not been deleted out from under the cursor, then this routine is a no-op.
59448 */
59449 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
59450   if( p->deferredMoveto ){
59451     int res, rc;
59452 #ifdef SQLITE_TEST
59453     extern int sqlite3_search_count;
59454 #endif
59455     assert( p->isTable );
59456     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
59457     if( rc ) return rc;
59458     p->lastRowid = p->movetoTarget;
59459     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
59460     p->rowidIsValid = 1;
59461 #ifdef SQLITE_TEST
59462     sqlite3_search_count++;
59463 #endif
59464     p->deferredMoveto = 0;
59465     p->cacheStatus = CACHE_STALE;
59466   }else if( ALWAYS(p->pCursor) ){
59467     int hasMoved;
59468     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
59469     if( rc ) return rc;
59470     if( hasMoved ){
59471       p->cacheStatus = CACHE_STALE;
59472       p->nullRow = 1;
59473     }
59474   }
59475   return SQLITE_OK;
59476 }
59477
59478 /*
59479 ** The following functions:
59480 **
59481 ** sqlite3VdbeSerialType()
59482 ** sqlite3VdbeSerialTypeLen()
59483 ** sqlite3VdbeSerialLen()
59484 ** sqlite3VdbeSerialPut()
59485 ** sqlite3VdbeSerialGet()
59486 **
59487 ** encapsulate the code that serializes values for storage in SQLite
59488 ** data and index records. Each serialized value consists of a
59489 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
59490 ** integer, stored as a varint.
59491 **
59492 ** In an SQLite index record, the serial type is stored directly before
59493 ** the blob of data that it corresponds to. In a table record, all serial
59494 ** types are stored at the start of the record, and the blobs of data at
59495 ** the end. Hence these functions allow the caller to handle the
59496 ** serial-type and data blob seperately.
59497 **
59498 ** The following table describes the various storage classes for data:
59499 **
59500 **   serial type        bytes of data      type
59501 **   --------------     ---------------    ---------------
59502 **      0                     0            NULL
59503 **      1                     1            signed integer
59504 **      2                     2            signed integer
59505 **      3                     3            signed integer
59506 **      4                     4            signed integer
59507 **      5                     6            signed integer
59508 **      6                     8            signed integer
59509 **      7                     8            IEEE float
59510 **      8                     0            Integer constant 0
59511 **      9                     0            Integer constant 1
59512 **     10,11                               reserved for expansion
59513 **    N>=12 and even       (N-12)/2        BLOB
59514 **    N>=13 and odd        (N-13)/2        text
59515 **
59516 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
59517 ** of SQLite will not understand those serial types.
59518 */
59519
59520 /*
59521 ** Return the serial-type for the value stored in pMem.
59522 */
59523 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
59524   int flags = pMem->flags;
59525   int n;
59526
59527   if( flags&MEM_Null ){
59528     return 0;
59529   }
59530   if( flags&MEM_Int ){
59531     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
59532 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
59533     i64 i = pMem->u.i;
59534     u64 u;
59535     if( file_format>=4 && (i&1)==i ){
59536       return 8+(u32)i;
59537     }
59538     if( i<0 ){
59539       if( i<(-MAX_6BYTE) ) return 6;
59540       /* Previous test prevents:  u = -(-9223372036854775808) */
59541       u = -i;
59542     }else{
59543       u = i;
59544     }
59545     if( u<=127 ) return 1;
59546     if( u<=32767 ) return 2;
59547     if( u<=8388607 ) return 3;
59548     if( u<=2147483647 ) return 4;
59549     if( u<=MAX_6BYTE ) return 5;
59550     return 6;
59551   }
59552   if( flags&MEM_Real ){
59553     return 7;
59554   }
59555   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
59556   n = pMem->n;
59557   if( flags & MEM_Zero ){
59558     n += pMem->u.nZero;
59559   }
59560   assert( n>=0 );
59561   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
59562 }
59563
59564 /*
59565 ** Return the length of the data corresponding to the supplied serial-type.
59566 */
59567 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
59568   if( serial_type>=12 ){
59569     return (serial_type-12)/2;
59570   }else{
59571     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
59572     return aSize[serial_type];
59573   }
59574 }
59575
59576 /*
59577 ** If we are on an architecture with mixed-endian floating 
59578 ** points (ex: ARM7) then swap the lower 4 bytes with the 
59579 ** upper 4 bytes.  Return the result.
59580 **
59581 ** For most architectures, this is a no-op.
59582 **
59583 ** (later):  It is reported to me that the mixed-endian problem
59584 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
59585 ** that early versions of GCC stored the two words of a 64-bit
59586 ** float in the wrong order.  And that error has been propagated
59587 ** ever since.  The blame is not necessarily with GCC, though.
59588 ** GCC might have just copying the problem from a prior compiler.
59589 ** I am also told that newer versions of GCC that follow a different
59590 ** ABI get the byte order right.
59591 **
59592 ** Developers using SQLite on an ARM7 should compile and run their
59593 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
59594 ** enabled, some asserts below will ensure that the byte order of
59595 ** floating point values is correct.
59596 **
59597 ** (2007-08-30)  Frank van Vugt has studied this problem closely
59598 ** and has send his findings to the SQLite developers.  Frank
59599 ** writes that some Linux kernels offer floating point hardware
59600 ** emulation that uses only 32-bit mantissas instead of a full 
59601 ** 48-bits as required by the IEEE standard.  (This is the
59602 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
59603 ** byte swapping becomes very complicated.  To avoid problems,
59604 ** the necessary byte swapping is carried out using a 64-bit integer
59605 ** rather than a 64-bit float.  Frank assures us that the code here
59606 ** works for him.  We, the developers, have no way to independently
59607 ** verify this, but Frank seems to know what he is talking about
59608 ** so we trust him.
59609 */
59610 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
59611 static u64 floatSwap(u64 in){
59612   union {
59613     u64 r;
59614     u32 i[2];
59615   } u;
59616   u32 t;
59617
59618   u.r = in;
59619   t = u.i[0];
59620   u.i[0] = u.i[1];
59621   u.i[1] = t;
59622   return u.r;
59623 }
59624 # define swapMixedEndianFloat(X)  X = floatSwap(X)
59625 #else
59626 # define swapMixedEndianFloat(X)
59627 #endif
59628
59629 /*
59630 ** Write the serialized data blob for the value stored in pMem into 
59631 ** buf. It is assumed that the caller has allocated sufficient space.
59632 ** Return the number of bytes written.
59633 **
59634 ** nBuf is the amount of space left in buf[].  nBuf must always be
59635 ** large enough to hold the entire field.  Except, if the field is
59636 ** a blob with a zero-filled tail, then buf[] might be just the right
59637 ** size to hold everything except for the zero-filled tail.  If buf[]
59638 ** is only big enough to hold the non-zero prefix, then only write that
59639 ** prefix into buf[].  But if buf[] is large enough to hold both the
59640 ** prefix and the tail then write the prefix and set the tail to all
59641 ** zeros.
59642 **
59643 ** Return the number of bytes actually written into buf[].  The number
59644 ** of bytes in the zero-filled tail is included in the return value only
59645 ** if those bytes were zeroed in buf[].
59646 */ 
59647 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
59648   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
59649   u32 len;
59650
59651   /* Integer and Real */
59652   if( serial_type<=7 && serial_type>0 ){
59653     u64 v;
59654     u32 i;
59655     if( serial_type==7 ){
59656       assert( sizeof(v)==sizeof(pMem->r) );
59657       memcpy(&v, &pMem->r, sizeof(v));
59658       swapMixedEndianFloat(v);
59659     }else{
59660       v = pMem->u.i;
59661     }
59662     len = i = sqlite3VdbeSerialTypeLen(serial_type);
59663     assert( len<=(u32)nBuf );
59664     while( i-- ){
59665       buf[i] = (u8)(v&0xFF);
59666       v >>= 8;
59667     }
59668     return len;
59669   }
59670
59671   /* String or blob */
59672   if( serial_type>=12 ){
59673     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
59674              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
59675     assert( pMem->n<=nBuf );
59676     len = pMem->n;
59677     memcpy(buf, pMem->z, len);
59678     if( pMem->flags & MEM_Zero ){
59679       len += pMem->u.nZero;
59680       assert( nBuf>=0 );
59681       if( len > (u32)nBuf ){
59682         len = (u32)nBuf;
59683       }
59684       memset(&buf[pMem->n], 0, len-pMem->n);
59685     }
59686     return len;
59687   }
59688
59689   /* NULL or constants 0 or 1 */
59690   return 0;
59691 }
59692
59693 /*
59694 ** Deserialize the data blob pointed to by buf as serial type serial_type
59695 ** and store the result in pMem.  Return the number of bytes read.
59696 */ 
59697 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
59698   const unsigned char *buf,     /* Buffer to deserialize from */
59699   u32 serial_type,              /* Serial type to deserialize */
59700   Mem *pMem                     /* Memory cell to write value into */
59701 ){
59702   switch( serial_type ){
59703     case 10:   /* Reserved for future use */
59704     case 11:   /* Reserved for future use */
59705     case 0: {  /* NULL */
59706       pMem->flags = MEM_Null;
59707       break;
59708     }
59709     case 1: { /* 1-byte signed integer */
59710       pMem->u.i = (signed char)buf[0];
59711       pMem->flags = MEM_Int;
59712       return 1;
59713     }
59714     case 2: { /* 2-byte signed integer */
59715       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
59716       pMem->flags = MEM_Int;
59717       return 2;
59718     }
59719     case 3: { /* 3-byte signed integer */
59720       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
59721       pMem->flags = MEM_Int;
59722       return 3;
59723     }
59724     case 4: { /* 4-byte signed integer */
59725       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59726       pMem->flags = MEM_Int;
59727       return 4;
59728     }
59729     case 5: { /* 6-byte signed integer */
59730       u64 x = (((signed char)buf[0])<<8) | buf[1];
59731       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
59732       x = (x<<32) | y;
59733       pMem->u.i = *(i64*)&x;
59734       pMem->flags = MEM_Int;
59735       return 6;
59736     }
59737     case 6:   /* 8-byte signed integer */
59738     case 7: { /* IEEE floating point */
59739       u64 x;
59740       u32 y;
59741 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
59742       /* Verify that integers and floating point values use the same
59743       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
59744       ** defined that 64-bit floating point values really are mixed
59745       ** endian.
59746       */
59747       static const u64 t1 = ((u64)0x3ff00000)<<32;
59748       static const double r1 = 1.0;
59749       u64 t2 = t1;
59750       swapMixedEndianFloat(t2);
59751       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
59752 #endif
59753
59754       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
59755       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
59756       x = (x<<32) | y;
59757       if( serial_type==6 ){
59758         pMem->u.i = *(i64*)&x;
59759         pMem->flags = MEM_Int;
59760       }else{
59761         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
59762         swapMixedEndianFloat(x);
59763         memcpy(&pMem->r, &x, sizeof(x));
59764         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
59765       }
59766       return 8;
59767     }
59768     case 8:    /* Integer 0 */
59769     case 9: {  /* Integer 1 */
59770       pMem->u.i = serial_type-8;
59771       pMem->flags = MEM_Int;
59772       return 0;
59773     }
59774     default: {
59775       u32 len = (serial_type-12)/2;
59776       pMem->z = (char *)buf;
59777       pMem->n = len;
59778       pMem->xDel = 0;
59779       if( serial_type&0x01 ){
59780         pMem->flags = MEM_Str | MEM_Ephem;
59781       }else{
59782         pMem->flags = MEM_Blob | MEM_Ephem;
59783       }
59784       return len;
59785     }
59786   }
59787   return 0;
59788 }
59789
59790
59791 /*
59792 ** Given the nKey-byte encoding of a record in pKey[], parse the
59793 ** record into a UnpackedRecord structure.  Return a pointer to
59794 ** that structure.
59795 **
59796 ** The calling function might provide szSpace bytes of memory
59797 ** space at pSpace.  This space can be used to hold the returned
59798 ** VDbeParsedRecord structure if it is large enough.  If it is
59799 ** not big enough, space is obtained from sqlite3_malloc().
59800 **
59801 ** The returned structure should be closed by a call to
59802 ** sqlite3VdbeDeleteUnpackedRecord().
59803 */ 
59804 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
59805   KeyInfo *pKeyInfo,     /* Information about the record format */
59806   int nKey,              /* Size of the binary record */
59807   const void *pKey,      /* The binary record */
59808   char *pSpace,          /* Unaligned space available to hold the object */
59809   int szSpace            /* Size of pSpace[] in bytes */
59810 ){
59811   const unsigned char *aKey = (const unsigned char *)pKey;
59812   UnpackedRecord *p;  /* The unpacked record that we will return */
59813   int nByte;          /* Memory space needed to hold p, in bytes */
59814   int d;
59815   u32 idx;
59816   u16 u;              /* Unsigned loop counter */
59817   u32 szHdr;
59818   Mem *pMem;
59819   int nOff;           /* Increase pSpace by this much to 8-byte align it */
59820   
59821   /*
59822   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
59823   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
59824   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
59825   */
59826   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
59827   pSpace += nOff;
59828   szSpace -= nOff;
59829   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
59830   if( nByte>szSpace ){
59831     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
59832     if( p==0 ) return 0;
59833     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
59834   }else{
59835     p = (UnpackedRecord*)pSpace;
59836     p->flags = UNPACKED_NEED_DESTROY;
59837   }
59838   p->pKeyInfo = pKeyInfo;
59839   p->nField = pKeyInfo->nField + 1;
59840   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
59841   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59842   idx = getVarint32(aKey, szHdr);
59843   d = szHdr;
59844   u = 0;
59845   while( idx<szHdr && u<p->nField && d<=nKey ){
59846     u32 serial_type;
59847
59848     idx += getVarint32(&aKey[idx], serial_type);
59849     pMem->enc = pKeyInfo->enc;
59850     pMem->db = pKeyInfo->db;
59851     pMem->flags = 0;
59852     pMem->zMalloc = 0;
59853     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
59854     pMem++;
59855     u++;
59856   }
59857   assert( u<=pKeyInfo->nField + 1 );
59858   p->nField = u;
59859   return (void*)p;
59860 }
59861
59862 /*
59863 ** This routine destroys a UnpackedRecord object.
59864 */
59865 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
59866   int i;
59867   Mem *pMem;
59868
59869   assert( p!=0 );
59870   assert( p->flags & UNPACKED_NEED_DESTROY );
59871   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
59872     /* The unpacked record is always constructed by the
59873     ** sqlite3VdbeUnpackRecord() function above, which makes all
59874     ** strings and blobs static.  And none of the elements are
59875     ** ever transformed, so there is never anything to delete.
59876     */
59877     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
59878   }
59879   if( p->flags & UNPACKED_NEED_FREE ){
59880     sqlite3DbFree(p->pKeyInfo->db, p);
59881   }
59882 }
59883
59884 /*
59885 ** This function compares the two table rows or index records
59886 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
59887 ** or positive integer if key1 is less than, equal to or 
59888 ** greater than key2.  The {nKey1, pKey1} key must be a blob
59889 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
59890 ** key must be a parsed key such as obtained from
59891 ** sqlite3VdbeParseRecord.
59892 **
59893 ** Key1 and Key2 do not have to contain the same number of fields.
59894 ** The key with fewer fields is usually compares less than the 
59895 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
59896 ** and the common prefixes are equal, then key1 is less than key2.
59897 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
59898 ** equal, then the keys are considered to be equal and
59899 ** the parts beyond the common prefix are ignored.
59900 **
59901 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
59902 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
59903 ** an index key, and thus ends with a rowid value.  The last byte
59904 ** of the header will therefore be the serial type of the rowid:
59905 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
59906 ** The serial type of the final rowid will always be a single byte.
59907 ** By ignoring this last byte of the header, we force the comparison
59908 ** to ignore the rowid at the end of key1.
59909 */
59910 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
59911   int nKey1, const void *pKey1, /* Left key */
59912   UnpackedRecord *pPKey2        /* Right key */
59913 ){
59914   int d1;            /* Offset into aKey[] of next data element */
59915   u32 idx1;          /* Offset into aKey[] of next header element */
59916   u32 szHdr1;        /* Number of bytes in header */
59917   int i = 0;
59918   int nField;
59919   int rc = 0;
59920   const unsigned char *aKey1 = (const unsigned char *)pKey1;
59921   KeyInfo *pKeyInfo;
59922   Mem mem1;
59923
59924   pKeyInfo = pPKey2->pKeyInfo;
59925   mem1.enc = pKeyInfo->enc;
59926   mem1.db = pKeyInfo->db;
59927   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
59928   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
59929
59930   /* Compilers may complain that mem1.u.i is potentially uninitialized.
59931   ** We could initialize it, as shown here, to silence those complaints.
59932   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
59933   ** the unnecessary initialization has a measurable negative performance
59934   ** impact, since this routine is a very high runner.  And so, we choose
59935   ** to ignore the compiler warnings and leave this variable uninitialized.
59936   */
59937   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
59938   
59939   idx1 = getVarint32(aKey1, szHdr1);
59940   d1 = szHdr1;
59941   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
59942     szHdr1--;
59943   }
59944   nField = pKeyInfo->nField;
59945   while( idx1<szHdr1 && i<pPKey2->nField ){
59946     u32 serial_type1;
59947
59948     /* Read the serial types for the next element in each key. */
59949     idx1 += getVarint32( aKey1+idx1, serial_type1 );
59950     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
59951
59952     /* Extract the values to be compared.
59953     */
59954     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
59955
59956     /* Do the comparison
59957     */
59958     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
59959                            i<nField ? pKeyInfo->aColl[i] : 0);
59960     if( rc!=0 ){
59961       assert( mem1.zMalloc==0 );  /* See comment below */
59962
59963       /* Invert the result if we are using DESC sort order. */
59964       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
59965         rc = -rc;
59966       }
59967     
59968       /* If the PREFIX_SEARCH flag is set and all fields except the final
59969       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
59970       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
59971       ** This is used by the OP_IsUnique opcode.
59972       */
59973       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
59974         assert( idx1==szHdr1 && rc );
59975         assert( mem1.flags & MEM_Int );
59976         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
59977         pPKey2->rowid = mem1.u.i;
59978       }
59979     
59980       return rc;
59981     }
59982     i++;
59983   }
59984
59985   /* No memory allocation is ever used on mem1.  Prove this using
59986   ** the following assert().  If the assert() fails, it indicates a
59987   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
59988   */
59989   assert( mem1.zMalloc==0 );
59990
59991   /* rc==0 here means that one of the keys ran out of fields and
59992   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
59993   ** flag is set, then break the tie by treating key2 as larger.
59994   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
59995   ** are considered to be equal.  Otherwise, the longer key is the 
59996   ** larger.  As it happens, the pPKey2 will always be the longer
59997   ** if there is a difference.
59998   */
59999   assert( rc==0 );
60000   if( pPKey2->flags & UNPACKED_INCRKEY ){
60001     rc = -1;
60002   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
60003     /* Leave rc==0 */
60004   }else if( idx1<szHdr1 ){
60005     rc = 1;
60006   }
60007   return rc;
60008 }
60009  
60010
60011 /*
60012 ** pCur points at an index entry created using the OP_MakeRecord opcode.
60013 ** Read the rowid (the last field in the record) and store it in *rowid.
60014 ** Return SQLITE_OK if everything works, or an error code otherwise.
60015 **
60016 ** pCur might be pointing to text obtained from a corrupt database file.
60017 ** So the content cannot be trusted.  Do appropriate checks on the content.
60018 */
60019 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60020   i64 nCellKey = 0;
60021   int rc;
60022   u32 szHdr;        /* Size of the header */
60023   u32 typeRowid;    /* Serial type of the rowid */
60024   u32 lenRowid;     /* Size of the rowid */
60025   Mem m, v;
60026
60027   UNUSED_PARAMETER(db);
60028
60029   /* Get the size of the index entry.  Only indices entries of less
60030   ** than 2GiB are support - anything large must be database corruption.
60031   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60032   ** this code can safely assume that nCellKey is 32-bits  
60033   */
60034   assert( sqlite3BtreeCursorIsValid(pCur) );
60035   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60036   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
60037   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60038
60039   /* Read in the complete content of the index entry */
60040   memset(&m, 0, sizeof(m));
60041   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60042   if( rc ){
60043     return rc;
60044   }
60045
60046   /* The index entry must begin with a header size */
60047   (void)getVarint32((u8*)m.z, szHdr);
60048   testcase( szHdr==3 );
60049   testcase( szHdr==m.n );
60050   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60051     goto idx_rowid_corruption;
60052   }
60053
60054   /* The last field of the index should be an integer - the ROWID.
60055   ** Verify that the last entry really is an integer. */
60056   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60057   testcase( typeRowid==1 );
60058   testcase( typeRowid==2 );
60059   testcase( typeRowid==3 );
60060   testcase( typeRowid==4 );
60061   testcase( typeRowid==5 );
60062   testcase( typeRowid==6 );
60063   testcase( typeRowid==8 );
60064   testcase( typeRowid==9 );
60065   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60066     goto idx_rowid_corruption;
60067   }
60068   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60069   testcase( (u32)m.n==szHdr+lenRowid );
60070   if( unlikely((u32)m.n<szHdr+lenRowid) ){
60071     goto idx_rowid_corruption;
60072   }
60073
60074   /* Fetch the integer off the end of the index record */
60075   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60076   *rowid = v.u.i;
60077   sqlite3VdbeMemRelease(&m);
60078   return SQLITE_OK;
60079
60080   /* Jump here if database corruption is detected after m has been
60081   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
60082 idx_rowid_corruption:
60083   testcase( m.zMalloc!=0 );
60084   sqlite3VdbeMemRelease(&m);
60085   return SQLITE_CORRUPT_BKPT;
60086 }
60087
60088 /*
60089 ** Compare the key of the index entry that cursor pC is pointing to against
60090 ** the key string in pUnpacked.  Write into *pRes a number
60091 ** that is negative, zero, or positive if pC is less than, equal to,
60092 ** or greater than pUnpacked.  Return SQLITE_OK on success.
60093 **
60094 ** pUnpacked is either created without a rowid or is truncated so that it
60095 ** omits the rowid at the end.  The rowid at the end of the index entry
60096 ** is ignored as well.  Hence, this routine only compares the prefixes 
60097 ** of the keys prior to the final rowid, not the entire key.
60098 */
60099 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60100   VdbeCursor *pC,             /* The cursor to compare against */
60101   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
60102   int *res                    /* Write the comparison result here */
60103 ){
60104   i64 nCellKey = 0;
60105   int rc;
60106   BtCursor *pCur = pC->pCursor;
60107   Mem m;
60108
60109   assert( sqlite3BtreeCursorIsValid(pCur) );
60110   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60111   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
60112   /* nCellKey will always be between 0 and 0xffffffff because of the say
60113   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60114   if( nCellKey<=0 || nCellKey>0x7fffffff ){
60115     *res = 0;
60116     return SQLITE_CORRUPT_BKPT;
60117   }
60118   memset(&m, 0, sizeof(m));
60119   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60120   if( rc ){
60121     return rc;
60122   }
60123   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60124   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60125   sqlite3VdbeMemRelease(&m);
60126   return SQLITE_OK;
60127 }
60128
60129 /*
60130 ** This routine sets the value to be returned by subsequent calls to
60131 ** sqlite3_changes() on the database handle 'db'. 
60132 */
60133 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60134   assert( sqlite3_mutex_held(db->mutex) );
60135   db->nChange = nChange;
60136   db->nTotalChange += nChange;
60137 }
60138
60139 /*
60140 ** Set a flag in the vdbe to update the change counter when it is finalised
60141 ** or reset.
60142 */
60143 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60144   v->changeCntOn = 1;
60145 }
60146
60147 /*
60148 ** Mark every prepared statement associated with a database connection
60149 ** as expired.
60150 **
60151 ** An expired statement means that recompilation of the statement is
60152 ** recommend.  Statements expire when things happen that make their
60153 ** programs obsolete.  Removing user-defined functions or collating
60154 ** sequences, or changing an authorization function are the types of
60155 ** things that make prepared statements obsolete.
60156 */
60157 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60158   Vdbe *p;
60159   for(p = db->pVdbe; p; p=p->pNext){
60160     p->expired = 1;
60161   }
60162 }
60163
60164 /*
60165 ** Return the database associated with the Vdbe.
60166 */
60167 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60168   return v->db;
60169 }
60170
60171 /*
60172 ** Return a pointer to an sqlite3_value structure containing the value bound
60173 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
60174 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60175 ** constants) to the value before returning it.
60176 **
60177 ** The returned value must be freed by the caller using sqlite3ValueFree().
60178 */
60179 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60180   assert( iVar>0 );
60181   if( v ){
60182     Mem *pMem = &v->aVar[iVar-1];
60183     if( 0==(pMem->flags & MEM_Null) ){
60184       sqlite3_value *pRet = sqlite3ValueNew(v->db);
60185       if( pRet ){
60186         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60187         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60188         sqlite3VdbeMemStoreType((Mem *)pRet);
60189       }
60190       return pRet;
60191     }
60192   }
60193   return 0;
60194 }
60195
60196 /*
60197 ** Configure SQL variable iVar so that binding a new value to it signals
60198 ** to sqlite3_reoptimize() that re-preparing the statement may result
60199 ** in a better query plan.
60200 */
60201 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60202   assert( iVar>0 );
60203   if( iVar>32 ){
60204     v->expmask = 0xffffffff;
60205   }else{
60206     v->expmask |= ((u32)1 << (iVar-1));
60207   }
60208 }
60209
60210 /************** End of vdbeaux.c *********************************************/
60211 /************** Begin file vdbeapi.c *****************************************/
60212 /*
60213 ** 2004 May 26
60214 **
60215 ** The author disclaims copyright to this source code.  In place of
60216 ** a legal notice, here is a blessing:
60217 **
60218 **    May you do good and not evil.
60219 **    May you find forgiveness for yourself and forgive others.
60220 **    May you share freely, never taking more than you give.
60221 **
60222 *************************************************************************
60223 **
60224 ** This file contains code use to implement APIs that are part of the
60225 ** VDBE.
60226 */
60227
60228 #ifndef SQLITE_OMIT_DEPRECATED
60229 /*
60230 ** Return TRUE (non-zero) of the statement supplied as an argument needs
60231 ** to be recompiled.  A statement needs to be recompiled whenever the
60232 ** execution environment changes in a way that would alter the program
60233 ** that sqlite3_prepare() generates.  For example, if new functions or
60234 ** collating sequences are registered or if an authorizer function is
60235 ** added or changed.
60236 */
60237 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60238   Vdbe *p = (Vdbe*)pStmt;
60239   return p==0 || p->expired;
60240 }
60241 #endif
60242
60243 /*
60244 ** Check on a Vdbe to make sure it has not been finalized.  Log
60245 ** an error and return true if it has been finalized (or is otherwise
60246 ** invalid).  Return false if it is ok.
60247 */
60248 static int vdbeSafety(Vdbe *p){
60249   if( p->db==0 ){
60250     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60251     return 1;
60252   }else{
60253     return 0;
60254   }
60255 }
60256 static int vdbeSafetyNotNull(Vdbe *p){
60257   if( p==0 ){
60258     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60259     return 1;
60260   }else{
60261     return vdbeSafety(p);
60262   }
60263 }
60264
60265 /*
60266 ** The following routine destroys a virtual machine that is created by
60267 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
60268 ** success/failure code that describes the result of executing the virtual
60269 ** machine.
60270 **
60271 ** This routine sets the error code and string returned by
60272 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60273 */
60274 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60275   int rc;
60276   if( pStmt==0 ){
60277     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60278     ** pointer is a harmless no-op. */
60279     rc = SQLITE_OK;
60280   }else{
60281     Vdbe *v = (Vdbe*)pStmt;
60282     sqlite3 *db = v->db;
60283 #if SQLITE_THREADSAFE
60284     sqlite3_mutex *mutex;
60285 #endif
60286     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60287 #if SQLITE_THREADSAFE
60288     mutex = v->db->mutex;
60289 #endif
60290     sqlite3_mutex_enter(mutex);
60291     rc = sqlite3VdbeFinalize(v);
60292     rc = sqlite3ApiExit(db, rc);
60293     sqlite3_mutex_leave(mutex);
60294   }
60295   return rc;
60296 }
60297
60298 /*
60299 ** Terminate the current execution of an SQL statement and reset it
60300 ** back to its starting state so that it can be reused. A success code from
60301 ** the prior execution is returned.
60302 **
60303 ** This routine sets the error code and string returned by
60304 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60305 */
60306 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60307   int rc;
60308   if( pStmt==0 ){
60309     rc = SQLITE_OK;
60310   }else{
60311     Vdbe *v = (Vdbe*)pStmt;
60312     sqlite3_mutex_enter(v->db->mutex);
60313     rc = sqlite3VdbeReset(v);
60314     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
60315     assert( (rc & (v->db->errMask))==rc );
60316     rc = sqlite3ApiExit(v->db, rc);
60317     sqlite3_mutex_leave(v->db->mutex);
60318   }
60319   return rc;
60320 }
60321
60322 /*
60323 ** Set all the parameters in the compiled SQL statement to NULL.
60324 */
60325 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60326   int i;
60327   int rc = SQLITE_OK;
60328   Vdbe *p = (Vdbe*)pStmt;
60329 #if SQLITE_THREADSAFE
60330   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60331 #endif
60332   sqlite3_mutex_enter(mutex);
60333   for(i=0; i<p->nVar; i++){
60334     sqlite3VdbeMemRelease(&p->aVar[i]);
60335     p->aVar[i].flags = MEM_Null;
60336   }
60337   if( p->isPrepareV2 && p->expmask ){
60338     p->expired = 1;
60339   }
60340   sqlite3_mutex_leave(mutex);
60341   return rc;
60342 }
60343
60344
60345 /**************************** sqlite3_value_  *******************************
60346 ** The following routines extract information from a Mem or sqlite3_value
60347 ** structure.
60348 */
60349 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60350   Mem *p = (Mem*)pVal;
60351   if( p->flags & (MEM_Blob|MEM_Str) ){
60352     sqlite3VdbeMemExpandBlob(p);
60353     p->flags &= ~MEM_Str;
60354     p->flags |= MEM_Blob;
60355     return p->n ? p->z : 0;
60356   }else{
60357     return sqlite3_value_text(pVal);
60358   }
60359 }
60360 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60361   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60362 }
60363 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60364   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60365 }
60366 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60367   return sqlite3VdbeRealValue((Mem*)pVal);
60368 }
60369 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60370   return (int)sqlite3VdbeIntValue((Mem*)pVal);
60371 }
60372 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60373   return sqlite3VdbeIntValue((Mem*)pVal);
60374 }
60375 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60376   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60377 }
60378 #ifndef SQLITE_OMIT_UTF16
60379 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60380   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60381 }
60382 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60383   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60384 }
60385 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60386   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60387 }
60388 #endif /* SQLITE_OMIT_UTF16 */
60389 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60390   return pVal->type;
60391 }
60392
60393 /**************************** sqlite3_result_  *******************************
60394 ** The following routines are used by user-defined functions to specify
60395 ** the function result.
60396 **
60397 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60398 ** result as a string or blob but if the string or blob is too large, it
60399 ** then sets the error code to SQLITE_TOOBIG
60400 */
60401 static void setResultStrOrError(
60402   sqlite3_context *pCtx,  /* Function context */
60403   const char *z,          /* String pointer */
60404   int n,                  /* Bytes in string, or negative */
60405   u8 enc,                 /* Encoding of z.  0 for BLOBs */
60406   void (*xDel)(void*)     /* Destructor function */
60407 ){
60408   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60409     sqlite3_result_error_toobig(pCtx);
60410   }
60411 }
60412 SQLITE_API void sqlite3_result_blob(
60413   sqlite3_context *pCtx, 
60414   const void *z, 
60415   int n, 
60416   void (*xDel)(void *)
60417 ){
60418   assert( n>=0 );
60419   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60420   setResultStrOrError(pCtx, z, n, 0, xDel);
60421 }
60422 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
60423   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60424   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
60425 }
60426 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
60427   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60428   pCtx->isError = SQLITE_ERROR;
60429   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
60430 }
60431 #ifndef SQLITE_OMIT_UTF16
60432 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
60433   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60434   pCtx->isError = SQLITE_ERROR;
60435   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
60436 }
60437 #endif
60438 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
60439   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60440   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
60441 }
60442 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
60443   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60444   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
60445 }
60446 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
60447   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60448   sqlite3VdbeMemSetNull(&pCtx->s);
60449 }
60450 SQLITE_API void sqlite3_result_text(
60451   sqlite3_context *pCtx, 
60452   const char *z, 
60453   int n,
60454   void (*xDel)(void *)
60455 ){
60456   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60457   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
60458 }
60459 #ifndef SQLITE_OMIT_UTF16
60460 SQLITE_API void sqlite3_result_text16(
60461   sqlite3_context *pCtx, 
60462   const void *z, 
60463   int n, 
60464   void (*xDel)(void *)
60465 ){
60466   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60467   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
60468 }
60469 SQLITE_API void sqlite3_result_text16be(
60470   sqlite3_context *pCtx, 
60471   const void *z, 
60472   int n, 
60473   void (*xDel)(void *)
60474 ){
60475   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60476   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
60477 }
60478 SQLITE_API void sqlite3_result_text16le(
60479   sqlite3_context *pCtx, 
60480   const void *z, 
60481   int n, 
60482   void (*xDel)(void *)
60483 ){
60484   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60485   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
60486 }
60487 #endif /* SQLITE_OMIT_UTF16 */
60488 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
60489   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60490   sqlite3VdbeMemCopy(&pCtx->s, pValue);
60491 }
60492 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
60493   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60494   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
60495 }
60496 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
60497   pCtx->isError = errCode;
60498   if( pCtx->s.flags & MEM_Null ){
60499     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
60500                          SQLITE_UTF8, SQLITE_STATIC);
60501   }
60502 }
60503
60504 /* Force an SQLITE_TOOBIG error. */
60505 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
60506   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60507   pCtx->isError = SQLITE_TOOBIG;
60508   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
60509                        SQLITE_UTF8, SQLITE_STATIC);
60510 }
60511
60512 /* An SQLITE_NOMEM error. */
60513 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
60514   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60515   sqlite3VdbeMemSetNull(&pCtx->s);
60516   pCtx->isError = SQLITE_NOMEM;
60517   pCtx->s.db->mallocFailed = 1;
60518 }
60519
60520 /*
60521 ** This function is called after a transaction has been committed. It 
60522 ** invokes callbacks registered with sqlite3_wal_hook() as required.
60523 */
60524 static int doWalCallbacks(sqlite3 *db){
60525   int rc = SQLITE_OK;
60526 #ifndef SQLITE_OMIT_WAL
60527   int i;
60528   for(i=0; i<db->nDb; i++){
60529     Btree *pBt = db->aDb[i].pBt;
60530     if( pBt ){
60531       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
60532       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
60533         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
60534       }
60535     }
60536   }
60537 #endif
60538   return rc;
60539 }
60540
60541 /*
60542 ** Execute the statement pStmt, either until a row of data is ready, the
60543 ** statement is completely executed or an error occurs.
60544 **
60545 ** This routine implements the bulk of the logic behind the sqlite_step()
60546 ** API.  The only thing omitted is the automatic recompile if a 
60547 ** schema change has occurred.  That detail is handled by the
60548 ** outer sqlite3_step() wrapper procedure.
60549 */
60550 static int sqlite3Step(Vdbe *p){
60551   sqlite3 *db;
60552   int rc;
60553
60554   assert(p);
60555   if( p->magic!=VDBE_MAGIC_RUN ){
60556     /* We used to require that sqlite3_reset() be called before retrying
60557     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
60558     ** with version 3.7.0, we changed this so that sqlite3_reset() would
60559     ** be called automatically instead of throwing the SQLITE_MISUSE error.
60560     ** This "automatic-reset" change is not technically an incompatibility, 
60561     ** since any application that receives an SQLITE_MISUSE is broken by
60562     ** definition.
60563     **
60564     ** Nevertheless, some published applications that were originally written
60565     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
60566     ** returns, and the so were broken by the automatic-reset change.  As a
60567     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
60568     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
60569     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
60570     ** or SQLITE_BUSY error.
60571     */
60572 #ifdef SQLITE_OMIT_AUTORESET
60573     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
60574       sqlite3_reset((sqlite3_stmt*)p);
60575     }else{
60576       return SQLITE_MISUSE_BKPT;
60577     }
60578 #else
60579     sqlite3_reset((sqlite3_stmt*)p);
60580 #endif
60581   }
60582
60583   /* Check that malloc() has not failed. If it has, return early. */
60584   db = p->db;
60585   if( db->mallocFailed ){
60586     p->rc = SQLITE_NOMEM;
60587     return SQLITE_NOMEM;
60588   }
60589
60590   if( p->pc<=0 && p->expired ){
60591     p->rc = SQLITE_SCHEMA;
60592     rc = SQLITE_ERROR;
60593     goto end_of_step;
60594   }
60595   if( p->pc<0 ){
60596     /* If there are no other statements currently running, then
60597     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
60598     ** from interrupting a statement that has not yet started.
60599     */
60600     if( db->activeVdbeCnt==0 ){
60601       db->u1.isInterrupted = 0;
60602     }
60603
60604     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
60605
60606 #ifndef SQLITE_OMIT_TRACE
60607     if( db->xProfile && !db->init.busy ){
60608       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
60609     }
60610 #endif
60611
60612     db->activeVdbeCnt++;
60613     if( p->readOnly==0 ) db->writeVdbeCnt++;
60614     p->pc = 0;
60615   }
60616 #ifndef SQLITE_OMIT_EXPLAIN
60617   if( p->explain ){
60618     rc = sqlite3VdbeList(p);
60619   }else
60620 #endif /* SQLITE_OMIT_EXPLAIN */
60621   {
60622     db->vdbeExecCnt++;
60623     rc = sqlite3VdbeExec(p);
60624     db->vdbeExecCnt--;
60625   }
60626
60627 #ifndef SQLITE_OMIT_TRACE
60628   /* Invoke the profile callback if there is one
60629   */
60630   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
60631     sqlite3_int64 iNow;
60632     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
60633     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
60634   }
60635 #endif
60636
60637   if( rc==SQLITE_DONE ){
60638     assert( p->rc==SQLITE_OK );
60639     p->rc = doWalCallbacks(db);
60640     if( p->rc!=SQLITE_OK ){
60641       rc = SQLITE_ERROR;
60642     }
60643   }
60644
60645   db->errCode = rc;
60646   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
60647     p->rc = SQLITE_NOMEM;
60648   }
60649 end_of_step:
60650   /* At this point local variable rc holds the value that should be 
60651   ** returned if this statement was compiled using the legacy 
60652   ** sqlite3_prepare() interface. According to the docs, this can only
60653   ** be one of the values in the first assert() below. Variable p->rc 
60654   ** contains the value that would be returned if sqlite3_finalize() 
60655   ** were called on statement p.
60656   */
60657   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
60658        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
60659   );
60660   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
60661   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
60662     /* If this statement was prepared using sqlite3_prepare_v2(), and an
60663     ** error has occured, then return the error code in p->rc to the
60664     ** caller. Set the error code in the database handle to the same value.
60665     */ 
60666     rc = db->errCode = p->rc;
60667   }
60668   return (rc&db->errMask);
60669 }
60670
60671 /*
60672 ** This is the top-level implementation of sqlite3_step().  Call
60673 ** sqlite3Step() to do most of the work.  If a schema error occurs,
60674 ** call sqlite3Reprepare() and try again.
60675 */
60676 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
60677   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
60678   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
60679   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
60680   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
60681   sqlite3 *db;             /* The database connection */
60682
60683   if( vdbeSafetyNotNull(v) ){
60684     return SQLITE_MISUSE_BKPT;
60685   }
60686   db = v->db;
60687   sqlite3_mutex_enter(db->mutex);
60688   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
60689          && cnt++ < 5
60690          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
60691     sqlite3_reset(pStmt);
60692     v->expired = 0;
60693   }
60694   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
60695     /* This case occurs after failing to recompile an sql statement. 
60696     ** The error message from the SQL compiler has already been loaded 
60697     ** into the database handle. This block copies the error message 
60698     ** from the database handle into the statement and sets the statement
60699     ** program counter to 0 to ensure that when the statement is 
60700     ** finalized or reset the parser error message is available via
60701     ** sqlite3_errmsg() and sqlite3_errcode().
60702     */
60703     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
60704     sqlite3DbFree(db, v->zErrMsg);
60705     if( !db->mallocFailed ){
60706       v->zErrMsg = sqlite3DbStrDup(db, zErr);
60707       v->rc = rc2;
60708     } else {
60709       v->zErrMsg = 0;
60710       v->rc = rc = SQLITE_NOMEM;
60711     }
60712   }
60713   rc = sqlite3ApiExit(db, rc);
60714   sqlite3_mutex_leave(db->mutex);
60715   return rc;
60716 }
60717
60718 /*
60719 ** Extract the user data from a sqlite3_context structure and return a
60720 ** pointer to it.
60721 */
60722 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
60723   assert( p && p->pFunc );
60724   return p->pFunc->pUserData;
60725 }
60726
60727 /*
60728 ** Extract the user data from a sqlite3_context structure and return a
60729 ** pointer to it.
60730 **
60731 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
60732 ** returns a copy of the pointer to the database connection (the 1st
60733 ** parameter) of the sqlite3_create_function() and
60734 ** sqlite3_create_function16() routines that originally registered the
60735 ** application defined function.
60736 */
60737 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
60738   assert( p && p->pFunc );
60739   return p->s.db;
60740 }
60741
60742 /*
60743 ** The following is the implementation of an SQL function that always
60744 ** fails with an error message stating that the function is used in the
60745 ** wrong context.  The sqlite3_overload_function() API might construct
60746 ** SQL function that use this routine so that the functions will exist
60747 ** for name resolution but are actually overloaded by the xFindFunction
60748 ** method of virtual tables.
60749 */
60750 SQLITE_PRIVATE void sqlite3InvalidFunction(
60751   sqlite3_context *context,  /* The function calling context */
60752   int NotUsed,               /* Number of arguments to the function */
60753   sqlite3_value **NotUsed2   /* Value of each argument */
60754 ){
60755   const char *zName = context->pFunc->zName;
60756   char *zErr;
60757   UNUSED_PARAMETER2(NotUsed, NotUsed2);
60758   zErr = sqlite3_mprintf(
60759       "unable to use function %s in the requested context", zName);
60760   sqlite3_result_error(context, zErr, -1);
60761   sqlite3_free(zErr);
60762 }
60763
60764 /*
60765 ** Allocate or return the aggregate context for a user function.  A new
60766 ** context is allocated on the first call.  Subsequent calls return the
60767 ** same context that was returned on prior calls.
60768 */
60769 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
60770   Mem *pMem;
60771   assert( p && p->pFunc && p->pFunc->xStep );
60772   assert( sqlite3_mutex_held(p->s.db->mutex) );
60773   pMem = p->pMem;
60774   testcase( nByte<0 );
60775   if( (pMem->flags & MEM_Agg)==0 ){
60776     if( nByte<=0 ){
60777       sqlite3VdbeMemReleaseExternal(pMem);
60778       pMem->flags = MEM_Null;
60779       pMem->z = 0;
60780     }else{
60781       sqlite3VdbeMemGrow(pMem, nByte, 0);
60782       pMem->flags = MEM_Agg;
60783       pMem->u.pDef = p->pFunc;
60784       if( pMem->z ){
60785         memset(pMem->z, 0, nByte);
60786       }
60787     }
60788   }
60789   return (void*)pMem->z;
60790 }
60791
60792 /*
60793 ** Return the auxilary data pointer, if any, for the iArg'th argument to
60794 ** the user-function defined by pCtx.
60795 */
60796 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
60797   VdbeFunc *pVdbeFunc;
60798
60799   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60800   pVdbeFunc = pCtx->pVdbeFunc;
60801   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
60802     return 0;
60803   }
60804   return pVdbeFunc->apAux[iArg].pAux;
60805 }
60806
60807 /*
60808 ** Set the auxilary data pointer and delete function, for the iArg'th
60809 ** argument to the user-function defined by pCtx. Any previous value is
60810 ** deleted by calling the delete function specified when it was set.
60811 */
60812 SQLITE_API void sqlite3_set_auxdata(
60813   sqlite3_context *pCtx, 
60814   int iArg, 
60815   void *pAux, 
60816   void (*xDelete)(void*)
60817 ){
60818   struct AuxData *pAuxData;
60819   VdbeFunc *pVdbeFunc;
60820   if( iArg<0 ) goto failed;
60821
60822   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60823   pVdbeFunc = pCtx->pVdbeFunc;
60824   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
60825     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
60826     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
60827     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
60828     if( !pVdbeFunc ){
60829       goto failed;
60830     }
60831     pCtx->pVdbeFunc = pVdbeFunc;
60832     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
60833     pVdbeFunc->nAux = iArg+1;
60834     pVdbeFunc->pFunc = pCtx->pFunc;
60835   }
60836
60837   pAuxData = &pVdbeFunc->apAux[iArg];
60838   if( pAuxData->pAux && pAuxData->xDelete ){
60839     pAuxData->xDelete(pAuxData->pAux);
60840   }
60841   pAuxData->pAux = pAux;
60842   pAuxData->xDelete = xDelete;
60843   return;
60844
60845 failed:
60846   if( xDelete ){
60847     xDelete(pAux);
60848   }
60849 }
60850
60851 #ifndef SQLITE_OMIT_DEPRECATED
60852 /*
60853 ** Return the number of times the Step function of a aggregate has been 
60854 ** called.
60855 **
60856 ** This function is deprecated.  Do not use it for new code.  It is
60857 ** provide only to avoid breaking legacy code.  New aggregate function
60858 ** implementations should keep their own counts within their aggregate
60859 ** context.
60860 */
60861 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
60862   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
60863   return p->pMem->n;
60864 }
60865 #endif
60866
60867 /*
60868 ** Return the number of columns in the result set for the statement pStmt.
60869 */
60870 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
60871   Vdbe *pVm = (Vdbe *)pStmt;
60872   return pVm ? pVm->nResColumn : 0;
60873 }
60874
60875 /*
60876 ** Return the number of values available from the current row of the
60877 ** currently executing statement pStmt.
60878 */
60879 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
60880   Vdbe *pVm = (Vdbe *)pStmt;
60881   if( pVm==0 || pVm->pResultSet==0 ) return 0;
60882   return pVm->nResColumn;
60883 }
60884
60885
60886 /*
60887 ** Check to see if column iCol of the given statement is valid.  If
60888 ** it is, return a pointer to the Mem for the value of that column.
60889 ** If iCol is not valid, return a pointer to a Mem which has a value
60890 ** of NULL.
60891 */
60892 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
60893   Vdbe *pVm;
60894   Mem *pOut;
60895
60896   pVm = (Vdbe *)pStmt;
60897   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
60898     sqlite3_mutex_enter(pVm->db->mutex);
60899     pOut = &pVm->pResultSet[i];
60900   }else{
60901     /* If the value passed as the second argument is out of range, return
60902     ** a pointer to the following static Mem object which contains the
60903     ** value SQL NULL. Even though the Mem structure contains an element
60904     ** of type i64, on certain architecture (x86) with certain compiler
60905     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
60906     ** instead of an 8-byte one. This all works fine, except that when
60907     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
60908     ** that a Mem structure is located on an 8-byte boundary. To prevent
60909     ** this assert() from failing, when building with SQLITE_DEBUG defined
60910     ** using gcc, force nullMem to be 8-byte aligned using the magical
60911     ** __attribute__((aligned(8))) macro.  */
60912     static const Mem nullMem 
60913 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
60914       __attribute__((aligned(8))) 
60915 #endif
60916       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
60917 #ifdef SQLITE_DEBUG
60918          0, 0,  /* pScopyFrom, pFiller */
60919 #endif
60920          0, 0 };
60921
60922     if( pVm && ALWAYS(pVm->db) ){
60923       sqlite3_mutex_enter(pVm->db->mutex);
60924       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
60925     }
60926     pOut = (Mem*)&nullMem;
60927   }
60928   return pOut;
60929 }
60930
60931 /*
60932 ** This function is called after invoking an sqlite3_value_XXX function on a 
60933 ** column value (i.e. a value returned by evaluating an SQL expression in the
60934 ** select list of a SELECT statement) that may cause a malloc() failure. If 
60935 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
60936 ** code of statement pStmt set to SQLITE_NOMEM.
60937 **
60938 ** Specifically, this is called from within:
60939 **
60940 **     sqlite3_column_int()
60941 **     sqlite3_column_int64()
60942 **     sqlite3_column_text()
60943 **     sqlite3_column_text16()
60944 **     sqlite3_column_real()
60945 **     sqlite3_column_bytes()
60946 **     sqlite3_column_bytes16()
60947 **     sqiite3_column_blob()
60948 */
60949 static void columnMallocFailure(sqlite3_stmt *pStmt)
60950 {
60951   /* If malloc() failed during an encoding conversion within an
60952   ** sqlite3_column_XXX API, then set the return code of the statement to
60953   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
60954   ** and _finalize() will return NOMEM.
60955   */
60956   Vdbe *p = (Vdbe *)pStmt;
60957   if( p ){
60958     p->rc = sqlite3ApiExit(p->db, p->rc);
60959     sqlite3_mutex_leave(p->db->mutex);
60960   }
60961 }
60962
60963 /**************************** sqlite3_column_  *******************************
60964 ** The following routines are used to access elements of the current row
60965 ** in the result set.
60966 */
60967 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
60968   const void *val;
60969   val = sqlite3_value_blob( columnMem(pStmt,i) );
60970   /* Even though there is no encoding conversion, value_blob() might
60971   ** need to call malloc() to expand the result of a zeroblob() 
60972   ** expression. 
60973   */
60974   columnMallocFailure(pStmt);
60975   return val;
60976 }
60977 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
60978   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
60979   columnMallocFailure(pStmt);
60980   return val;
60981 }
60982 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
60983   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
60984   columnMallocFailure(pStmt);
60985   return val;
60986 }
60987 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
60988   double val = sqlite3_value_double( columnMem(pStmt,i) );
60989   columnMallocFailure(pStmt);
60990   return val;
60991 }
60992 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
60993   int val = sqlite3_value_int( columnMem(pStmt,i) );
60994   columnMallocFailure(pStmt);
60995   return val;
60996 }
60997 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
60998   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
60999   columnMallocFailure(pStmt);
61000   return val;
61001 }
61002 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
61003   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
61004   columnMallocFailure(pStmt);
61005   return val;
61006 }
61007 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
61008   Mem *pOut = columnMem(pStmt, i);
61009   if( pOut->flags&MEM_Static ){
61010     pOut->flags &= ~MEM_Static;
61011     pOut->flags |= MEM_Ephem;
61012   }
61013   columnMallocFailure(pStmt);
61014   return (sqlite3_value *)pOut;
61015 }
61016 #ifndef SQLITE_OMIT_UTF16
61017 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61018   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61019   columnMallocFailure(pStmt);
61020   return val;
61021 }
61022 #endif /* SQLITE_OMIT_UTF16 */
61023 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61024   int iType = sqlite3_value_type( columnMem(pStmt,i) );
61025   columnMallocFailure(pStmt);
61026   return iType;
61027 }
61028
61029 /* The following function is experimental and subject to change or
61030 ** removal */
61031 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61032 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61033 **}
61034 */
61035
61036 /*
61037 ** Convert the N-th element of pStmt->pColName[] into a string using
61038 ** xFunc() then return that string.  If N is out of range, return 0.
61039 **
61040 ** There are up to 5 names for each column.  useType determines which
61041 ** name is returned.  Here are the names:
61042 **
61043 **    0      The column name as it should be displayed for output
61044 **    1      The datatype name for the column
61045 **    2      The name of the database that the column derives from
61046 **    3      The name of the table that the column derives from
61047 **    4      The name of the table column that the result column derives from
61048 **
61049 ** If the result is not a simple column reference (if it is an expression
61050 ** or a constant) then useTypes 2, 3, and 4 return NULL.
61051 */
61052 static const void *columnName(
61053   sqlite3_stmt *pStmt,
61054   int N,
61055   const void *(*xFunc)(Mem*),
61056   int useType
61057 ){
61058   const void *ret = 0;
61059   Vdbe *p = (Vdbe *)pStmt;
61060   int n;
61061   sqlite3 *db = p->db;
61062   
61063   assert( db!=0 );
61064   n = sqlite3_column_count(pStmt);
61065   if( N<n && N>=0 ){
61066     N += useType*n;
61067     sqlite3_mutex_enter(db->mutex);
61068     assert( db->mallocFailed==0 );
61069     ret = xFunc(&p->aColName[N]);
61070      /* A malloc may have failed inside of the xFunc() call. If this
61071     ** is the case, clear the mallocFailed flag and return NULL.
61072     */
61073     if( db->mallocFailed ){
61074       db->mallocFailed = 0;
61075       ret = 0;
61076     }
61077     sqlite3_mutex_leave(db->mutex);
61078   }
61079   return ret;
61080 }
61081
61082 /*
61083 ** Return the name of the Nth column of the result set returned by SQL
61084 ** statement pStmt.
61085 */
61086 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61087   return columnName(
61088       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61089 }
61090 #ifndef SQLITE_OMIT_UTF16
61091 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61092   return columnName(
61093       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61094 }
61095 #endif
61096
61097 /*
61098 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
61099 ** not define OMIT_DECLTYPE.
61100 */
61101 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61102 # error "Must not define both SQLITE_OMIT_DECLTYPE \
61103          and SQLITE_ENABLE_COLUMN_METADATA"
61104 #endif
61105
61106 #ifndef SQLITE_OMIT_DECLTYPE
61107 /*
61108 ** Return the column declaration type (if applicable) of the 'i'th column
61109 ** of the result set of SQL statement pStmt.
61110 */
61111 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61112   return columnName(
61113       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61114 }
61115 #ifndef SQLITE_OMIT_UTF16
61116 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61117   return columnName(
61118       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61119 }
61120 #endif /* SQLITE_OMIT_UTF16 */
61121 #endif /* SQLITE_OMIT_DECLTYPE */
61122
61123 #ifdef SQLITE_ENABLE_COLUMN_METADATA
61124 /*
61125 ** Return the name of the database from which a result column derives.
61126 ** NULL is returned if the result column is an expression or constant or
61127 ** anything else which is not an unabiguous reference to a database column.
61128 */
61129 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61130   return columnName(
61131       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61132 }
61133 #ifndef SQLITE_OMIT_UTF16
61134 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61135   return columnName(
61136       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61137 }
61138 #endif /* SQLITE_OMIT_UTF16 */
61139
61140 /*
61141 ** Return the name of the table from which a result column derives.
61142 ** NULL is returned if the result column is an expression or constant or
61143 ** anything else which is not an unabiguous reference to a database column.
61144 */
61145 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61146   return columnName(
61147       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61148 }
61149 #ifndef SQLITE_OMIT_UTF16
61150 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61151   return columnName(
61152       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61153 }
61154 #endif /* SQLITE_OMIT_UTF16 */
61155
61156 /*
61157 ** Return the name of the table column from which a result column derives.
61158 ** NULL is returned if the result column is an expression or constant or
61159 ** anything else which is not an unabiguous reference to a database column.
61160 */
61161 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61162   return columnName(
61163       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61164 }
61165 #ifndef SQLITE_OMIT_UTF16
61166 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61167   return columnName(
61168       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61169 }
61170 #endif /* SQLITE_OMIT_UTF16 */
61171 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
61172
61173
61174 /******************************* sqlite3_bind_  ***************************
61175 ** 
61176 ** Routines used to attach values to wildcards in a compiled SQL statement.
61177 */
61178 /*
61179 ** Unbind the value bound to variable i in virtual machine p. This is the 
61180 ** the same as binding a NULL value to the column. If the "i" parameter is
61181 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61182 **
61183 ** A successful evaluation of this routine acquires the mutex on p.
61184 ** the mutex is released if any kind of error occurs.
61185 **
61186 ** The error code stored in database p->db is overwritten with the return
61187 ** value in any case.
61188 */
61189 static int vdbeUnbind(Vdbe *p, int i){
61190   Mem *pVar;
61191   if( vdbeSafetyNotNull(p) ){
61192     return SQLITE_MISUSE_BKPT;
61193   }
61194   sqlite3_mutex_enter(p->db->mutex);
61195   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61196     sqlite3Error(p->db, SQLITE_MISUSE, 0);
61197     sqlite3_mutex_leave(p->db->mutex);
61198     sqlite3_log(SQLITE_MISUSE, 
61199         "bind on a busy prepared statement: [%s]", p->zSql);
61200     return SQLITE_MISUSE_BKPT;
61201   }
61202   if( i<1 || i>p->nVar ){
61203     sqlite3Error(p->db, SQLITE_RANGE, 0);
61204     sqlite3_mutex_leave(p->db->mutex);
61205     return SQLITE_RANGE;
61206   }
61207   i--;
61208   pVar = &p->aVar[i];
61209   sqlite3VdbeMemRelease(pVar);
61210   pVar->flags = MEM_Null;
61211   sqlite3Error(p->db, SQLITE_OK, 0);
61212
61213   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
61214   ** binding a new value to this variable invalidates the current query plan.
61215   **
61216   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61217   ** parameter in the WHERE clause might influence the choice of query plan
61218   ** for a statement, then the statement will be automatically recompiled,
61219   ** as if there had been a schema change, on the first sqlite3_step() call
61220   ** following any change to the bindings of that parameter.
61221   */
61222   if( p->isPrepareV2 &&
61223      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61224   ){
61225     p->expired = 1;
61226   }
61227   return SQLITE_OK;
61228 }
61229
61230 /*
61231 ** Bind a text or BLOB value.
61232 */
61233 static int bindText(
61234   sqlite3_stmt *pStmt,   /* The statement to bind against */
61235   int i,                 /* Index of the parameter to bind */
61236   const void *zData,     /* Pointer to the data to be bound */
61237   int nData,             /* Number of bytes of data to be bound */
61238   void (*xDel)(void*),   /* Destructor for the data */
61239   u8 encoding            /* Encoding for the data */
61240 ){
61241   Vdbe *p = (Vdbe *)pStmt;
61242   Mem *pVar;
61243   int rc;
61244
61245   rc = vdbeUnbind(p, i);
61246   if( rc==SQLITE_OK ){
61247     if( zData!=0 ){
61248       pVar = &p->aVar[i-1];
61249       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61250       if( rc==SQLITE_OK && encoding!=0 ){
61251         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61252       }
61253       sqlite3Error(p->db, rc, 0);
61254       rc = sqlite3ApiExit(p->db, rc);
61255     }
61256     sqlite3_mutex_leave(p->db->mutex);
61257   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61258     xDel((void*)zData);
61259   }
61260   return rc;
61261 }
61262
61263
61264 /*
61265 ** Bind a blob value to an SQL statement variable.
61266 */
61267 SQLITE_API int sqlite3_bind_blob(
61268   sqlite3_stmt *pStmt, 
61269   int i, 
61270   const void *zData, 
61271   int nData, 
61272   void (*xDel)(void*)
61273 ){
61274   return bindText(pStmt, i, zData, nData, xDel, 0);
61275 }
61276 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61277   int rc;
61278   Vdbe *p = (Vdbe *)pStmt;
61279   rc = vdbeUnbind(p, i);
61280   if( rc==SQLITE_OK ){
61281     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61282     sqlite3_mutex_leave(p->db->mutex);
61283   }
61284   return rc;
61285 }
61286 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61287   return sqlite3_bind_int64(p, i, (i64)iValue);
61288 }
61289 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61290   int rc;
61291   Vdbe *p = (Vdbe *)pStmt;
61292   rc = vdbeUnbind(p, i);
61293   if( rc==SQLITE_OK ){
61294     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61295     sqlite3_mutex_leave(p->db->mutex);
61296   }
61297   return rc;
61298 }
61299 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61300   int rc;
61301   Vdbe *p = (Vdbe*)pStmt;
61302   rc = vdbeUnbind(p, i);
61303   if( rc==SQLITE_OK ){
61304     sqlite3_mutex_leave(p->db->mutex);
61305   }
61306   return rc;
61307 }
61308 SQLITE_API int sqlite3_bind_text( 
61309   sqlite3_stmt *pStmt, 
61310   int i, 
61311   const char *zData, 
61312   int nData, 
61313   void (*xDel)(void*)
61314 ){
61315   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61316 }
61317 #ifndef SQLITE_OMIT_UTF16
61318 SQLITE_API int sqlite3_bind_text16(
61319   sqlite3_stmt *pStmt, 
61320   int i, 
61321   const void *zData, 
61322   int nData, 
61323   void (*xDel)(void*)
61324 ){
61325   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61326 }
61327 #endif /* SQLITE_OMIT_UTF16 */
61328 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61329   int rc;
61330   switch( pValue->type ){
61331     case SQLITE_INTEGER: {
61332       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61333       break;
61334     }
61335     case SQLITE_FLOAT: {
61336       rc = sqlite3_bind_double(pStmt, i, pValue->r);
61337       break;
61338     }
61339     case SQLITE_BLOB: {
61340       if( pValue->flags & MEM_Zero ){
61341         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61342       }else{
61343         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61344       }
61345       break;
61346     }
61347     case SQLITE_TEXT: {
61348       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
61349                               pValue->enc);
61350       break;
61351     }
61352     default: {
61353       rc = sqlite3_bind_null(pStmt, i);
61354       break;
61355     }
61356   }
61357   return rc;
61358 }
61359 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61360   int rc;
61361   Vdbe *p = (Vdbe *)pStmt;
61362   rc = vdbeUnbind(p, i);
61363   if( rc==SQLITE_OK ){
61364     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61365     sqlite3_mutex_leave(p->db->mutex);
61366   }
61367   return rc;
61368 }
61369
61370 /*
61371 ** Return the number of wildcards that can be potentially bound to.
61372 ** This routine is added to support DBD::SQLite.  
61373 */
61374 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61375   Vdbe *p = (Vdbe*)pStmt;
61376   return p ? p->nVar : 0;
61377 }
61378
61379 /*
61380 ** Create a mapping from variable numbers to variable names
61381 ** in the Vdbe.azVar[] array, if such a mapping does not already
61382 ** exist.
61383 */
61384 static void createVarMap(Vdbe *p){
61385   if( !p->okVar ){
61386     int j;
61387     Op *pOp;
61388     sqlite3_mutex_enter(p->db->mutex);
61389     /* The race condition here is harmless.  If two threads call this
61390     ** routine on the same Vdbe at the same time, they both might end
61391     ** up initializing the Vdbe.azVar[] array.  That is a little extra
61392     ** work but it results in the same answer.
61393     */
61394     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
61395       if( pOp->opcode==OP_Variable ){
61396         assert( pOp->p1>0 && pOp->p1<=p->nVar );
61397         p->azVar[pOp->p1-1] = pOp->p4.z;
61398       }
61399     }
61400     p->okVar = 1;
61401     sqlite3_mutex_leave(p->db->mutex);
61402   }
61403 }
61404
61405 /*
61406 ** Return the name of a wildcard parameter.  Return NULL if the index
61407 ** is out of range or if the wildcard is unnamed.
61408 **
61409 ** The result is always UTF-8.
61410 */
61411 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61412   Vdbe *p = (Vdbe*)pStmt;
61413   if( p==0 || i<1 || i>p->nVar ){
61414     return 0;
61415   }
61416   createVarMap(p);
61417   return p->azVar[i-1];
61418 }
61419
61420 /*
61421 ** Given a wildcard parameter name, return the index of the variable
61422 ** with that name.  If there is no variable with the given name,
61423 ** return 0.
61424 */
61425 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61426   int i;
61427   if( p==0 ){
61428     return 0;
61429   }
61430   createVarMap(p); 
61431   if( zName ){
61432     for(i=0; i<p->nVar; i++){
61433       const char *z = p->azVar[i];
61434       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
61435         return i+1;
61436       }
61437     }
61438   }
61439   return 0;
61440 }
61441 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
61442   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
61443 }
61444
61445 /*
61446 ** Transfer all bindings from the first statement over to the second.
61447 */
61448 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61449   Vdbe *pFrom = (Vdbe*)pFromStmt;
61450   Vdbe *pTo = (Vdbe*)pToStmt;
61451   int i;
61452   assert( pTo->db==pFrom->db );
61453   assert( pTo->nVar==pFrom->nVar );
61454   sqlite3_mutex_enter(pTo->db->mutex);
61455   for(i=0; i<pFrom->nVar; i++){
61456     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
61457   }
61458   sqlite3_mutex_leave(pTo->db->mutex);
61459   return SQLITE_OK;
61460 }
61461
61462 #ifndef SQLITE_OMIT_DEPRECATED
61463 /*
61464 ** Deprecated external interface.  Internal/core SQLite code
61465 ** should call sqlite3TransferBindings.
61466 **
61467 ** Is is misuse to call this routine with statements from different
61468 ** database connections.  But as this is a deprecated interface, we
61469 ** will not bother to check for that condition.
61470 **
61471 ** If the two statements contain a different number of bindings, then
61472 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
61473 ** SQLITE_OK is returned.
61474 */
61475 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61476   Vdbe *pFrom = (Vdbe*)pFromStmt;
61477   Vdbe *pTo = (Vdbe*)pToStmt;
61478   if( pFrom->nVar!=pTo->nVar ){
61479     return SQLITE_ERROR;
61480   }
61481   if( pTo->isPrepareV2 && pTo->expmask ){
61482     pTo->expired = 1;
61483   }
61484   if( pFrom->isPrepareV2 && pFrom->expmask ){
61485     pFrom->expired = 1;
61486   }
61487   return sqlite3TransferBindings(pFromStmt, pToStmt);
61488 }
61489 #endif
61490
61491 /*
61492 ** Return the sqlite3* database handle to which the prepared statement given
61493 ** in the argument belongs.  This is the same database handle that was
61494 ** the first argument to the sqlite3_prepare() that was used to create
61495 ** the statement in the first place.
61496 */
61497 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
61498   return pStmt ? ((Vdbe*)pStmt)->db : 0;
61499 }
61500
61501 /*
61502 ** Return true if the prepared statement is guaranteed to not modify the
61503 ** database.
61504 */
61505 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
61506   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
61507 }
61508
61509 /*
61510 ** Return a pointer to the next prepared statement after pStmt associated
61511 ** with database connection pDb.  If pStmt is NULL, return the first
61512 ** prepared statement for the database connection.  Return NULL if there
61513 ** are no more.
61514 */
61515 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
61516   sqlite3_stmt *pNext;
61517   sqlite3_mutex_enter(pDb->mutex);
61518   if( pStmt==0 ){
61519     pNext = (sqlite3_stmt*)pDb->pVdbe;
61520   }else{
61521     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
61522   }
61523   sqlite3_mutex_leave(pDb->mutex);
61524   return pNext;
61525 }
61526
61527 /*
61528 ** Return the value of a status counter for a prepared statement
61529 */
61530 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
61531   Vdbe *pVdbe = (Vdbe*)pStmt;
61532   int v = pVdbe->aCounter[op-1];
61533   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
61534   return v;
61535 }
61536
61537 /************** End of vdbeapi.c *********************************************/
61538 /************** Begin file vdbetrace.c ***************************************/
61539 /*
61540 ** 2009 November 25
61541 **
61542 ** The author disclaims copyright to this source code.  In place of
61543 ** a legal notice, here is a blessing:
61544 **
61545 **    May you do good and not evil.
61546 **    May you find forgiveness for yourself and forgive others.
61547 **    May you share freely, never taking more than you give.
61548 **
61549 *************************************************************************
61550 **
61551 ** This file contains code used to insert the values of host parameters
61552 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
61553 */
61554
61555 #ifndef SQLITE_OMIT_TRACE
61556
61557 /*
61558 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
61559 ** bytes in this text up to but excluding the first character in
61560 ** a host parameter.  If the text contains no host parameters, return
61561 ** the total number of bytes in the text.
61562 */
61563 static int findNextHostParameter(const char *zSql, int *pnToken){
61564   int tokenType;
61565   int nTotal = 0;
61566   int n;
61567
61568   *pnToken = 0;
61569   while( zSql[0] ){
61570     n = sqlite3GetToken((u8*)zSql, &tokenType);
61571     assert( n>0 && tokenType!=TK_ILLEGAL );
61572     if( tokenType==TK_VARIABLE ){
61573       *pnToken = n;
61574       break;
61575     }
61576     nTotal += n;
61577     zSql += n;
61578   }
61579   return nTotal;
61580 }
61581
61582 /*
61583 ** This function returns a pointer to a nul-terminated string in memory
61584 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
61585 ** string contains a copy of zRawSql but with host parameters expanded to 
61586 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
61587 ** then the returned string holds a copy of zRawSql with "-- " prepended
61588 ** to each line of text.
61589 **
61590 ** The calling function is responsible for making sure the memory returned
61591 ** is eventually freed.
61592 **
61593 ** ALGORITHM:  Scan the input string looking for host parameters in any of
61594 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
61595 ** string literals, quoted identifier names, and comments.  For text forms,
61596 ** the host parameter index is found by scanning the perpared
61597 ** statement for the corresponding OP_Variable opcode.  Once the host
61598 ** parameter index is known, locate the value in p->aVar[].  Then render
61599 ** the value as a literal in place of the host parameter name.
61600 */
61601 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
61602   Vdbe *p,                 /* The prepared statement being evaluated */
61603   const char *zRawSql      /* Raw text of the SQL statement */
61604 ){
61605   sqlite3 *db;             /* The database connection */
61606   int idx = 0;             /* Index of a host parameter */
61607   int nextIndex = 1;       /* Index of next ? host parameter */
61608   int n;                   /* Length of a token prefix */
61609   int nToken;              /* Length of the parameter token */
61610   int i;                   /* Loop counter */
61611   Mem *pVar;               /* Value of a host parameter */
61612   StrAccum out;            /* Accumulate the output here */
61613   char zBase[100];         /* Initial working space */
61614
61615   db = p->db;
61616   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
61617                       db->aLimit[SQLITE_LIMIT_LENGTH]);
61618   out.db = db;
61619   if( db->vdbeExecCnt>1 ){
61620     while( *zRawSql ){
61621       const char *zStart = zRawSql;
61622       while( *(zRawSql++)!='\n' && *zRawSql );
61623       sqlite3StrAccumAppend(&out, "-- ", 3);
61624       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
61625     }
61626   }else{
61627     while( zRawSql[0] ){
61628       n = findNextHostParameter(zRawSql, &nToken);
61629       assert( n>0 );
61630       sqlite3StrAccumAppend(&out, zRawSql, n);
61631       zRawSql += n;
61632       assert( zRawSql[0] || nToken==0 );
61633       if( nToken==0 ) break;
61634       if( zRawSql[0]=='?' ){
61635         if( nToken>1 ){
61636           assert( sqlite3Isdigit(zRawSql[1]) );
61637           sqlite3GetInt32(&zRawSql[1], &idx);
61638         }else{
61639           idx = nextIndex;
61640         }
61641       }else{
61642         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
61643         testcase( zRawSql[0]==':' );
61644         testcase( zRawSql[0]=='$' );
61645         testcase( zRawSql[0]=='@' );
61646         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
61647         assert( idx>0 );
61648       }
61649       zRawSql += nToken;
61650       nextIndex = idx + 1;
61651       assert( idx>0 && idx<=p->nVar );
61652       pVar = &p->aVar[idx-1];
61653       if( pVar->flags & MEM_Null ){
61654         sqlite3StrAccumAppend(&out, "NULL", 4);
61655       }else if( pVar->flags & MEM_Int ){
61656         sqlite3XPrintf(&out, "%lld", pVar->u.i);
61657       }else if( pVar->flags & MEM_Real ){
61658         sqlite3XPrintf(&out, "%!.15g", pVar->r);
61659       }else if( pVar->flags & MEM_Str ){
61660 #ifndef SQLITE_OMIT_UTF16
61661         u8 enc = ENC(db);
61662         if( enc!=SQLITE_UTF8 ){
61663           Mem utf8;
61664           memset(&utf8, 0, sizeof(utf8));
61665           utf8.db = db;
61666           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
61667           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
61668           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
61669           sqlite3VdbeMemRelease(&utf8);
61670         }else
61671 #endif
61672         {
61673           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
61674         }
61675       }else if( pVar->flags & MEM_Zero ){
61676         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
61677       }else{
61678         assert( pVar->flags & MEM_Blob );
61679         sqlite3StrAccumAppend(&out, "x'", 2);
61680         for(i=0; i<pVar->n; i++){
61681           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
61682         }
61683         sqlite3StrAccumAppend(&out, "'", 1);
61684       }
61685     }
61686   }
61687   return sqlite3StrAccumFinish(&out);
61688 }
61689
61690 #endif /* #ifndef SQLITE_OMIT_TRACE */
61691
61692 /************** End of vdbetrace.c *******************************************/
61693 /************** Begin file vdbe.c ********************************************/
61694 /*
61695 ** 2001 September 15
61696 **
61697 ** The author disclaims copyright to this source code.  In place of
61698 ** a legal notice, here is a blessing:
61699 **
61700 **    May you do good and not evil.
61701 **    May you find forgiveness for yourself and forgive others.
61702 **    May you share freely, never taking more than you give.
61703 **
61704 *************************************************************************
61705 ** The code in this file implements execution method of the 
61706 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
61707 ** handles housekeeping details such as creating and deleting
61708 ** VDBE instances.  This file is solely interested in executing
61709 ** the VDBE program.
61710 **
61711 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
61712 ** to a VDBE.
61713 **
61714 ** The SQL parser generates a program which is then executed by
61715 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
61716 ** similar in form to assembly language.  The program consists of
61717 ** a linear sequence of operations.  Each operation has an opcode 
61718 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
61719 ** is a null-terminated string.  Operand P5 is an unsigned character.
61720 ** Few opcodes use all 5 operands.
61721 **
61722 ** Computation results are stored on a set of registers numbered beginning
61723 ** with 1 and going up to Vdbe.nMem.  Each register can store
61724 ** either an integer, a null-terminated string, a floating point
61725 ** number, or the SQL "NULL" value.  An implicit conversion from one
61726 ** type to the other occurs as necessary.
61727 ** 
61728 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
61729 ** function which does the work of interpreting a VDBE program.
61730 ** But other routines are also provided to help in building up
61731 ** a program instruction by instruction.
61732 **
61733 ** Various scripts scan this source file in order to generate HTML
61734 ** documentation, headers files, or other derived files.  The formatting
61735 ** of the code in this file is, therefore, important.  See other comments
61736 ** in this file for details.  If in doubt, do not deviate from existing
61737 ** commenting and indentation practices when changing or adding code.
61738 */
61739
61740 /*
61741 ** Invoke this macro on memory cells just prior to changing the
61742 ** value of the cell.  This macro verifies that shallow copies are
61743 ** not misused.
61744 */
61745 #ifdef SQLITE_DEBUG
61746 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
61747 #else
61748 # define memAboutToChange(P,M)
61749 #endif
61750
61751 /*
61752 ** The following global variable is incremented every time a cursor
61753 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
61754 ** procedures use this information to make sure that indices are
61755 ** working correctly.  This variable has no function other than to
61756 ** help verify the correct operation of the library.
61757 */
61758 #ifdef SQLITE_TEST
61759 SQLITE_API int sqlite3_search_count = 0;
61760 #endif
61761
61762 /*
61763 ** When this global variable is positive, it gets decremented once before
61764 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
61765 ** field of the sqlite3 structure is set in order to simulate and interrupt.
61766 **
61767 ** This facility is used for testing purposes only.  It does not function
61768 ** in an ordinary build.
61769 */
61770 #ifdef SQLITE_TEST
61771 SQLITE_API int sqlite3_interrupt_count = 0;
61772 #endif
61773
61774 /*
61775 ** The next global variable is incremented each type the OP_Sort opcode
61776 ** is executed.  The test procedures use this information to make sure that
61777 ** sorting is occurring or not occurring at appropriate times.   This variable
61778 ** has no function other than to help verify the correct operation of the
61779 ** library.
61780 */
61781 #ifdef SQLITE_TEST
61782 SQLITE_API int sqlite3_sort_count = 0;
61783 #endif
61784
61785 /*
61786 ** The next global variable records the size of the largest MEM_Blob
61787 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
61788 ** use this information to make sure that the zero-blob functionality
61789 ** is working correctly.   This variable has no function other than to
61790 ** help verify the correct operation of the library.
61791 */
61792 #ifdef SQLITE_TEST
61793 SQLITE_API int sqlite3_max_blobsize = 0;
61794 static void updateMaxBlobsize(Mem *p){
61795   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
61796     sqlite3_max_blobsize = p->n;
61797   }
61798 }
61799 #endif
61800
61801 /*
61802 ** The next global variable is incremented each type the OP_Found opcode
61803 ** is executed. This is used to test whether or not the foreign key
61804 ** operation implemented using OP_FkIsZero is working. This variable
61805 ** has no function other than to help verify the correct operation of the
61806 ** library.
61807 */
61808 #ifdef SQLITE_TEST
61809 SQLITE_API int sqlite3_found_count = 0;
61810 #endif
61811
61812 /*
61813 ** Test a register to see if it exceeds the current maximum blob size.
61814 ** If it does, record the new maximum blob size.
61815 */
61816 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
61817 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
61818 #else
61819 # define UPDATE_MAX_BLOBSIZE(P)
61820 #endif
61821
61822 /*
61823 ** Convert the given register into a string if it isn't one
61824 ** already. Return non-zero if a malloc() fails.
61825 */
61826 #define Stringify(P, enc) \
61827    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
61828      { goto no_mem; }
61829
61830 /*
61831 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
61832 ** a pointer to a dynamically allocated string where some other entity
61833 ** is responsible for deallocating that string.  Because the register
61834 ** does not control the string, it might be deleted without the register
61835 ** knowing it.
61836 **
61837 ** This routine converts an ephemeral string into a dynamically allocated
61838 ** string that the register itself controls.  In other words, it
61839 ** converts an MEM_Ephem string into an MEM_Dyn string.
61840 */
61841 #define Deephemeralize(P) \
61842    if( ((P)->flags&MEM_Ephem)!=0 \
61843        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
61844
61845 /*
61846 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
61847 ** P if required.
61848 */
61849 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
61850
61851 /*
61852 ** Argument pMem points at a register that will be passed to a
61853 ** user-defined function or returned to the user as the result of a query.
61854 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
61855 ** routines.
61856 */
61857 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
61858   int flags = pMem->flags;
61859   if( flags & MEM_Null ){
61860     pMem->type = SQLITE_NULL;
61861   }
61862   else if( flags & MEM_Int ){
61863     pMem->type = SQLITE_INTEGER;
61864   }
61865   else if( flags & MEM_Real ){
61866     pMem->type = SQLITE_FLOAT;
61867   }
61868   else if( flags & MEM_Str ){
61869     pMem->type = SQLITE_TEXT;
61870   }else{
61871     pMem->type = SQLITE_BLOB;
61872   }
61873 }
61874
61875 /*
61876 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
61877 ** if we run out of memory.
61878 */
61879 static VdbeCursor *allocateCursor(
61880   Vdbe *p,              /* The virtual machine */
61881   int iCur,             /* Index of the new VdbeCursor */
61882   int nField,           /* Number of fields in the table or index */
61883   int iDb,              /* When database the cursor belongs to, or -1 */
61884   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
61885 ){
61886   /* Find the memory cell that will be used to store the blob of memory
61887   ** required for this VdbeCursor structure. It is convenient to use a 
61888   ** vdbe memory cell to manage the memory allocation required for a
61889   ** VdbeCursor structure for the following reasons:
61890   **
61891   **   * Sometimes cursor numbers are used for a couple of different
61892   **     purposes in a vdbe program. The different uses might require
61893   **     different sized allocations. Memory cells provide growable
61894   **     allocations.
61895   **
61896   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
61897   **     be freed lazily via the sqlite3_release_memory() API. This
61898   **     minimizes the number of malloc calls made by the system.
61899   **
61900   ** Memory cells for cursors are allocated at the top of the address
61901   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
61902   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
61903   */
61904   Mem *pMem = &p->aMem[p->nMem-iCur];
61905
61906   int nByte;
61907   VdbeCursor *pCx = 0;
61908   nByte = 
61909       ROUND8(sizeof(VdbeCursor)) + 
61910       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
61911       2*nField*sizeof(u32);
61912
61913   assert( iCur<p->nCursor );
61914   if( p->apCsr[iCur] ){
61915     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
61916     p->apCsr[iCur] = 0;
61917   }
61918   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
61919     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
61920     memset(pCx, 0, sizeof(VdbeCursor));
61921     pCx->iDb = iDb;
61922     pCx->nField = nField;
61923     if( nField ){
61924       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
61925     }
61926     if( isBtreeCursor ){
61927       pCx->pCursor = (BtCursor*)
61928           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
61929       sqlite3BtreeCursorZero(pCx->pCursor);
61930     }
61931   }
61932   return pCx;
61933 }
61934
61935 /*
61936 ** Try to convert a value into a numeric representation if we can
61937 ** do so without loss of information.  In other words, if the string
61938 ** looks like a number, convert it into a number.  If it does not
61939 ** look like a number, leave it alone.
61940 */
61941 static void applyNumericAffinity(Mem *pRec){
61942   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
61943     double rValue;
61944     i64 iValue;
61945     u8 enc = pRec->enc;
61946     if( (pRec->flags&MEM_Str)==0 ) return;
61947     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
61948     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
61949       pRec->u.i = iValue;
61950       pRec->flags |= MEM_Int;
61951     }else{
61952       pRec->r = rValue;
61953       pRec->flags |= MEM_Real;
61954     }
61955   }
61956 }
61957
61958 /*
61959 ** Processing is determine by the affinity parameter:
61960 **
61961 ** SQLITE_AFF_INTEGER:
61962 ** SQLITE_AFF_REAL:
61963 ** SQLITE_AFF_NUMERIC:
61964 **    Try to convert pRec to an integer representation or a 
61965 **    floating-point representation if an integer representation
61966 **    is not possible.  Note that the integer representation is
61967 **    always preferred, even if the affinity is REAL, because
61968 **    an integer representation is more space efficient on disk.
61969 **
61970 ** SQLITE_AFF_TEXT:
61971 **    Convert pRec to a text representation.
61972 **
61973 ** SQLITE_AFF_NONE:
61974 **    No-op.  pRec is unchanged.
61975 */
61976 static void applyAffinity(
61977   Mem *pRec,          /* The value to apply affinity to */
61978   char affinity,      /* The affinity to be applied */
61979   u8 enc              /* Use this text encoding */
61980 ){
61981   if( affinity==SQLITE_AFF_TEXT ){
61982     /* Only attempt the conversion to TEXT if there is an integer or real
61983     ** representation (blob and NULL do not get converted) but no string
61984     ** representation.
61985     */
61986     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
61987       sqlite3VdbeMemStringify(pRec, enc);
61988     }
61989     pRec->flags &= ~(MEM_Real|MEM_Int);
61990   }else if( affinity!=SQLITE_AFF_NONE ){
61991     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
61992              || affinity==SQLITE_AFF_NUMERIC );
61993     applyNumericAffinity(pRec);
61994     if( pRec->flags & MEM_Real ){
61995       sqlite3VdbeIntegerAffinity(pRec);
61996     }
61997   }
61998 }
61999
62000 /*
62001 ** Try to convert the type of a function argument or a result column
62002 ** into a numeric representation.  Use either INTEGER or REAL whichever
62003 ** is appropriate.  But only do the conversion if it is possible without
62004 ** loss of information and return the revised type of the argument.
62005 */
62006 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
62007   Mem *pMem = (Mem*)pVal;
62008   if( pMem->type==SQLITE_TEXT ){
62009     applyNumericAffinity(pMem);
62010     sqlite3VdbeMemStoreType(pMem);
62011   }
62012   return pMem->type;
62013 }
62014
62015 /*
62016 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
62017 ** not the internal Mem* type.
62018 */
62019 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62020   sqlite3_value *pVal, 
62021   u8 affinity, 
62022   u8 enc
62023 ){
62024   applyAffinity((Mem *)pVal, affinity, enc);
62025 }
62026
62027 #ifdef SQLITE_DEBUG
62028 /*
62029 ** Write a nice string representation of the contents of cell pMem
62030 ** into buffer zBuf, length nBuf.
62031 */
62032 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62033   char *zCsr = zBuf;
62034   int f = pMem->flags;
62035
62036   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62037
62038   if( f&MEM_Blob ){
62039     int i;
62040     char c;
62041     if( f & MEM_Dyn ){
62042       c = 'z';
62043       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62044     }else if( f & MEM_Static ){
62045       c = 't';
62046       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62047     }else if( f & MEM_Ephem ){
62048       c = 'e';
62049       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62050     }else{
62051       c = 's';
62052     }
62053
62054     sqlite3_snprintf(100, zCsr, "%c", c);
62055     zCsr += sqlite3Strlen30(zCsr);
62056     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62057     zCsr += sqlite3Strlen30(zCsr);
62058     for(i=0; i<16 && i<pMem->n; i++){
62059       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62060       zCsr += sqlite3Strlen30(zCsr);
62061     }
62062     for(i=0; i<16 && i<pMem->n; i++){
62063       char z = pMem->z[i];
62064       if( z<32 || z>126 ) *zCsr++ = '.';
62065       else *zCsr++ = z;
62066     }
62067
62068     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62069     zCsr += sqlite3Strlen30(zCsr);
62070     if( f & MEM_Zero ){
62071       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62072       zCsr += sqlite3Strlen30(zCsr);
62073     }
62074     *zCsr = '\0';
62075   }else if( f & MEM_Str ){
62076     int j, k;
62077     zBuf[0] = ' ';
62078     if( f & MEM_Dyn ){
62079       zBuf[1] = 'z';
62080       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62081     }else if( f & MEM_Static ){
62082       zBuf[1] = 't';
62083       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62084     }else if( f & MEM_Ephem ){
62085       zBuf[1] = 'e';
62086       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62087     }else{
62088       zBuf[1] = 's';
62089     }
62090     k = 2;
62091     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62092     k += sqlite3Strlen30(&zBuf[k]);
62093     zBuf[k++] = '[';
62094     for(j=0; j<15 && j<pMem->n; j++){
62095       u8 c = pMem->z[j];
62096       if( c>=0x20 && c<0x7f ){
62097         zBuf[k++] = c;
62098       }else{
62099         zBuf[k++] = '.';
62100       }
62101     }
62102     zBuf[k++] = ']';
62103     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62104     k += sqlite3Strlen30(&zBuf[k]);
62105     zBuf[k++] = 0;
62106   }
62107 }
62108 #endif
62109
62110 #ifdef SQLITE_DEBUG
62111 /*
62112 ** Print the value of a register for tracing purposes:
62113 */
62114 static void memTracePrint(FILE *out, Mem *p){
62115   if( p->flags & MEM_Null ){
62116     fprintf(out, " NULL");
62117   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62118     fprintf(out, " si:%lld", p->u.i);
62119   }else if( p->flags & MEM_Int ){
62120     fprintf(out, " i:%lld", p->u.i);
62121 #ifndef SQLITE_OMIT_FLOATING_POINT
62122   }else if( p->flags & MEM_Real ){
62123     fprintf(out, " r:%g", p->r);
62124 #endif
62125   }else if( p->flags & MEM_RowSet ){
62126     fprintf(out, " (rowset)");
62127   }else{
62128     char zBuf[200];
62129     sqlite3VdbeMemPrettyPrint(p, zBuf);
62130     fprintf(out, " ");
62131     fprintf(out, "%s", zBuf);
62132   }
62133 }
62134 static void registerTrace(FILE *out, int iReg, Mem *p){
62135   fprintf(out, "REG[%d] = ", iReg);
62136   memTracePrint(out, p);
62137   fprintf(out, "\n");
62138 }
62139 #endif
62140
62141 #ifdef SQLITE_DEBUG
62142 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62143 #else
62144 #  define REGISTER_TRACE(R,M)
62145 #endif
62146
62147
62148 #ifdef VDBE_PROFILE
62149
62150 /* 
62151 ** hwtime.h contains inline assembler code for implementing 
62152 ** high-performance timing routines.
62153 */
62154 /************** Include hwtime.h in the middle of vdbe.c *********************/
62155 /************** Begin file hwtime.h ******************************************/
62156 /*
62157 ** 2008 May 27
62158 **
62159 ** The author disclaims copyright to this source code.  In place of
62160 ** a legal notice, here is a blessing:
62161 **
62162 **    May you do good and not evil.
62163 **    May you find forgiveness for yourself and forgive others.
62164 **    May you share freely, never taking more than you give.
62165 **
62166 ******************************************************************************
62167 **
62168 ** This file contains inline asm code for retrieving "high-performance"
62169 ** counters for x86 class CPUs.
62170 */
62171 #ifndef _HWTIME_H_
62172 #define _HWTIME_H_
62173
62174 /*
62175 ** The following routine only works on pentium-class (or newer) processors.
62176 ** It uses the RDTSC opcode to read the cycle count value out of the
62177 ** processor and returns that value.  This can be used for high-res
62178 ** profiling.
62179 */
62180 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
62181       (defined(i386) || defined(__i386__) || defined(_M_IX86))
62182
62183   #if defined(__GNUC__)
62184
62185   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62186      unsigned int lo, hi;
62187      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62188      return (sqlite_uint64)hi << 32 | lo;
62189   }
62190
62191   #elif defined(_MSC_VER)
62192
62193   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62194      __asm {
62195         rdtsc
62196         ret       ; return value at EDX:EAX
62197      }
62198   }
62199
62200   #endif
62201
62202 #elif (defined(__GNUC__) && defined(__x86_64__))
62203
62204   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62205       unsigned long val;
62206       __asm__ __volatile__ ("rdtsc" : "=A" (val));
62207       return val;
62208   }
62209  
62210 #elif (defined(__GNUC__) && defined(__ppc__))
62211
62212   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62213       unsigned long long retval;
62214       unsigned long junk;
62215       __asm__ __volatile__ ("\n\
62216           1:      mftbu   %1\n\
62217                   mftb    %L0\n\
62218                   mftbu   %0\n\
62219                   cmpw    %0,%1\n\
62220                   bne     1b"
62221                   : "=r" (retval), "=r" (junk));
62222       return retval;
62223   }
62224
62225 #else
62226
62227   #error Need implementation of sqlite3Hwtime() for your platform.
62228
62229   /*
62230   ** To compile without implementing sqlite3Hwtime() for your platform,
62231   ** you can remove the above #error and use the following
62232   ** stub function.  You will lose timing support for many
62233   ** of the debugging and testing utilities, but it should at
62234   ** least compile and run.
62235   */
62236 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62237
62238 #endif
62239
62240 #endif /* !defined(_HWTIME_H_) */
62241
62242 /************** End of hwtime.h **********************************************/
62243 /************** Continuing where we left off in vdbe.c ***********************/
62244
62245 #endif
62246
62247 /*
62248 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62249 ** sqlite3_interrupt() routine has been called.  If it has been, then
62250 ** processing of the VDBE program is interrupted.
62251 **
62252 ** This macro added to every instruction that does a jump in order to
62253 ** implement a loop.  This test used to be on every single instruction,
62254 ** but that meant we more testing that we needed.  By only testing the
62255 ** flag on jump instructions, we get a (small) speed improvement.
62256 */
62257 #define CHECK_FOR_INTERRUPT \
62258    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62259
62260
62261 #ifndef NDEBUG
62262 /*
62263 ** This function is only called from within an assert() expression. It
62264 ** checks that the sqlite3.nTransaction variable is correctly set to
62265 ** the number of non-transaction savepoints currently in the 
62266 ** linked list starting at sqlite3.pSavepoint.
62267 ** 
62268 ** Usage:
62269 **
62270 **     assert( checkSavepointCount(db) );
62271 */
62272 static int checkSavepointCount(sqlite3 *db){
62273   int n = 0;
62274   Savepoint *p;
62275   for(p=db->pSavepoint; p; p=p->pNext) n++;
62276   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62277   return 1;
62278 }
62279 #endif
62280
62281 /*
62282 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62283 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62284 ** in memory obtained from sqlite3DbMalloc).
62285 */
62286 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62287   sqlite3 *db = p->db;
62288   sqlite3DbFree(db, p->zErrMsg);
62289   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62290   sqlite3_free(pVtab->zErrMsg);
62291   pVtab->zErrMsg = 0;
62292 }
62293
62294
62295 /*
62296 ** Execute as much of a VDBE program as we can then return.
62297 **
62298 ** sqlite3VdbeMakeReady() must be called before this routine in order to
62299 ** close the program with a final OP_Halt and to set up the callbacks
62300 ** and the error message pointer.
62301 **
62302 ** Whenever a row or result data is available, this routine will either
62303 ** invoke the result callback (if there is one) or return with
62304 ** SQLITE_ROW.
62305 **
62306 ** If an attempt is made to open a locked database, then this routine
62307 ** will either invoke the busy callback (if there is one) or it will
62308 ** return SQLITE_BUSY.
62309 **
62310 ** If an error occurs, an error message is written to memory obtained
62311 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62312 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62313 **
62314 ** If the callback ever returns non-zero, then the program exits
62315 ** immediately.  There will be no error message but the p->rc field is
62316 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62317 **
62318 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62319 ** routine to return SQLITE_ERROR.
62320 **
62321 ** Other fatal errors return SQLITE_ERROR.
62322 **
62323 ** After this routine has finished, sqlite3VdbeFinalize() should be
62324 ** used to clean up the mess that was left behind.
62325 */
62326 SQLITE_PRIVATE int sqlite3VdbeExec(
62327   Vdbe *p                    /* The VDBE */
62328 ){
62329   int pc=0;                  /* The program counter */
62330   Op *aOp = p->aOp;          /* Copy of p->aOp */
62331   Op *pOp;                   /* Current operation */
62332   int rc = SQLITE_OK;        /* Value to return */
62333   sqlite3 *db = p->db;       /* The database */
62334   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62335   u8 encoding = ENC(db);     /* The database encoding */
62336 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62337   int checkProgress;         /* True if progress callbacks are enabled */
62338   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
62339 #endif
62340   Mem *aMem = p->aMem;       /* Copy of p->aMem */
62341   Mem *pIn1 = 0;             /* 1st input operand */
62342   Mem *pIn2 = 0;             /* 2nd input operand */
62343   Mem *pIn3 = 0;             /* 3rd input operand */
62344   Mem *pOut = 0;             /* Output operand */
62345   int iCompare = 0;          /* Result of last OP_Compare operation */
62346   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
62347 #ifdef VDBE_PROFILE
62348   u64 start;                 /* CPU clock count at start of opcode */
62349   int origPc;                /* Program counter at start of opcode */
62350 #endif
62351   /********************************************************************
62352   ** Automatically generated code
62353   **
62354   ** The following union is automatically generated by the
62355   ** vdbe-compress.tcl script.  The purpose of this union is to
62356   ** reduce the amount of stack space required by this function.
62357   ** See comments in the vdbe-compress.tcl script for details.
62358   */
62359   union vdbeExecUnion {
62360     struct OP_Yield_stack_vars {
62361       int pcDest;
62362     } aa;
62363     struct OP_Variable_stack_vars {
62364       Mem *pVar;       /* Value being transferred */
62365     } ab;
62366     struct OP_Move_stack_vars {
62367       char *zMalloc;   /* Holding variable for allocated memory */
62368       int n;           /* Number of registers left to copy */
62369       int p1;          /* Register to copy from */
62370       int p2;          /* Register to copy to */
62371     } ac;
62372     struct OP_ResultRow_stack_vars {
62373       Mem *pMem;
62374       int i;
62375     } ad;
62376     struct OP_Concat_stack_vars {
62377       i64 nByte;
62378     } ae;
62379     struct OP_Remainder_stack_vars {
62380       int flags;      /* Combined MEM_* flags from both inputs */
62381       i64 iA;         /* Integer value of left operand */
62382       i64 iB;         /* Integer value of right operand */
62383       double rA;      /* Real value of left operand */
62384       double rB;      /* Real value of right operand */
62385     } af;
62386     struct OP_Function_stack_vars {
62387       int i;
62388       Mem *pArg;
62389       sqlite3_context ctx;
62390       sqlite3_value **apVal;
62391       int n;
62392     } ag;
62393     struct OP_ShiftRight_stack_vars {
62394       i64 iA;
62395       u64 uA;
62396       i64 iB;
62397       u8 op;
62398     } ah;
62399     struct OP_Ge_stack_vars {
62400       int res;            /* Result of the comparison of pIn1 against pIn3 */
62401       char affinity;      /* Affinity to use for comparison */
62402       u16 flags1;         /* Copy of initial value of pIn1->flags */
62403       u16 flags3;         /* Copy of initial value of pIn3->flags */
62404     } ai;
62405     struct OP_Compare_stack_vars {
62406       int n;
62407       int i;
62408       int p1;
62409       int p2;
62410       const KeyInfo *pKeyInfo;
62411       int idx;
62412       CollSeq *pColl;    /* Collating sequence to use on this term */
62413       int bRev;          /* True for DESCENDING sort order */
62414     } aj;
62415     struct OP_Or_stack_vars {
62416       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62417       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62418     } ak;
62419     struct OP_IfNot_stack_vars {
62420       int c;
62421     } al;
62422     struct OP_Column_stack_vars {
62423       u32 payloadSize;   /* Number of bytes in the record */
62424       i64 payloadSize64; /* Number of bytes in the record */
62425       int p1;            /* P1 value of the opcode */
62426       int p2;            /* column number to retrieve */
62427       VdbeCursor *pC;    /* The VDBE cursor */
62428       char *zRec;        /* Pointer to complete record-data */
62429       BtCursor *pCrsr;   /* The BTree cursor */
62430       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62431       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62432       int nField;        /* number of fields in the record */
62433       int len;           /* The length of the serialized data for the column */
62434       int i;             /* Loop counter */
62435       char *zData;       /* Part of the record being decoded */
62436       Mem *pDest;        /* Where to write the extracted value */
62437       Mem sMem;          /* For storing the record being decoded */
62438       u8 *zIdx;          /* Index into header */
62439       u8 *zEndHdr;       /* Pointer to first byte after the header */
62440       u32 offset;        /* Offset into the data */
62441       u32 szField;       /* Number of bytes in the content of a field */
62442       int szHdr;         /* Size of the header size field at start of record */
62443       int avail;         /* Number of bytes of available data */
62444       Mem *pReg;         /* PseudoTable input register */
62445     } am;
62446     struct OP_Affinity_stack_vars {
62447       const char *zAffinity;   /* The affinity to be applied */
62448       char cAff;               /* A single character of affinity */
62449     } an;
62450     struct OP_MakeRecord_stack_vars {
62451       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
62452       Mem *pRec;             /* The new record */
62453       u64 nData;             /* Number of bytes of data space */
62454       int nHdr;              /* Number of bytes of header space */
62455       i64 nByte;             /* Data space required for this record */
62456       int nZero;             /* Number of zero bytes at the end of the record */
62457       int nVarint;           /* Number of bytes in a varint */
62458       u32 serial_type;       /* Type field */
62459       Mem *pData0;           /* First field to be combined into the record */
62460       Mem *pLast;            /* Last field of the record */
62461       int nField;            /* Number of fields in the record */
62462       char *zAffinity;       /* The affinity string for the record */
62463       int file_format;       /* File format to use for encoding */
62464       int i;                 /* Space used in zNewRecord[] */
62465       int len;               /* Length of a field */
62466     } ao;
62467     struct OP_Count_stack_vars {
62468       i64 nEntry;
62469       BtCursor *pCrsr;
62470     } ap;
62471     struct OP_Savepoint_stack_vars {
62472       int p1;                         /* Value of P1 operand */
62473       char *zName;                    /* Name of savepoint */
62474       int nName;
62475       Savepoint *pNew;
62476       Savepoint *pSavepoint;
62477       Savepoint *pTmp;
62478       int iSavepoint;
62479       int ii;
62480     } aq;
62481     struct OP_AutoCommit_stack_vars {
62482       int desiredAutoCommit;
62483       int iRollback;
62484       int turnOnAC;
62485     } ar;
62486     struct OP_Transaction_stack_vars {
62487       Btree *pBt;
62488     } as;
62489     struct OP_ReadCookie_stack_vars {
62490       int iMeta;
62491       int iDb;
62492       int iCookie;
62493     } at;
62494     struct OP_SetCookie_stack_vars {
62495       Db *pDb;
62496     } au;
62497     struct OP_VerifyCookie_stack_vars {
62498       int iMeta;
62499       int iGen;
62500       Btree *pBt;
62501     } av;
62502     struct OP_OpenWrite_stack_vars {
62503       int nField;
62504       KeyInfo *pKeyInfo;
62505       int p2;
62506       int iDb;
62507       int wrFlag;
62508       Btree *pX;
62509       VdbeCursor *pCur;
62510       Db *pDb;
62511     } aw;
62512     struct OP_OpenEphemeral_stack_vars {
62513       VdbeCursor *pCx;
62514     } ax;
62515     struct OP_OpenPseudo_stack_vars {
62516       VdbeCursor *pCx;
62517     } ay;
62518     struct OP_SeekGt_stack_vars {
62519       int res;
62520       int oc;
62521       VdbeCursor *pC;
62522       UnpackedRecord r;
62523       int nField;
62524       i64 iKey;      /* The rowid we are to seek to */
62525     } az;
62526     struct OP_Seek_stack_vars {
62527       VdbeCursor *pC;
62528     } ba;
62529     struct OP_Found_stack_vars {
62530       int alreadyExists;
62531       VdbeCursor *pC;
62532       int res;
62533       UnpackedRecord *pIdxKey;
62534       UnpackedRecord r;
62535       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62536     } bb;
62537     struct OP_IsUnique_stack_vars {
62538       u16 ii;
62539       VdbeCursor *pCx;
62540       BtCursor *pCrsr;
62541       u16 nField;
62542       Mem *aMx;
62543       UnpackedRecord r;                  /* B-Tree index search key */
62544       i64 R;                             /* Rowid stored in register P3 */
62545     } bc;
62546     struct OP_NotExists_stack_vars {
62547       VdbeCursor *pC;
62548       BtCursor *pCrsr;
62549       int res;
62550       u64 iKey;
62551     } bd;
62552     struct OP_NewRowid_stack_vars {
62553       i64 v;                 /* The new rowid */
62554       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
62555       int res;               /* Result of an sqlite3BtreeLast() */
62556       int cnt;               /* Counter to limit the number of searches */
62557       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
62558       VdbeFrame *pFrame;     /* Root frame of VDBE */
62559     } be;
62560     struct OP_InsertInt_stack_vars {
62561       Mem *pData;       /* MEM cell holding data for the record to be inserted */
62562       Mem *pKey;        /* MEM cell holding key  for the record */
62563       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62564       VdbeCursor *pC;   /* Cursor to table into which insert is written */
62565       int nZero;        /* Number of zero-bytes to append */
62566       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62567       const char *zDb;  /* database name - used by the update hook */
62568       const char *zTbl; /* Table name - used by the opdate hook */
62569       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62570     } bf;
62571     struct OP_Delete_stack_vars {
62572       i64 iKey;
62573       VdbeCursor *pC;
62574     } bg;
62575     struct OP_RowData_stack_vars {
62576       VdbeCursor *pC;
62577       BtCursor *pCrsr;
62578       u32 n;
62579       i64 n64;
62580     } bh;
62581     struct OP_Rowid_stack_vars {
62582       VdbeCursor *pC;
62583       i64 v;
62584       sqlite3_vtab *pVtab;
62585       const sqlite3_module *pModule;
62586     } bi;
62587     struct OP_NullRow_stack_vars {
62588       VdbeCursor *pC;
62589     } bj;
62590     struct OP_Last_stack_vars {
62591       VdbeCursor *pC;
62592       BtCursor *pCrsr;
62593       int res;
62594     } bk;
62595     struct OP_Rewind_stack_vars {
62596       VdbeCursor *pC;
62597       BtCursor *pCrsr;
62598       int res;
62599     } bl;
62600     struct OP_Next_stack_vars {
62601       VdbeCursor *pC;
62602       BtCursor *pCrsr;
62603       int res;
62604     } bm;
62605     struct OP_IdxInsert_stack_vars {
62606       VdbeCursor *pC;
62607       BtCursor *pCrsr;
62608       int nKey;
62609       const char *zKey;
62610     } bn;
62611     struct OP_IdxDelete_stack_vars {
62612       VdbeCursor *pC;
62613       BtCursor *pCrsr;
62614       int res;
62615       UnpackedRecord r;
62616     } bo;
62617     struct OP_IdxRowid_stack_vars {
62618       BtCursor *pCrsr;
62619       VdbeCursor *pC;
62620       i64 rowid;
62621     } bp;
62622     struct OP_IdxGE_stack_vars {
62623       VdbeCursor *pC;
62624       int res;
62625       UnpackedRecord r;
62626     } bq;
62627     struct OP_Destroy_stack_vars {
62628       int iMoved;
62629       int iCnt;
62630       Vdbe *pVdbe;
62631       int iDb;
62632     } br;
62633     struct OP_Clear_stack_vars {
62634       int nChange;
62635     } bs;
62636     struct OP_CreateTable_stack_vars {
62637       int pgno;
62638       int flags;
62639       Db *pDb;
62640     } bt;
62641     struct OP_ParseSchema_stack_vars {
62642       int iDb;
62643       const char *zMaster;
62644       char *zSql;
62645       InitData initData;
62646     } bu;
62647     struct OP_IntegrityCk_stack_vars {
62648       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
62649       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
62650       int j;          /* Loop counter */
62651       int nErr;       /* Number of errors reported */
62652       char *z;        /* Text of the error report */
62653       Mem *pnErr;     /* Register keeping track of errors remaining */
62654     } bv;
62655     struct OP_RowSetRead_stack_vars {
62656       i64 val;
62657     } bw;
62658     struct OP_RowSetTest_stack_vars {
62659       int iSet;
62660       int exists;
62661     } bx;
62662     struct OP_Program_stack_vars {
62663       int nMem;               /* Number of memory registers for sub-program */
62664       int nByte;              /* Bytes of runtime space required for sub-program */
62665       Mem *pRt;               /* Register to allocate runtime space */
62666       Mem *pMem;              /* Used to iterate through memory cells */
62667       Mem *pEnd;              /* Last memory cell in new array */
62668       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
62669       SubProgram *pProgram;   /* Sub-program to execute */
62670       void *t;                /* Token identifying trigger */
62671     } by;
62672     struct OP_Param_stack_vars {
62673       VdbeFrame *pFrame;
62674       Mem *pIn;
62675     } bz;
62676     struct OP_MemMax_stack_vars {
62677       Mem *pIn1;
62678       VdbeFrame *pFrame;
62679     } ca;
62680     struct OP_AggStep_stack_vars {
62681       int n;
62682       int i;
62683       Mem *pMem;
62684       Mem *pRec;
62685       sqlite3_context ctx;
62686       sqlite3_value **apVal;
62687     } cb;
62688     struct OP_AggFinal_stack_vars {
62689       Mem *pMem;
62690     } cc;
62691     struct OP_Checkpoint_stack_vars {
62692       int i;                          /* Loop counter */
62693       int aRes[3];                    /* Results */
62694       Mem *pMem;                      /* Write results here */
62695     } cd;
62696     struct OP_JournalMode_stack_vars {
62697       Btree *pBt;                     /* Btree to change journal mode of */
62698       Pager *pPager;                  /* Pager associated with pBt */
62699       int eNew;                       /* New journal mode */
62700       int eOld;                       /* The old journal mode */
62701       const char *zFilename;          /* Name of database file for pPager */
62702     } ce;
62703     struct OP_IncrVacuum_stack_vars {
62704       Btree *pBt;
62705     } cf;
62706     struct OP_VBegin_stack_vars {
62707       VTable *pVTab;
62708     } cg;
62709     struct OP_VOpen_stack_vars {
62710       VdbeCursor *pCur;
62711       sqlite3_vtab_cursor *pVtabCursor;
62712       sqlite3_vtab *pVtab;
62713       sqlite3_module *pModule;
62714     } ch;
62715     struct OP_VFilter_stack_vars {
62716       int nArg;
62717       int iQuery;
62718       const sqlite3_module *pModule;
62719       Mem *pQuery;
62720       Mem *pArgc;
62721       sqlite3_vtab_cursor *pVtabCursor;
62722       sqlite3_vtab *pVtab;
62723       VdbeCursor *pCur;
62724       int res;
62725       int i;
62726       Mem **apArg;
62727     } ci;
62728     struct OP_VColumn_stack_vars {
62729       sqlite3_vtab *pVtab;
62730       const sqlite3_module *pModule;
62731       Mem *pDest;
62732       sqlite3_context sContext;
62733     } cj;
62734     struct OP_VNext_stack_vars {
62735       sqlite3_vtab *pVtab;
62736       const sqlite3_module *pModule;
62737       int res;
62738       VdbeCursor *pCur;
62739     } ck;
62740     struct OP_VRename_stack_vars {
62741       sqlite3_vtab *pVtab;
62742       Mem *pName;
62743     } cl;
62744     struct OP_VUpdate_stack_vars {
62745       sqlite3_vtab *pVtab;
62746       sqlite3_module *pModule;
62747       int nArg;
62748       int i;
62749       sqlite_int64 rowid;
62750       Mem **apArg;
62751       Mem *pX;
62752     } cm;
62753     struct OP_Trace_stack_vars {
62754       char *zTrace;
62755     } cn;
62756   } u;
62757   /* End automatically generated code
62758   ********************************************************************/
62759
62760   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
62761   sqlite3VdbeEnter(p);
62762   if( p->rc==SQLITE_NOMEM ){
62763     /* This happens if a malloc() inside a call to sqlite3_column_text() or
62764     ** sqlite3_column_text16() failed.  */
62765     goto no_mem;
62766   }
62767   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
62768   p->rc = SQLITE_OK;
62769   assert( p->explain==0 );
62770   p->pResultSet = 0;
62771   db->busyHandler.nBusy = 0;
62772   CHECK_FOR_INTERRUPT;
62773   sqlite3VdbeIOTraceSql(p);
62774 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62775   checkProgress = db->xProgress!=0;
62776 #endif
62777 #ifdef SQLITE_DEBUG
62778   sqlite3BeginBenignMalloc();
62779   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
62780     int i;
62781     printf("VDBE Program Listing:\n");
62782     sqlite3VdbePrintSql(p);
62783     for(i=0; i<p->nOp; i++){
62784       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
62785     }
62786   }
62787   sqlite3EndBenignMalloc();
62788 #endif
62789   for(pc=p->pc; rc==SQLITE_OK; pc++){
62790     assert( pc>=0 && pc<p->nOp );
62791     if( db->mallocFailed ) goto no_mem;
62792 #ifdef VDBE_PROFILE
62793     origPc = pc;
62794     start = sqlite3Hwtime();
62795 #endif
62796     pOp = &aOp[pc];
62797
62798     /* Only allow tracing if SQLITE_DEBUG is defined.
62799     */
62800 #ifdef SQLITE_DEBUG
62801     if( p->trace ){
62802       if( pc==0 ){
62803         printf("VDBE Execution Trace:\n");
62804         sqlite3VdbePrintSql(p);
62805       }
62806       sqlite3VdbePrintOp(p->trace, pc, pOp);
62807     }
62808 #endif
62809       
62810
62811     /* Check to see if we need to simulate an interrupt.  This only happens
62812     ** if we have a special test build.
62813     */
62814 #ifdef SQLITE_TEST
62815     if( sqlite3_interrupt_count>0 ){
62816       sqlite3_interrupt_count--;
62817       if( sqlite3_interrupt_count==0 ){
62818         sqlite3_interrupt(db);
62819       }
62820     }
62821 #endif
62822
62823 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62824     /* Call the progress callback if it is configured and the required number
62825     ** of VDBE ops have been executed (either since this invocation of
62826     ** sqlite3VdbeExec() or since last time the progress callback was called).
62827     ** If the progress callback returns non-zero, exit the virtual machine with
62828     ** a return code SQLITE_ABORT.
62829     */
62830     if( checkProgress ){
62831       if( db->nProgressOps==nProgressOps ){
62832         int prc;
62833         prc = db->xProgress(db->pProgressArg);
62834         if( prc!=0 ){
62835           rc = SQLITE_INTERRUPT;
62836           goto vdbe_error_halt;
62837         }
62838         nProgressOps = 0;
62839       }
62840       nProgressOps++;
62841     }
62842 #endif
62843
62844     /* On any opcode with the "out2-prerelase" tag, free any
62845     ** external allocations out of mem[p2] and set mem[p2] to be
62846     ** an undefined integer.  Opcodes will either fill in the integer
62847     ** value or convert mem[p2] to a different type.
62848     */
62849     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
62850     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
62851       assert( pOp->p2>0 );
62852       assert( pOp->p2<=p->nMem );
62853       pOut = &aMem[pOp->p2];
62854       memAboutToChange(p, pOut);
62855       sqlite3VdbeMemReleaseExternal(pOut);
62856       pOut->flags = MEM_Int;
62857     }
62858
62859     /* Sanity checking on other operands */
62860 #ifdef SQLITE_DEBUG
62861     if( (pOp->opflags & OPFLG_IN1)!=0 ){
62862       assert( pOp->p1>0 );
62863       assert( pOp->p1<=p->nMem );
62864       assert( memIsValid(&aMem[pOp->p1]) );
62865       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
62866     }
62867     if( (pOp->opflags & OPFLG_IN2)!=0 ){
62868       assert( pOp->p2>0 );
62869       assert( pOp->p2<=p->nMem );
62870       assert( memIsValid(&aMem[pOp->p2]) );
62871       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
62872     }
62873     if( (pOp->opflags & OPFLG_IN3)!=0 ){
62874       assert( pOp->p3>0 );
62875       assert( pOp->p3<=p->nMem );
62876       assert( memIsValid(&aMem[pOp->p3]) );
62877       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
62878     }
62879     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
62880       assert( pOp->p2>0 );
62881       assert( pOp->p2<=p->nMem );
62882       memAboutToChange(p, &aMem[pOp->p2]);
62883     }
62884     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
62885       assert( pOp->p3>0 );
62886       assert( pOp->p3<=p->nMem );
62887       memAboutToChange(p, &aMem[pOp->p3]);
62888     }
62889 #endif
62890   
62891     switch( pOp->opcode ){
62892
62893 /*****************************************************************************
62894 ** What follows is a massive switch statement where each case implements a
62895 ** separate instruction in the virtual machine.  If we follow the usual
62896 ** indentation conventions, each case should be indented by 6 spaces.  But
62897 ** that is a lot of wasted space on the left margin.  So the code within
62898 ** the switch statement will break with convention and be flush-left. Another
62899 ** big comment (similar to this one) will mark the point in the code where
62900 ** we transition back to normal indentation.
62901 **
62902 ** The formatting of each case is important.  The makefile for SQLite
62903 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
62904 ** file looking for lines that begin with "case OP_".  The opcodes.h files
62905 ** will be filled with #defines that give unique integer values to each
62906 ** opcode and the opcodes.c file is filled with an array of strings where
62907 ** each string is the symbolic name for the corresponding opcode.  If the
62908 ** case statement is followed by a comment of the form "/# same as ... #/"
62909 ** that comment is used to determine the particular value of the opcode.
62910 **
62911 ** Other keywords in the comment that follows each case are used to
62912 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
62913 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
62914 ** the mkopcodeh.awk script for additional information.
62915 **
62916 ** Documentation about VDBE opcodes is generated by scanning this file
62917 ** for lines of that contain "Opcode:".  That line and all subsequent
62918 ** comment lines are used in the generation of the opcode.html documentation
62919 ** file.
62920 **
62921 ** SUMMARY:
62922 **
62923 **     Formatting is important to scripts that scan this file.
62924 **     Do not deviate from the formatting style currently in use.
62925 **
62926 *****************************************************************************/
62927
62928 /* Opcode:  Goto * P2 * * *
62929 **
62930 ** An unconditional jump to address P2.
62931 ** The next instruction executed will be 
62932 ** the one at index P2 from the beginning of
62933 ** the program.
62934 */
62935 case OP_Goto: {             /* jump */
62936   CHECK_FOR_INTERRUPT;
62937   pc = pOp->p2 - 1;
62938   break;
62939 }
62940
62941 /* Opcode:  Gosub P1 P2 * * *
62942 **
62943 ** Write the current address onto register P1
62944 ** and then jump to address P2.
62945 */
62946 case OP_Gosub: {            /* jump, in1 */
62947   pIn1 = &aMem[pOp->p1];
62948   assert( (pIn1->flags & MEM_Dyn)==0 );
62949   memAboutToChange(p, pIn1);
62950   pIn1->flags = MEM_Int;
62951   pIn1->u.i = pc;
62952   REGISTER_TRACE(pOp->p1, pIn1);
62953   pc = pOp->p2 - 1;
62954   break;
62955 }
62956
62957 /* Opcode:  Return P1 * * * *
62958 **
62959 ** Jump to the next instruction after the address in register P1.
62960 */
62961 case OP_Return: {           /* in1 */
62962   pIn1 = &aMem[pOp->p1];
62963   assert( pIn1->flags & MEM_Int );
62964   pc = (int)pIn1->u.i;
62965   break;
62966 }
62967
62968 /* Opcode:  Yield P1 * * * *
62969 **
62970 ** Swap the program counter with the value in register P1.
62971 */
62972 case OP_Yield: {            /* in1 */
62973 #if 0  /* local variables moved into u.aa */
62974   int pcDest;
62975 #endif /* local variables moved into u.aa */
62976   pIn1 = &aMem[pOp->p1];
62977   assert( (pIn1->flags & MEM_Dyn)==0 );
62978   pIn1->flags = MEM_Int;
62979   u.aa.pcDest = (int)pIn1->u.i;
62980   pIn1->u.i = pc;
62981   REGISTER_TRACE(pOp->p1, pIn1);
62982   pc = u.aa.pcDest;
62983   break;
62984 }
62985
62986 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
62987 **
62988 ** Check the value in register P3.  If is is NULL then Halt using
62989 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
62990 ** value in register P3 is not NULL, then this routine is a no-op.
62991 */
62992 case OP_HaltIfNull: {      /* in3 */
62993   pIn3 = &aMem[pOp->p3];
62994   if( (pIn3->flags & MEM_Null)==0 ) break;
62995   /* Fall through into OP_Halt */
62996 }
62997
62998 /* Opcode:  Halt P1 P2 * P4 *
62999 **
63000 ** Exit immediately.  All open cursors, etc are closed
63001 ** automatically.
63002 **
63003 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
63004 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
63005 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
63006 ** whether or not to rollback the current transaction.  Do not rollback
63007 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
63008 ** then back out all changes that have occurred during this execution of the
63009 ** VDBE, but do not rollback the transaction. 
63010 **
63011 ** If P4 is not null then it is an error message string.
63012 **
63013 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63014 ** every program.  So a jump past the last instruction of the program
63015 ** is the same as executing Halt.
63016 */
63017 case OP_Halt: {
63018   if( pOp->p1==SQLITE_OK && p->pFrame ){
63019     /* Halt the sub-program. Return control to the parent frame. */
63020     VdbeFrame *pFrame = p->pFrame;
63021     p->pFrame = pFrame->pParent;
63022     p->nFrame--;
63023     sqlite3VdbeSetChanges(db, p->nChange);
63024     pc = sqlite3VdbeFrameRestore(pFrame);
63025     if( pOp->p2==OE_Ignore ){
63026       /* Instruction pc is the OP_Program that invoked the sub-program 
63027       ** currently being halted. If the p2 instruction of this OP_Halt
63028       ** instruction is set to OE_Ignore, then the sub-program is throwing
63029       ** an IGNORE exception. In this case jump to the address specified
63030       ** as the p2 of the calling OP_Program.  */
63031       pc = p->aOp[pc].p2-1;
63032     }
63033     aOp = p->aOp;
63034     aMem = p->aMem;
63035     break;
63036   }
63037
63038   p->rc = pOp->p1;
63039   p->errorAction = (u8)pOp->p2;
63040   p->pc = pc;
63041   if( pOp->p4.z ){
63042     assert( p->rc!=SQLITE_OK );
63043     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63044     testcase( sqlite3GlobalConfig.xLog!=0 );
63045     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63046   }else if( p->rc ){
63047     testcase( sqlite3GlobalConfig.xLog!=0 );
63048     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63049   }
63050   rc = sqlite3VdbeHalt(p);
63051   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63052   if( rc==SQLITE_BUSY ){
63053     p->rc = rc = SQLITE_BUSY;
63054   }else{
63055     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63056     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63057     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63058   }
63059   goto vdbe_return;
63060 }
63061
63062 /* Opcode: Integer P1 P2 * * *
63063 **
63064 ** The 32-bit integer value P1 is written into register P2.
63065 */
63066 case OP_Integer: {         /* out2-prerelease */
63067   pOut->u.i = pOp->p1;
63068   break;
63069 }
63070
63071 /* Opcode: Int64 * P2 * P4 *
63072 **
63073 ** P4 is a pointer to a 64-bit integer value.
63074 ** Write that value into register P2.
63075 */
63076 case OP_Int64: {           /* out2-prerelease */
63077   assert( pOp->p4.pI64!=0 );
63078   pOut->u.i = *pOp->p4.pI64;
63079   break;
63080 }
63081
63082 #ifndef SQLITE_OMIT_FLOATING_POINT
63083 /* Opcode: Real * P2 * P4 *
63084 **
63085 ** P4 is a pointer to a 64-bit floating point value.
63086 ** Write that value into register P2.
63087 */
63088 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
63089   pOut->flags = MEM_Real;
63090   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63091   pOut->r = *pOp->p4.pReal;
63092   break;
63093 }
63094 #endif
63095
63096 /* Opcode: String8 * P2 * P4 *
63097 **
63098 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
63099 ** into an OP_String before it is executed for the first time.
63100 */
63101 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
63102   assert( pOp->p4.z!=0 );
63103   pOp->opcode = OP_String;
63104   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63105
63106 #ifndef SQLITE_OMIT_UTF16
63107   if( encoding!=SQLITE_UTF8 ){
63108     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63109     if( rc==SQLITE_TOOBIG ) goto too_big;
63110     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63111     assert( pOut->zMalloc==pOut->z );
63112     assert( pOut->flags & MEM_Dyn );
63113     pOut->zMalloc = 0;
63114     pOut->flags |= MEM_Static;
63115     pOut->flags &= ~MEM_Dyn;
63116     if( pOp->p4type==P4_DYNAMIC ){
63117       sqlite3DbFree(db, pOp->p4.z);
63118     }
63119     pOp->p4type = P4_DYNAMIC;
63120     pOp->p4.z = pOut->z;
63121     pOp->p1 = pOut->n;
63122   }
63123 #endif
63124   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63125     goto too_big;
63126   }
63127   /* Fall through to the next case, OP_String */
63128 }
63129   
63130 /* Opcode: String P1 P2 * P4 *
63131 **
63132 ** The string value P4 of length P1 (bytes) is stored in register P2.
63133 */
63134 case OP_String: {          /* out2-prerelease */
63135   assert( pOp->p4.z!=0 );
63136   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63137   pOut->z = pOp->p4.z;
63138   pOut->n = pOp->p1;
63139   pOut->enc = encoding;
63140   UPDATE_MAX_BLOBSIZE(pOut);
63141   break;
63142 }
63143
63144 /* Opcode: Null * P2 * * *
63145 **
63146 ** Write a NULL into register P2.
63147 */
63148 case OP_Null: {           /* out2-prerelease */
63149   pOut->flags = MEM_Null;
63150   break;
63151 }
63152
63153
63154 /* Opcode: Blob P1 P2 * P4
63155 **
63156 ** P4 points to a blob of data P1 bytes long.  Store this
63157 ** blob in register P2.
63158 */
63159 case OP_Blob: {                /* out2-prerelease */
63160   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63161   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63162   pOut->enc = encoding;
63163   UPDATE_MAX_BLOBSIZE(pOut);
63164   break;
63165 }
63166
63167 /* Opcode: Variable P1 P2 * P4 *
63168 **
63169 ** Transfer the values of bound parameter P1 into register P2
63170 **
63171 ** If the parameter is named, then its name appears in P4 and P3==1.
63172 ** The P4 value is used by sqlite3_bind_parameter_name().
63173 */
63174 case OP_Variable: {            /* out2-prerelease */
63175 #if 0  /* local variables moved into u.ab */
63176   Mem *pVar;       /* Value being transferred */
63177 #endif /* local variables moved into u.ab */
63178
63179   assert( pOp->p1>0 && pOp->p1<=p->nVar );
63180   u.ab.pVar = &p->aVar[pOp->p1 - 1];
63181   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63182     goto too_big;
63183   }
63184   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63185   UPDATE_MAX_BLOBSIZE(pOut);
63186   break;
63187 }
63188
63189 /* Opcode: Move P1 P2 P3 * *
63190 **
63191 ** Move the values in register P1..P1+P3-1 over into
63192 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
63193 ** left holding a NULL.  It is an error for register ranges
63194 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63195 */
63196 case OP_Move: {
63197 #if 0  /* local variables moved into u.ac */
63198   char *zMalloc;   /* Holding variable for allocated memory */
63199   int n;           /* Number of registers left to copy */
63200   int p1;          /* Register to copy from */
63201   int p2;          /* Register to copy to */
63202 #endif /* local variables moved into u.ac */
63203
63204   u.ac.n = pOp->p3;
63205   u.ac.p1 = pOp->p1;
63206   u.ac.p2 = pOp->p2;
63207   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63208   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63209
63210   pIn1 = &aMem[u.ac.p1];
63211   pOut = &aMem[u.ac.p2];
63212   while( u.ac.n-- ){
63213     assert( pOut<=&aMem[p->nMem] );
63214     assert( pIn1<=&aMem[p->nMem] );
63215     assert( memIsValid(pIn1) );
63216     memAboutToChange(p, pOut);
63217     u.ac.zMalloc = pOut->zMalloc;
63218     pOut->zMalloc = 0;
63219     sqlite3VdbeMemMove(pOut, pIn1);
63220     pIn1->zMalloc = u.ac.zMalloc;
63221     REGISTER_TRACE(u.ac.p2++, pOut);
63222     pIn1++;
63223     pOut++;
63224   }
63225   break;
63226 }
63227
63228 /* Opcode: Copy P1 P2 * * *
63229 **
63230 ** Make a copy of register P1 into register P2.
63231 **
63232 ** This instruction makes a deep copy of the value.  A duplicate
63233 ** is made of any string or blob constant.  See also OP_SCopy.
63234 */
63235 case OP_Copy: {             /* in1, out2 */
63236   pIn1 = &aMem[pOp->p1];
63237   pOut = &aMem[pOp->p2];
63238   assert( pOut!=pIn1 );
63239   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63240   Deephemeralize(pOut);
63241   REGISTER_TRACE(pOp->p2, pOut);
63242   break;
63243 }
63244
63245 /* Opcode: SCopy P1 P2 * * *
63246 **
63247 ** Make a shallow copy of register P1 into register P2.
63248 **
63249 ** This instruction makes a shallow copy of the value.  If the value
63250 ** is a string or blob, then the copy is only a pointer to the
63251 ** original and hence if the original changes so will the copy.
63252 ** Worse, if the original is deallocated, the copy becomes invalid.
63253 ** Thus the program must guarantee that the original will not change
63254 ** during the lifetime of the copy.  Use OP_Copy to make a complete
63255 ** copy.
63256 */
63257 case OP_SCopy: {            /* in1, out2 */
63258   pIn1 = &aMem[pOp->p1];
63259   pOut = &aMem[pOp->p2];
63260   assert( pOut!=pIn1 );
63261   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63262 #ifdef SQLITE_DEBUG
63263   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63264 #endif
63265   REGISTER_TRACE(pOp->p2, pOut);
63266   break;
63267 }
63268
63269 /* Opcode: ResultRow P1 P2 * * *
63270 **
63271 ** The registers P1 through P1+P2-1 contain a single row of
63272 ** results. This opcode causes the sqlite3_step() call to terminate
63273 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63274 ** structure to provide access to the top P1 values as the result
63275 ** row.
63276 */
63277 case OP_ResultRow: {
63278 #if 0  /* local variables moved into u.ad */
63279   Mem *pMem;
63280   int i;
63281 #endif /* local variables moved into u.ad */
63282   assert( p->nResColumn==pOp->p2 );
63283   assert( pOp->p1>0 );
63284   assert( pOp->p1+pOp->p2<=p->nMem+1 );
63285
63286   /* If this statement has violated immediate foreign key constraints, do
63287   ** not return the number of rows modified. And do not RELEASE the statement
63288   ** transaction. It needs to be rolled back.  */
63289   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63290     assert( db->flags&SQLITE_CountRows );
63291     assert( p->usesStmtJournal );
63292     break;
63293   }
63294
63295   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63296   ** DML statements invoke this opcode to return the number of rows
63297   ** modified to the user. This is the only way that a VM that
63298   ** opens a statement transaction may invoke this opcode.
63299   **
63300   ** In case this is such a statement, close any statement transaction
63301   ** opened by this VM before returning control to the user. This is to
63302   ** ensure that statement-transactions are always nested, not overlapping.
63303   ** If the open statement-transaction is not closed here, then the user
63304   ** may step another VM that opens its own statement transaction. This
63305   ** may lead to overlapping statement transactions.
63306   **
63307   ** The statement transaction is never a top-level transaction.  Hence
63308   ** the RELEASE call below can never fail.
63309   */
63310   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63311   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63312   if( NEVER(rc!=SQLITE_OK) ){
63313     break;
63314   }
63315
63316   /* Invalidate all ephemeral cursor row caches */
63317   p->cacheCtr = (p->cacheCtr + 2)|1;
63318
63319   /* Make sure the results of the current row are \000 terminated
63320   ** and have an assigned type.  The results are de-ephemeralized as
63321   ** as side effect.
63322   */
63323   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63324   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63325     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63326     Deephemeralize(&u.ad.pMem[u.ad.i]);
63327     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63328             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63329     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63330     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63331     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63332   }
63333   if( db->mallocFailed ) goto no_mem;
63334
63335   /* Return SQLITE_ROW
63336   */
63337   p->pc = pc + 1;
63338   rc = SQLITE_ROW;
63339   goto vdbe_return;
63340 }
63341
63342 /* Opcode: Concat P1 P2 P3 * *
63343 **
63344 ** Add the text in register P1 onto the end of the text in
63345 ** register P2 and store the result in register P3.
63346 ** If either the P1 or P2 text are NULL then store NULL in P3.
63347 **
63348 **   P3 = P2 || P1
63349 **
63350 ** It is illegal for P1 and P3 to be the same register. Sometimes,
63351 ** if P3 is the same register as P2, the implementation is able
63352 ** to avoid a memcpy().
63353 */
63354 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
63355 #if 0  /* local variables moved into u.ae */
63356   i64 nByte;
63357 #endif /* local variables moved into u.ae */
63358
63359   pIn1 = &aMem[pOp->p1];
63360   pIn2 = &aMem[pOp->p2];
63361   pOut = &aMem[pOp->p3];
63362   assert( pIn1!=pOut );
63363   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63364     sqlite3VdbeMemSetNull(pOut);
63365     break;
63366   }
63367   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63368   Stringify(pIn1, encoding);
63369   Stringify(pIn2, encoding);
63370   u.ae.nByte = pIn1->n + pIn2->n;
63371   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63372     goto too_big;
63373   }
63374   MemSetTypeFlag(pOut, MEM_Str);
63375   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63376     goto no_mem;
63377   }
63378   if( pOut!=pIn2 ){
63379     memcpy(pOut->z, pIn2->z, pIn2->n);
63380   }
63381   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63382   pOut->z[u.ae.nByte] = 0;
63383   pOut->z[u.ae.nByte+1] = 0;
63384   pOut->flags |= MEM_Term;
63385   pOut->n = (int)u.ae.nByte;
63386   pOut->enc = encoding;
63387   UPDATE_MAX_BLOBSIZE(pOut);
63388   break;
63389 }
63390
63391 /* Opcode: Add P1 P2 P3 * *
63392 **
63393 ** Add the value in register P1 to the value in register P2
63394 ** and store the result in register P3.
63395 ** If either input is NULL, the result is NULL.
63396 */
63397 /* Opcode: Multiply P1 P2 P3 * *
63398 **
63399 **
63400 ** Multiply the value in register P1 by the value in register P2
63401 ** and store the result in register P3.
63402 ** If either input is NULL, the result is NULL.
63403 */
63404 /* Opcode: Subtract P1 P2 P3 * *
63405 **
63406 ** Subtract the value in register P1 from the value in register P2
63407 ** and store the result in register P3.
63408 ** If either input is NULL, the result is NULL.
63409 */
63410 /* Opcode: Divide P1 P2 P3 * *
63411 **
63412 ** Divide the value in register P1 by the value in register P2
63413 ** and store the result in register P3 (P3=P2/P1). If the value in 
63414 ** register P1 is zero, then the result is NULL. If either input is 
63415 ** NULL, the result is NULL.
63416 */
63417 /* Opcode: Remainder P1 P2 P3 * *
63418 **
63419 ** Compute the remainder after integer division of the value in
63420 ** register P1 by the value in register P2 and store the result in P3. 
63421 ** If the value in register P2 is zero the result is NULL.
63422 ** If either operand is NULL, the result is NULL.
63423 */
63424 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
63425 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
63426 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
63427 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
63428 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
63429 #if 0  /* local variables moved into u.af */
63430   int flags;      /* Combined MEM_* flags from both inputs */
63431   i64 iA;         /* Integer value of left operand */
63432   i64 iB;         /* Integer value of right operand */
63433   double rA;      /* Real value of left operand */
63434   double rB;      /* Real value of right operand */
63435 #endif /* local variables moved into u.af */
63436
63437   pIn1 = &aMem[pOp->p1];
63438   applyNumericAffinity(pIn1);
63439   pIn2 = &aMem[pOp->p2];
63440   applyNumericAffinity(pIn2);
63441   pOut = &aMem[pOp->p3];
63442   u.af.flags = pIn1->flags | pIn2->flags;
63443   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
63444   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
63445     u.af.iA = pIn1->u.i;
63446     u.af.iB = pIn2->u.i;
63447     switch( pOp->opcode ){
63448       case OP_Add:       if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63449       case OP_Subtract:  if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63450       case OP_Multiply:  if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
63451       case OP_Divide: {
63452         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63453         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
63454         u.af.iB /= u.af.iA;
63455         break;
63456       }
63457       default: {
63458         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63459         if( u.af.iA==-1 ) u.af.iA = 1;
63460         u.af.iB %= u.af.iA;
63461         break;
63462       }
63463     }
63464     pOut->u.i = u.af.iB;
63465     MemSetTypeFlag(pOut, MEM_Int);
63466   }else{
63467 fp_math:
63468     u.af.rA = sqlite3VdbeRealValue(pIn1);
63469     u.af.rB = sqlite3VdbeRealValue(pIn2);
63470     switch( pOp->opcode ){
63471       case OP_Add:         u.af.rB += u.af.rA;       break;
63472       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
63473       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
63474       case OP_Divide: {
63475         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63476         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
63477         u.af.rB /= u.af.rA;
63478         break;
63479       }
63480       default: {
63481         u.af.iA = (i64)u.af.rA;
63482         u.af.iB = (i64)u.af.rB;
63483         if( u.af.iA==0 ) goto arithmetic_result_is_null;
63484         if( u.af.iA==-1 ) u.af.iA = 1;
63485         u.af.rB = (double)(u.af.iB % u.af.iA);
63486         break;
63487       }
63488     }
63489 #ifdef SQLITE_OMIT_FLOATING_POINT
63490     pOut->u.i = u.af.rB;
63491     MemSetTypeFlag(pOut, MEM_Int);
63492 #else
63493     if( sqlite3IsNaN(u.af.rB) ){
63494       goto arithmetic_result_is_null;
63495     }
63496     pOut->r = u.af.rB;
63497     MemSetTypeFlag(pOut, MEM_Real);
63498     if( (u.af.flags & MEM_Real)==0 ){
63499       sqlite3VdbeIntegerAffinity(pOut);
63500     }
63501 #endif
63502   }
63503   break;
63504
63505 arithmetic_result_is_null:
63506   sqlite3VdbeMemSetNull(pOut);
63507   break;
63508 }
63509
63510 /* Opcode: CollSeq * * P4
63511 **
63512 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
63513 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
63514 ** be returned. This is used by the built-in min(), max() and nullif()
63515 ** functions.
63516 **
63517 ** The interface used by the implementation of the aforementioned functions
63518 ** to retrieve the collation sequence set by this opcode is not available
63519 ** publicly, only to user functions defined in func.c.
63520 */
63521 case OP_CollSeq: {
63522   assert( pOp->p4type==P4_COLLSEQ );
63523   break;
63524 }
63525
63526 /* Opcode: Function P1 P2 P3 P4 P5
63527 **
63528 ** Invoke a user function (P4 is a pointer to a Function structure that
63529 ** defines the function) with P5 arguments taken from register P2 and
63530 ** successors.  The result of the function is stored in register P3.
63531 ** Register P3 must not be one of the function inputs.
63532 **
63533 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
63534 ** function was determined to be constant at compile time. If the first
63535 ** argument was constant then bit 0 of P1 is set. This is used to determine
63536 ** whether meta data associated with a user function argument using the
63537 ** sqlite3_set_auxdata() API may be safely retained until the next
63538 ** invocation of this opcode.
63539 **
63540 ** See also: AggStep and AggFinal
63541 */
63542 case OP_Function: {
63543 #if 0  /* local variables moved into u.ag */
63544   int i;
63545   Mem *pArg;
63546   sqlite3_context ctx;
63547   sqlite3_value **apVal;
63548   int n;
63549 #endif /* local variables moved into u.ag */
63550
63551   u.ag.n = pOp->p5;
63552   u.ag.apVal = p->apArg;
63553   assert( u.ag.apVal || u.ag.n==0 );
63554   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63555   pOut = &aMem[pOp->p3];
63556   memAboutToChange(p, pOut);
63557
63558   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
63559   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
63560   u.ag.pArg = &aMem[pOp->p2];
63561   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
63562     assert( memIsValid(u.ag.pArg) );
63563     u.ag.apVal[u.ag.i] = u.ag.pArg;
63564     Deephemeralize(u.ag.pArg);
63565     sqlite3VdbeMemStoreType(u.ag.pArg);
63566     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
63567   }
63568
63569   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
63570   if( pOp->p4type==P4_FUNCDEF ){
63571     u.ag.ctx.pFunc = pOp->p4.pFunc;
63572     u.ag.ctx.pVdbeFunc = 0;
63573   }else{
63574     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
63575     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
63576   }
63577
63578   u.ag.ctx.s.flags = MEM_Null;
63579   u.ag.ctx.s.db = db;
63580   u.ag.ctx.s.xDel = 0;
63581   u.ag.ctx.s.zMalloc = 0;
63582
63583   /* The output cell may already have a buffer allocated. Move
63584   ** the pointer to u.ag.ctx.s so in case the user-function can use
63585   ** the already allocated buffer instead of allocating a new one.
63586   */
63587   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
63588   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
63589
63590   u.ag.ctx.isError = 0;
63591   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63592     assert( pOp>aOp );
63593     assert( pOp[-1].p4type==P4_COLLSEQ );
63594     assert( pOp[-1].opcode==OP_CollSeq );
63595     u.ag.ctx.pColl = pOp[-1].p4.pColl;
63596   }
63597   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
63598   if( db->mallocFailed ){
63599     /* Even though a malloc() has failed, the implementation of the
63600     ** user function may have called an sqlite3_result_XXX() function
63601     ** to return a value. The following call releases any resources
63602     ** associated with such a value.
63603     */
63604     sqlite3VdbeMemRelease(&u.ag.ctx.s);
63605     goto no_mem;
63606   }
63607
63608   /* If any auxiliary data functions have been called by this user function,
63609   ** immediately call the destructor for any non-static values.
63610   */
63611   if( u.ag.ctx.pVdbeFunc ){
63612     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
63613     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
63614     pOp->p4type = P4_VDBEFUNC;
63615   }
63616
63617   /* If the function returned an error, throw an exception */
63618   if( u.ag.ctx.isError ){
63619     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
63620     rc = u.ag.ctx.isError;
63621   }
63622
63623   /* Copy the result of the function into register P3 */
63624   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
63625   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
63626   if( sqlite3VdbeMemTooBig(pOut) ){
63627     goto too_big;
63628   }
63629
63630 #if 0
63631   /* The app-defined function has done something that as caused this
63632   ** statement to expire.  (Perhaps the function called sqlite3_exec()
63633   ** with a CREATE TABLE statement.)
63634   */
63635   if( p->expired ) rc = SQLITE_ABORT;
63636 #endif
63637
63638   REGISTER_TRACE(pOp->p3, pOut);
63639   UPDATE_MAX_BLOBSIZE(pOut);
63640   break;
63641 }
63642
63643 /* Opcode: BitAnd P1 P2 P3 * *
63644 **
63645 ** Take the bit-wise AND of the values in register P1 and P2 and
63646 ** store the result in register P3.
63647 ** If either input is NULL, the result is NULL.
63648 */
63649 /* Opcode: BitOr P1 P2 P3 * *
63650 **
63651 ** Take the bit-wise OR of the values in register P1 and P2 and
63652 ** store the result in register P3.
63653 ** If either input is NULL, the result is NULL.
63654 */
63655 /* Opcode: ShiftLeft P1 P2 P3 * *
63656 **
63657 ** Shift the integer value in register P2 to the left by the
63658 ** number of bits specified by the integer in register P1.
63659 ** Store the result in register P3.
63660 ** If either input is NULL, the result is NULL.
63661 */
63662 /* Opcode: ShiftRight P1 P2 P3 * *
63663 **
63664 ** Shift the integer value in register P2 to the right by the
63665 ** number of bits specified by the integer in register P1.
63666 ** Store the result in register P3.
63667 ** If either input is NULL, the result is NULL.
63668 */
63669 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
63670 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
63671 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
63672 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
63673 #if 0  /* local variables moved into u.ah */
63674   i64 iA;
63675   u64 uA;
63676   i64 iB;
63677   u8 op;
63678 #endif /* local variables moved into u.ah */
63679
63680   pIn1 = &aMem[pOp->p1];
63681   pIn2 = &aMem[pOp->p2];
63682   pOut = &aMem[pOp->p3];
63683   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63684     sqlite3VdbeMemSetNull(pOut);
63685     break;
63686   }
63687   u.ah.iA = sqlite3VdbeIntValue(pIn2);
63688   u.ah.iB = sqlite3VdbeIntValue(pIn1);
63689   u.ah.op = pOp->opcode;
63690   if( u.ah.op==OP_BitAnd ){
63691     u.ah.iA &= u.ah.iB;
63692   }else if( u.ah.op==OP_BitOr ){
63693     u.ah.iA |= u.ah.iB;
63694   }else if( u.ah.iB!=0 ){
63695     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
63696
63697     /* If shifting by a negative amount, shift in the other direction */
63698     if( u.ah.iB<0 ){
63699       assert( OP_ShiftRight==OP_ShiftLeft+1 );
63700       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
63701       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
63702     }
63703
63704     if( u.ah.iB>=64 ){
63705       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
63706     }else{
63707       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
63708       if( u.ah.op==OP_ShiftLeft ){
63709         u.ah.uA <<= u.ah.iB;
63710       }else{
63711         u.ah.uA >>= u.ah.iB;
63712         /* Sign-extend on a right shift of a negative number */
63713         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
63714       }
63715       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
63716     }
63717   }
63718   pOut->u.i = u.ah.iA;
63719   MemSetTypeFlag(pOut, MEM_Int);
63720   break;
63721 }
63722
63723 /* Opcode: AddImm  P1 P2 * * *
63724 ** 
63725 ** Add the constant P2 to the value in register P1.
63726 ** The result is always an integer.
63727 **
63728 ** To force any register to be an integer, just add 0.
63729 */
63730 case OP_AddImm: {            /* in1 */
63731   pIn1 = &aMem[pOp->p1];
63732   memAboutToChange(p, pIn1);
63733   sqlite3VdbeMemIntegerify(pIn1);
63734   pIn1->u.i += pOp->p2;
63735   break;
63736 }
63737
63738 /* Opcode: MustBeInt P1 P2 * * *
63739 ** 
63740 ** Force the value in register P1 to be an integer.  If the value
63741 ** in P1 is not an integer and cannot be converted into an integer
63742 ** without data loss, then jump immediately to P2, or if P2==0
63743 ** raise an SQLITE_MISMATCH exception.
63744 */
63745 case OP_MustBeInt: {            /* jump, in1 */
63746   pIn1 = &aMem[pOp->p1];
63747   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
63748   if( (pIn1->flags & MEM_Int)==0 ){
63749     if( pOp->p2==0 ){
63750       rc = SQLITE_MISMATCH;
63751       goto abort_due_to_error;
63752     }else{
63753       pc = pOp->p2 - 1;
63754     }
63755   }else{
63756     MemSetTypeFlag(pIn1, MEM_Int);
63757   }
63758   break;
63759 }
63760
63761 #ifndef SQLITE_OMIT_FLOATING_POINT
63762 /* Opcode: RealAffinity P1 * * * *
63763 **
63764 ** If register P1 holds an integer convert it to a real value.
63765 **
63766 ** This opcode is used when extracting information from a column that
63767 ** has REAL affinity.  Such column values may still be stored as
63768 ** integers, for space efficiency, but after extraction we want them
63769 ** to have only a real value.
63770 */
63771 case OP_RealAffinity: {                  /* in1 */
63772   pIn1 = &aMem[pOp->p1];
63773   if( pIn1->flags & MEM_Int ){
63774     sqlite3VdbeMemRealify(pIn1);
63775   }
63776   break;
63777 }
63778 #endif
63779
63780 #ifndef SQLITE_OMIT_CAST
63781 /* Opcode: ToText P1 * * * *
63782 **
63783 ** Force the value in register P1 to be text.
63784 ** If the value is numeric, convert it to a string using the
63785 ** equivalent of printf().  Blob values are unchanged and
63786 ** are afterwards simply interpreted as text.
63787 **
63788 ** A NULL value is not changed by this routine.  It remains NULL.
63789 */
63790 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
63791   pIn1 = &aMem[pOp->p1];
63792   memAboutToChange(p, pIn1);
63793   if( pIn1->flags & MEM_Null ) break;
63794   assert( MEM_Str==(MEM_Blob>>3) );
63795   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
63796   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63797   rc = ExpandBlob(pIn1);
63798   assert( pIn1->flags & MEM_Str || db->mallocFailed );
63799   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
63800   UPDATE_MAX_BLOBSIZE(pIn1);
63801   break;
63802 }
63803
63804 /* Opcode: ToBlob P1 * * * *
63805 **
63806 ** Force the value in register P1 to be a BLOB.
63807 ** If the value is numeric, convert it to a string first.
63808 ** Strings are simply reinterpreted as blobs with no change
63809 ** to the underlying data.
63810 **
63811 ** A NULL value is not changed by this routine.  It remains NULL.
63812 */
63813 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
63814   pIn1 = &aMem[pOp->p1];
63815   if( pIn1->flags & MEM_Null ) break;
63816   if( (pIn1->flags & MEM_Blob)==0 ){
63817     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
63818     assert( pIn1->flags & MEM_Str || db->mallocFailed );
63819     MemSetTypeFlag(pIn1, MEM_Blob);
63820   }else{
63821     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
63822   }
63823   UPDATE_MAX_BLOBSIZE(pIn1);
63824   break;
63825 }
63826
63827 /* Opcode: ToNumeric P1 * * * *
63828 **
63829 ** Force the value in register P1 to be numeric (either an
63830 ** integer or a floating-point number.)
63831 ** If the value is text or blob, try to convert it to an using the
63832 ** equivalent of atoi() or atof() and store 0 if no such conversion 
63833 ** is possible.
63834 **
63835 ** A NULL value is not changed by this routine.  It remains NULL.
63836 */
63837 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
63838   pIn1 = &aMem[pOp->p1];
63839   sqlite3VdbeMemNumerify(pIn1);
63840   break;
63841 }
63842 #endif /* SQLITE_OMIT_CAST */
63843
63844 /* Opcode: ToInt P1 * * * *
63845 **
63846 ** Force the value in register P1 to be an integer.  If
63847 ** The value is currently a real number, drop its fractional part.
63848 ** If the value is text or blob, try to convert it to an integer using the
63849 ** equivalent of atoi() and store 0 if no such conversion is possible.
63850 **
63851 ** A NULL value is not changed by this routine.  It remains NULL.
63852 */
63853 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
63854   pIn1 = &aMem[pOp->p1];
63855   if( (pIn1->flags & MEM_Null)==0 ){
63856     sqlite3VdbeMemIntegerify(pIn1);
63857   }
63858   break;
63859 }
63860
63861 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
63862 /* Opcode: ToReal P1 * * * *
63863 **
63864 ** Force the value in register P1 to be a floating point number.
63865 ** If The value is currently an integer, convert it.
63866 ** If the value is text or blob, try to convert it to an integer using the
63867 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
63868 **
63869 ** A NULL value is not changed by this routine.  It remains NULL.
63870 */
63871 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
63872   pIn1 = &aMem[pOp->p1];
63873   memAboutToChange(p, pIn1);
63874   if( (pIn1->flags & MEM_Null)==0 ){
63875     sqlite3VdbeMemRealify(pIn1);
63876   }
63877   break;
63878 }
63879 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
63880
63881 /* Opcode: Lt P1 P2 P3 P4 P5
63882 **
63883 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
63884 ** jump to address P2.  
63885 **
63886 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
63887 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
63888 ** bit is clear then fall through if either operand is NULL.
63889 **
63890 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
63891 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
63892 ** to coerce both inputs according to this affinity before the
63893 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
63894 ** affinity is used. Note that the affinity conversions are stored
63895 ** back into the input registers P1 and P3.  So this opcode can cause
63896 ** persistent changes to registers P1 and P3.
63897 **
63898 ** Once any conversions have taken place, and neither value is NULL, 
63899 ** the values are compared. If both values are blobs then memcmp() is
63900 ** used to determine the results of the comparison.  If both values
63901 ** are text, then the appropriate collating function specified in
63902 ** P4 is  used to do the comparison.  If P4 is not specified then
63903 ** memcmp() is used to compare text string.  If both values are
63904 ** numeric, then a numeric comparison is used. If the two values
63905 ** are of different types, then numbers are considered less than
63906 ** strings and strings are considered less than blobs.
63907 **
63908 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
63909 ** store a boolean result (either 0, or 1, or NULL) in register P2.
63910 */
63911 /* Opcode: Ne P1 P2 P3 P4 P5
63912 **
63913 ** This works just like the Lt opcode except that the jump is taken if
63914 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
63915 ** additional information.
63916 **
63917 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
63918 ** true or false and is never NULL.  If both operands are NULL then the result
63919 ** of comparison is false.  If either operand is NULL then the result is true.
63920 ** If neither operand is NULL the the result is the same as it would be if
63921 ** the SQLITE_NULLEQ flag were omitted from P5.
63922 */
63923 /* Opcode: Eq P1 P2 P3 P4 P5
63924 **
63925 ** This works just like the Lt opcode except that the jump is taken if
63926 ** the operands in registers P1 and P3 are equal.
63927 ** See the Lt opcode for additional information.
63928 **
63929 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
63930 ** true or false and is never NULL.  If both operands are NULL then the result
63931 ** of comparison is true.  If either operand is NULL then the result is false.
63932 ** If neither operand is NULL the the result is the same as it would be if
63933 ** the SQLITE_NULLEQ flag were omitted from P5.
63934 */
63935 /* Opcode: Le P1 P2 P3 P4 P5
63936 **
63937 ** This works just like the Lt opcode except that the jump is taken if
63938 ** the content of register P3 is less than or equal to the content of
63939 ** register P1.  See the Lt opcode for additional information.
63940 */
63941 /* Opcode: Gt P1 P2 P3 P4 P5
63942 **
63943 ** This works just like the Lt opcode except that the jump is taken if
63944 ** the content of register P3 is greater than the content of
63945 ** register P1.  See the Lt opcode for additional information.
63946 */
63947 /* Opcode: Ge P1 P2 P3 P4 P5
63948 **
63949 ** This works just like the Lt opcode except that the jump is taken if
63950 ** the content of register P3 is greater than or equal to the content of
63951 ** register P1.  See the Lt opcode for additional information.
63952 */
63953 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
63954 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
63955 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
63956 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
63957 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
63958 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
63959 #if 0  /* local variables moved into u.ai */
63960   int res;            /* Result of the comparison of pIn1 against pIn3 */
63961   char affinity;      /* Affinity to use for comparison */
63962   u16 flags1;         /* Copy of initial value of pIn1->flags */
63963   u16 flags3;         /* Copy of initial value of pIn3->flags */
63964 #endif /* local variables moved into u.ai */
63965
63966   pIn1 = &aMem[pOp->p1];
63967   pIn3 = &aMem[pOp->p3];
63968   u.ai.flags1 = pIn1->flags;
63969   u.ai.flags3 = pIn3->flags;
63970   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
63971     /* One or both operands are NULL */
63972     if( pOp->p5 & SQLITE_NULLEQ ){
63973       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
63974       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
63975       ** or not both operands are null.
63976       */
63977       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
63978       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
63979     }else{
63980       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
63981       ** then the result is always NULL.
63982       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
63983       */
63984       if( pOp->p5 & SQLITE_STOREP2 ){
63985         pOut = &aMem[pOp->p2];
63986         MemSetTypeFlag(pOut, MEM_Null);
63987         REGISTER_TRACE(pOp->p2, pOut);
63988       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
63989         pc = pOp->p2-1;
63990       }
63991       break;
63992     }
63993   }else{
63994     /* Neither operand is NULL.  Do a comparison. */
63995     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
63996     if( u.ai.affinity ){
63997       applyAffinity(pIn1, u.ai.affinity, encoding);
63998       applyAffinity(pIn3, u.ai.affinity, encoding);
63999       if( db->mallocFailed ) goto no_mem;
64000     }
64001
64002     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
64003     ExpandBlob(pIn1);
64004     ExpandBlob(pIn3);
64005     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
64006   }
64007   switch( pOp->opcode ){
64008     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
64009     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
64010     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
64011     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
64012     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
64013     default:       u.ai.res = u.ai.res>=0;     break;
64014   }
64015
64016   if( pOp->p5 & SQLITE_STOREP2 ){
64017     pOut = &aMem[pOp->p2];
64018     memAboutToChange(p, pOut);
64019     MemSetTypeFlag(pOut, MEM_Int);
64020     pOut->u.i = u.ai.res;
64021     REGISTER_TRACE(pOp->p2, pOut);
64022   }else if( u.ai.res ){
64023     pc = pOp->p2-1;
64024   }
64025
64026   /* Undo any changes made by applyAffinity() to the input registers. */
64027   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64028   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64029   break;
64030 }
64031
64032 /* Opcode: Permutation * * * P4 *
64033 **
64034 ** Set the permutation used by the OP_Compare operator to be the array
64035 ** of integers in P4.
64036 **
64037 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
64038 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
64039 ** immediately prior to the OP_Compare.
64040 */
64041 case OP_Permutation: {
64042   assert( pOp->p4type==P4_INTARRAY );
64043   assert( pOp->p4.ai );
64044   aPermute = pOp->p4.ai;
64045   break;
64046 }
64047
64048 /* Opcode: Compare P1 P2 P3 P4 *
64049 **
64050 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64051 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
64052 ** the comparison for use by the next OP_Jump instruct.
64053 **
64054 ** P4 is a KeyInfo structure that defines collating sequences and sort
64055 ** orders for the comparison.  The permutation applies to registers
64056 ** only.  The KeyInfo elements are used sequentially.
64057 **
64058 ** The comparison is a sort comparison, so NULLs compare equal,
64059 ** NULLs are less than numbers, numbers are less than strings,
64060 ** and strings are less than blobs.
64061 */
64062 case OP_Compare: {
64063 #if 0  /* local variables moved into u.aj */
64064   int n;
64065   int i;
64066   int p1;
64067   int p2;
64068   const KeyInfo *pKeyInfo;
64069   int idx;
64070   CollSeq *pColl;    /* Collating sequence to use on this term */
64071   int bRev;          /* True for DESCENDING sort order */
64072 #endif /* local variables moved into u.aj */
64073
64074   u.aj.n = pOp->p3;
64075   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64076   assert( u.aj.n>0 );
64077   assert( u.aj.pKeyInfo!=0 );
64078   u.aj.p1 = pOp->p1;
64079   u.aj.p2 = pOp->p2;
64080 #if SQLITE_DEBUG
64081   if( aPermute ){
64082     int k, mx = 0;
64083     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64084     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64085     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64086   }else{
64087     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64088     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64089   }
64090 #endif /* SQLITE_DEBUG */
64091   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64092     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64093     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64094     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64095     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64096     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64097     assert( u.aj.i<u.aj.pKeyInfo->nField );
64098     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64099     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64100     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64101     if( iCompare ){
64102       if( u.aj.bRev ) iCompare = -iCompare;
64103       break;
64104     }
64105   }
64106   aPermute = 0;
64107   break;
64108 }
64109
64110 /* Opcode: Jump P1 P2 P3 * *
64111 **
64112 ** Jump to the instruction at address P1, P2, or P3 depending on whether
64113 ** in the most recent OP_Compare instruction the P1 vector was less than
64114 ** equal to, or greater than the P2 vector, respectively.
64115 */
64116 case OP_Jump: {             /* jump */
64117   if( iCompare<0 ){
64118     pc = pOp->p1 - 1;
64119   }else if( iCompare==0 ){
64120     pc = pOp->p2 - 1;
64121   }else{
64122     pc = pOp->p3 - 1;
64123   }
64124   break;
64125 }
64126
64127 /* Opcode: And P1 P2 P3 * *
64128 **
64129 ** Take the logical AND of the values in registers P1 and P2 and
64130 ** write the result into register P3.
64131 **
64132 ** If either P1 or P2 is 0 (false) then the result is 0 even if
64133 ** the other input is NULL.  A NULL and true or two NULLs give
64134 ** a NULL output.
64135 */
64136 /* Opcode: Or P1 P2 P3 * *
64137 **
64138 ** Take the logical OR of the values in register P1 and P2 and
64139 ** store the answer in register P3.
64140 **
64141 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64142 ** even if the other input is NULL.  A NULL and false or two NULLs
64143 ** give a NULL output.
64144 */
64145 case OP_And:              /* same as TK_AND, in1, in2, out3 */
64146 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
64147 #if 0  /* local variables moved into u.ak */
64148   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64149   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64150 #endif /* local variables moved into u.ak */
64151
64152   pIn1 = &aMem[pOp->p1];
64153   if( pIn1->flags & MEM_Null ){
64154     u.ak.v1 = 2;
64155   }else{
64156     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64157   }
64158   pIn2 = &aMem[pOp->p2];
64159   if( pIn2->flags & MEM_Null ){
64160     u.ak.v2 = 2;
64161   }else{
64162     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64163   }
64164   if( pOp->opcode==OP_And ){
64165     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64166     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64167   }else{
64168     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64169     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64170   }
64171   pOut = &aMem[pOp->p3];
64172   if( u.ak.v1==2 ){
64173     MemSetTypeFlag(pOut, MEM_Null);
64174   }else{
64175     pOut->u.i = u.ak.v1;
64176     MemSetTypeFlag(pOut, MEM_Int);
64177   }
64178   break;
64179 }
64180
64181 /* Opcode: Not P1 P2 * * *
64182 **
64183 ** Interpret the value in register P1 as a boolean value.  Store the
64184 ** boolean complement in register P2.  If the value in register P1 is 
64185 ** NULL, then a NULL is stored in P2.
64186 */
64187 case OP_Not: {                /* same as TK_NOT, in1, out2 */
64188   pIn1 = &aMem[pOp->p1];
64189   pOut = &aMem[pOp->p2];
64190   if( pIn1->flags & MEM_Null ){
64191     sqlite3VdbeMemSetNull(pOut);
64192   }else{
64193     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64194   }
64195   break;
64196 }
64197
64198 /* Opcode: BitNot P1 P2 * * *
64199 **
64200 ** Interpret the content of register P1 as an integer.  Store the
64201 ** ones-complement of the P1 value into register P2.  If P1 holds
64202 ** a NULL then store a NULL in P2.
64203 */
64204 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
64205   pIn1 = &aMem[pOp->p1];
64206   pOut = &aMem[pOp->p2];
64207   if( pIn1->flags & MEM_Null ){
64208     sqlite3VdbeMemSetNull(pOut);
64209   }else{
64210     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64211   }
64212   break;
64213 }
64214
64215 /* Opcode: If P1 P2 P3 * *
64216 **
64217 ** Jump to P2 if the value in register P1 is true.  The value is
64218 ** is considered true if it is numeric and non-zero.  If the value
64219 ** in P1 is NULL then take the jump if P3 is true.
64220 */
64221 /* Opcode: IfNot P1 P2 P3 * *
64222 **
64223 ** Jump to P2 if the value in register P1 is False.  The value is
64224 ** is considered true if it has a numeric value of zero.  If the value
64225 ** in P1 is NULL then take the jump if P3 is true.
64226 */
64227 case OP_If:                 /* jump, in1 */
64228 case OP_IfNot: {            /* jump, in1 */
64229 #if 0  /* local variables moved into u.al */
64230   int c;
64231 #endif /* local variables moved into u.al */
64232   pIn1 = &aMem[pOp->p1];
64233   if( pIn1->flags & MEM_Null ){
64234     u.al.c = pOp->p3;
64235   }else{
64236 #ifdef SQLITE_OMIT_FLOATING_POINT
64237     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64238 #else
64239     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64240 #endif
64241     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64242   }
64243   if( u.al.c ){
64244     pc = pOp->p2-1;
64245   }
64246   break;
64247 }
64248
64249 /* Opcode: IsNull P1 P2 * * *
64250 **
64251 ** Jump to P2 if the value in register P1 is NULL.
64252 */
64253 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
64254   pIn1 = &aMem[pOp->p1];
64255   if( (pIn1->flags & MEM_Null)!=0 ){
64256     pc = pOp->p2 - 1;
64257   }
64258   break;
64259 }
64260
64261 /* Opcode: NotNull P1 P2 * * *
64262 **
64263 ** Jump to P2 if the value in register P1 is not NULL.  
64264 */
64265 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
64266   pIn1 = &aMem[pOp->p1];
64267   if( (pIn1->flags & MEM_Null)==0 ){
64268     pc = pOp->p2 - 1;
64269   }
64270   break;
64271 }
64272
64273 /* Opcode: Column P1 P2 P3 P4 P5
64274 **
64275 ** Interpret the data that cursor P1 points to as a structure built using
64276 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
64277 ** information about the format of the data.)  Extract the P2-th column
64278 ** from this record.  If there are less that (P2+1) 
64279 ** values in the record, extract a NULL.
64280 **
64281 ** The value extracted is stored in register P3.
64282 **
64283 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
64284 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
64285 ** the result.
64286 **
64287 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64288 ** then the cache of the cursor is reset prior to extracting the column.
64289 ** The first OP_Column against a pseudo-table after the value of the content
64290 ** register has changed should have this bit set.
64291 */
64292 case OP_Column: {
64293 #if 0  /* local variables moved into u.am */
64294   u32 payloadSize;   /* Number of bytes in the record */
64295   i64 payloadSize64; /* Number of bytes in the record */
64296   int p1;            /* P1 value of the opcode */
64297   int p2;            /* column number to retrieve */
64298   VdbeCursor *pC;    /* The VDBE cursor */
64299   char *zRec;        /* Pointer to complete record-data */
64300   BtCursor *pCrsr;   /* The BTree cursor */
64301   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64302   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64303   int nField;        /* number of fields in the record */
64304   int len;           /* The length of the serialized data for the column */
64305   int i;             /* Loop counter */
64306   char *zData;       /* Part of the record being decoded */
64307   Mem *pDest;        /* Where to write the extracted value */
64308   Mem sMem;          /* For storing the record being decoded */
64309   u8 *zIdx;          /* Index into header */
64310   u8 *zEndHdr;       /* Pointer to first byte after the header */
64311   u32 offset;        /* Offset into the data */
64312   u32 szField;       /* Number of bytes in the content of a field */
64313   int szHdr;         /* Size of the header size field at start of record */
64314   int avail;         /* Number of bytes of available data */
64315   Mem *pReg;         /* PseudoTable input register */
64316 #endif /* local variables moved into u.am */
64317
64318
64319   u.am.p1 = pOp->p1;
64320   u.am.p2 = pOp->p2;
64321   u.am.pC = 0;
64322   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64323   assert( u.am.p1<p->nCursor );
64324   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64325   u.am.pDest = &aMem[pOp->p3];
64326   memAboutToChange(p, u.am.pDest);
64327   MemSetTypeFlag(u.am.pDest, MEM_Null);
64328   u.am.zRec = 0;
64329
64330   /* This block sets the variable u.am.payloadSize to be the total number of
64331   ** bytes in the record.
64332   **
64333   ** u.am.zRec is set to be the complete text of the record if it is available.
64334   ** The complete record text is always available for pseudo-tables
64335   ** If the record is stored in a cursor, the complete record text
64336   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
64337   ** If the data is unavailable,  u.am.zRec is set to NULL.
64338   **
64339   ** We also compute the number of columns in the record.  For cursors,
64340   ** the number of columns is stored in the VdbeCursor.nField element.
64341   */
64342   u.am.pC = p->apCsr[u.am.p1];
64343   assert( u.am.pC!=0 );
64344 #ifndef SQLITE_OMIT_VIRTUALTABLE
64345   assert( u.am.pC->pVtabCursor==0 );
64346 #endif
64347   u.am.pCrsr = u.am.pC->pCursor;
64348   if( u.am.pCrsr!=0 ){
64349     /* The record is stored in a B-Tree */
64350     rc = sqlite3VdbeCursorMoveto(u.am.pC);
64351     if( rc ) goto abort_due_to_error;
64352     if( u.am.pC->nullRow ){
64353       u.am.payloadSize = 0;
64354     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64355       u.am.payloadSize = u.am.pC->payloadSize;
64356       u.am.zRec = (char*)u.am.pC->aRow;
64357     }else if( u.am.pC->isIndex ){
64358       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64359       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64360       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
64361       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64362       ** payload size, so it is impossible for u.am.payloadSize64 to be
64363       ** larger than 32 bits. */
64364       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64365       u.am.payloadSize = (u32)u.am.payloadSize64;
64366     }else{
64367       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64368       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64369       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
64370     }
64371   }else if( u.am.pC->pseudoTableReg>0 ){
64372     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64373     assert( u.am.pReg->flags & MEM_Blob );
64374     assert( memIsValid(u.am.pReg) );
64375     u.am.payloadSize = u.am.pReg->n;
64376     u.am.zRec = u.am.pReg->z;
64377     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64378     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64379   }else{
64380     /* Consider the row to be NULL */
64381     u.am.payloadSize = 0;
64382   }
64383
64384   /* If u.am.payloadSize is 0, then just store a NULL */
64385   if( u.am.payloadSize==0 ){
64386     assert( u.am.pDest->flags&MEM_Null );
64387     goto op_column_out;
64388   }
64389   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64390   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64391     goto too_big;
64392   }
64393
64394   u.am.nField = u.am.pC->nField;
64395   assert( u.am.p2<u.am.nField );
64396
64397   /* Read and parse the table header.  Store the results of the parse
64398   ** into the record header cache fields of the cursor.
64399   */
64400   u.am.aType = u.am.pC->aType;
64401   if( u.am.pC->cacheStatus==p->cacheCtr ){
64402     u.am.aOffset = u.am.pC->aOffset;
64403   }else{
64404     assert(u.am.aType);
64405     u.am.avail = 0;
64406     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64407     u.am.pC->payloadSize = u.am.payloadSize;
64408     u.am.pC->cacheStatus = p->cacheCtr;
64409
64410     /* Figure out how many bytes are in the header */
64411     if( u.am.zRec ){
64412       u.am.zData = u.am.zRec;
64413     }else{
64414       if( u.am.pC->isIndex ){
64415         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64416       }else{
64417         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64418       }
64419       /* If KeyFetch()/DataFetch() managed to get the entire payload,
64420       ** save the payload in the u.am.pC->aRow cache.  That will save us from
64421       ** having to make additional calls to fetch the content portion of
64422       ** the record.
64423       */
64424       assert( u.am.avail>=0 );
64425       if( u.am.payloadSize <= (u32)u.am.avail ){
64426         u.am.zRec = u.am.zData;
64427         u.am.pC->aRow = (u8*)u.am.zData;
64428       }else{
64429         u.am.pC->aRow = 0;
64430       }
64431     }
64432     /* The following assert is true in all cases accept when
64433     ** the database file has been corrupted externally.
64434     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
64435     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
64436
64437     /* Make sure a corrupt database has not given us an oversize header.
64438     ** Do this now to avoid an oversize memory allocation.
64439     **
64440     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
64441     ** types use so much data space that there can only be 4096 and 32 of
64442     ** them, respectively.  So the maximum header length results from a
64443     ** 3-byte type for each of the maximum of 32768 columns plus three
64444     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
64445     */
64446     if( u.am.offset > 98307 ){
64447       rc = SQLITE_CORRUPT_BKPT;
64448       goto op_column_out;
64449     }
64450
64451     /* Compute in u.am.len the number of bytes of data we need to read in order
64452     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
64453     ** u.am.nField might be significantly less than the true number of columns
64454     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
64455     ** We want to minimize u.am.len in order to limit the size of the memory
64456     ** allocation, especially if a corrupt database file has caused u.am.offset
64457     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
64458     ** still exceed Robson memory allocation limits on some configurations.
64459     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
64460     ** will likely be much smaller since u.am.nField will likely be less than
64461     ** 20 or so.  This insures that Robson memory allocation limits are
64462     ** not exceeded even for corrupt database files.
64463     */
64464     u.am.len = u.am.nField*5 + 3;
64465     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
64466
64467     /* The KeyFetch() or DataFetch() above are fast and will get the entire
64468     ** record header in most cases.  But they will fail to get the complete
64469     ** record header if the record header does not fit on a single page
64470     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
64471     ** acquire the complete header text.
64472     */
64473     if( !u.am.zRec && u.am.avail<u.am.len ){
64474       u.am.sMem.flags = 0;
64475       u.am.sMem.db = 0;
64476       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
64477       if( rc!=SQLITE_OK ){
64478         goto op_column_out;
64479       }
64480       u.am.zData = u.am.sMem.z;
64481     }
64482     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
64483     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
64484
64485     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
64486     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
64487     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
64488     ** of the record to the start of the data for the u.am.i-th column
64489     */
64490     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
64491       if( u.am.zIdx<u.am.zEndHdr ){
64492         u.am.aOffset[u.am.i] = u.am.offset;
64493         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
64494         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
64495         u.am.offset += u.am.szField;
64496         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
64497           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
64498           break;
64499         }
64500       }else{
64501         /* If u.am.i is less that u.am.nField, then there are less fields in this
64502         ** record than SetNumColumns indicated there are columns in the
64503         ** table. Set the u.am.offset for any extra columns not present in
64504         ** the record to 0. This tells code below to store a NULL
64505         ** instead of deserializing a value from the record.
64506         */
64507         u.am.aOffset[u.am.i] = 0;
64508       }
64509     }
64510     sqlite3VdbeMemRelease(&u.am.sMem);
64511     u.am.sMem.flags = MEM_Null;
64512
64513     /* If we have read more header data than was contained in the header,
64514     ** or if the end of the last field appears to be past the end of the
64515     ** record, or if the end of the last field appears to be before the end
64516     ** of the record (when all fields present), then we must be dealing
64517     ** with a corrupt database.
64518     */
64519     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
64520          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
64521       rc = SQLITE_CORRUPT_BKPT;
64522       goto op_column_out;
64523     }
64524   }
64525
64526   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
64527   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
64528   ** then there are not enough fields in the record to satisfy the
64529   ** request.  In this case, set the value NULL or to P4 if P4 is
64530   ** a pointer to a Mem object.
64531   */
64532   if( u.am.aOffset[u.am.p2] ){
64533     assert( rc==SQLITE_OK );
64534     if( u.am.zRec ){
64535       sqlite3VdbeMemReleaseExternal(u.am.pDest);
64536       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
64537     }else{
64538       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
64539       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
64540       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
64541       if( rc!=SQLITE_OK ){
64542         goto op_column_out;
64543       }
64544       u.am.zData = u.am.sMem.z;
64545       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
64546     }
64547     u.am.pDest->enc = encoding;
64548   }else{
64549     if( pOp->p4type==P4_MEM ){
64550       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
64551     }else{
64552       assert( u.am.pDest->flags&MEM_Null );
64553     }
64554   }
64555
64556   /* If we dynamically allocated space to hold the data (in the
64557   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
64558   ** dynamically allocated space over to the u.am.pDest structure.
64559   ** This prevents a memory copy.
64560   */
64561   if( u.am.sMem.zMalloc ){
64562     assert( u.am.sMem.z==u.am.sMem.zMalloc );
64563     assert( !(u.am.pDest->flags & MEM_Dyn) );
64564     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
64565     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
64566     u.am.pDest->flags |= MEM_Term;
64567     u.am.pDest->z = u.am.sMem.z;
64568     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
64569   }
64570
64571   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
64572
64573 op_column_out:
64574   UPDATE_MAX_BLOBSIZE(u.am.pDest);
64575   REGISTER_TRACE(pOp->p3, u.am.pDest);
64576   break;
64577 }
64578
64579 /* Opcode: Affinity P1 P2 * P4 *
64580 **
64581 ** Apply affinities to a range of P2 registers starting with P1.
64582 **
64583 ** P4 is a string that is P2 characters long. The nth character of the
64584 ** string indicates the column affinity that should be used for the nth
64585 ** memory cell in the range.
64586 */
64587 case OP_Affinity: {
64588 #if 0  /* local variables moved into u.an */
64589   const char *zAffinity;   /* The affinity to be applied */
64590   char cAff;               /* A single character of affinity */
64591 #endif /* local variables moved into u.an */
64592
64593   u.an.zAffinity = pOp->p4.z;
64594   assert( u.an.zAffinity!=0 );
64595   assert( u.an.zAffinity[pOp->p2]==0 );
64596   pIn1 = &aMem[pOp->p1];
64597   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
64598     assert( pIn1 <= &p->aMem[p->nMem] );
64599     assert( memIsValid(pIn1) );
64600     ExpandBlob(pIn1);
64601     applyAffinity(pIn1, u.an.cAff, encoding);
64602     pIn1++;
64603   }
64604   break;
64605 }
64606
64607 /* Opcode: MakeRecord P1 P2 P3 P4 *
64608 **
64609 ** Convert P2 registers beginning with P1 into the [record format]
64610 ** use as a data record in a database table or as a key
64611 ** in an index.  The OP_Column opcode can decode the record later.
64612 **
64613 ** P4 may be a string that is P2 characters long.  The nth character of the
64614 ** string indicates the column affinity that should be used for the nth
64615 ** field of the index key.
64616 **
64617 ** The mapping from character to affinity is given by the SQLITE_AFF_
64618 ** macros defined in sqliteInt.h.
64619 **
64620 ** If P4 is NULL then all index fields have the affinity NONE.
64621 */
64622 case OP_MakeRecord: {
64623 #if 0  /* local variables moved into u.ao */
64624   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64625   Mem *pRec;             /* The new record */
64626   u64 nData;             /* Number of bytes of data space */
64627   int nHdr;              /* Number of bytes of header space */
64628   i64 nByte;             /* Data space required for this record */
64629   int nZero;             /* Number of zero bytes at the end of the record */
64630   int nVarint;           /* Number of bytes in a varint */
64631   u32 serial_type;       /* Type field */
64632   Mem *pData0;           /* First field to be combined into the record */
64633   Mem *pLast;            /* Last field of the record */
64634   int nField;            /* Number of fields in the record */
64635   char *zAffinity;       /* The affinity string for the record */
64636   int file_format;       /* File format to use for encoding */
64637   int i;                 /* Space used in zNewRecord[] */
64638   int len;               /* Length of a field */
64639 #endif /* local variables moved into u.ao */
64640
64641   /* Assuming the record contains N fields, the record format looks
64642   ** like this:
64643   **
64644   ** ------------------------------------------------------------------------
64645   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
64646   ** ------------------------------------------------------------------------
64647   **
64648   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
64649   ** and so froth.
64650   **
64651   ** Each type field is a varint representing the serial type of the
64652   ** corresponding data element (see sqlite3VdbeSerialType()). The
64653   ** hdr-size field is also a varint which is the offset from the beginning
64654   ** of the record to data0.
64655   */
64656   u.ao.nData = 0;         /* Number of bytes of data space */
64657   u.ao.nHdr = 0;          /* Number of bytes of header space */
64658   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
64659   u.ao.nField = pOp->p1;
64660   u.ao.zAffinity = pOp->p4.z;
64661   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
64662   u.ao.pData0 = &aMem[u.ao.nField];
64663   u.ao.nField = pOp->p2;
64664   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
64665   u.ao.file_format = p->minWriteFileFormat;
64666
64667   /* Identify the output register */
64668   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
64669   pOut = &aMem[pOp->p3];
64670   memAboutToChange(p, pOut);
64671
64672   /* Loop through the elements that will make up the record to figure
64673   ** out how much space is required for the new record.
64674   */
64675   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64676     assert( memIsValid(u.ao.pRec) );
64677     if( u.ao.zAffinity ){
64678       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
64679     }
64680     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
64681       sqlite3VdbeMemExpandBlob(u.ao.pRec);
64682     }
64683     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64684     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
64685     u.ao.nData += u.ao.len;
64686     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
64687     if( u.ao.pRec->flags & MEM_Zero ){
64688       /* Only pure zero-filled BLOBs can be input to this Opcode.
64689       ** We do not allow blobs with a prefix and a zero-filled tail. */
64690       u.ao.nZero += u.ao.pRec->u.nZero;
64691     }else if( u.ao.len ){
64692       u.ao.nZero = 0;
64693     }
64694   }
64695
64696   /* Add the initial header varint and total the size */
64697   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
64698   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
64699     u.ao.nHdr++;
64700   }
64701   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
64702   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64703     goto too_big;
64704   }
64705
64706   /* Make sure the output register has a buffer large enough to store
64707   ** the new record. The output register (pOp->p3) is not allowed to
64708   ** be one of the input registers (because the following call to
64709   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
64710   */
64711   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
64712     goto no_mem;
64713   }
64714   u.ao.zNewRecord = (u8 *)pOut->z;
64715
64716   /* Write the record */
64717   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
64718   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64719     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64720     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
64721   }
64722   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
64723     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
64724   }
64725   assert( u.ao.i==u.ao.nByte );
64726
64727   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64728   pOut->n = (int)u.ao.nByte;
64729   pOut->flags = MEM_Blob | MEM_Dyn;
64730   pOut->xDel = 0;
64731   if( u.ao.nZero ){
64732     pOut->u.nZero = u.ao.nZero;
64733     pOut->flags |= MEM_Zero;
64734   }
64735   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
64736   REGISTER_TRACE(pOp->p3, pOut);
64737   UPDATE_MAX_BLOBSIZE(pOut);
64738   break;
64739 }
64740
64741 /* Opcode: Count P1 P2 * * *
64742 **
64743 ** Store the number of entries (an integer value) in the table or index 
64744 ** opened by cursor P1 in register P2
64745 */
64746 #ifndef SQLITE_OMIT_BTREECOUNT
64747 case OP_Count: {         /* out2-prerelease */
64748 #if 0  /* local variables moved into u.ap */
64749   i64 nEntry;
64750   BtCursor *pCrsr;
64751 #endif /* local variables moved into u.ap */
64752
64753   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
64754   if( u.ap.pCrsr ){
64755     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
64756   }else{
64757     u.ap.nEntry = 0;
64758   }
64759   pOut->u.i = u.ap.nEntry;
64760   break;
64761 }
64762 #endif
64763
64764 /* Opcode: Savepoint P1 * * P4 *
64765 **
64766 ** Open, release or rollback the savepoint named by parameter P4, depending
64767 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
64768 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
64769 */
64770 case OP_Savepoint: {
64771 #if 0  /* local variables moved into u.aq */
64772   int p1;                         /* Value of P1 operand */
64773   char *zName;                    /* Name of savepoint */
64774   int nName;
64775   Savepoint *pNew;
64776   Savepoint *pSavepoint;
64777   Savepoint *pTmp;
64778   int iSavepoint;
64779   int ii;
64780 #endif /* local variables moved into u.aq */
64781
64782   u.aq.p1 = pOp->p1;
64783   u.aq.zName = pOp->p4.z;
64784
64785   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
64786   ** transaction, then there cannot be any savepoints.
64787   */
64788   assert( db->pSavepoint==0 || db->autoCommit==0 );
64789   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
64790   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
64791   assert( checkSavepointCount(db) );
64792
64793   if( u.aq.p1==SAVEPOINT_BEGIN ){
64794     if( db->writeVdbeCnt>0 ){
64795       /* A new savepoint cannot be created if there are active write
64796       ** statements (i.e. open read/write incremental blob handles).
64797       */
64798       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
64799         "SQL statements in progress");
64800       rc = SQLITE_BUSY;
64801     }else{
64802       u.aq.nName = sqlite3Strlen30(u.aq.zName);
64803
64804       /* Create a new savepoint structure. */
64805       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
64806       if( u.aq.pNew ){
64807         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
64808         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
64809
64810         /* If there is no open transaction, then mark this as a special
64811         ** "transaction savepoint". */
64812         if( db->autoCommit ){
64813           db->autoCommit = 0;
64814           db->isTransactionSavepoint = 1;
64815         }else{
64816           db->nSavepoint++;
64817         }
64818
64819         /* Link the new savepoint into the database handle's list. */
64820         u.aq.pNew->pNext = db->pSavepoint;
64821         db->pSavepoint = u.aq.pNew;
64822         u.aq.pNew->nDeferredCons = db->nDeferredCons;
64823       }
64824     }
64825   }else{
64826     u.aq.iSavepoint = 0;
64827
64828     /* Find the named savepoint. If there is no such savepoint, then an
64829     ** an error is returned to the user.  */
64830     for(
64831       u.aq.pSavepoint = db->pSavepoint;
64832       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
64833       u.aq.pSavepoint = u.aq.pSavepoint->pNext
64834     ){
64835       u.aq.iSavepoint++;
64836     }
64837     if( !u.aq.pSavepoint ){
64838       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
64839       rc = SQLITE_ERROR;
64840     }else if(
64841         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
64842     ){
64843       /* It is not possible to release (commit) a savepoint if there are
64844       ** active write statements. It is not possible to rollback a savepoint
64845       ** if there are any active statements at all.
64846       */
64847       sqlite3SetString(&p->zErrMsg, db,
64848         "cannot %s savepoint - SQL statements in progress",
64849         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
64850       );
64851       rc = SQLITE_BUSY;
64852     }else{
64853
64854       /* Determine whether or not this is a transaction savepoint. If so,
64855       ** and this is a RELEASE command, then the current transaction
64856       ** is committed.
64857       */
64858       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
64859       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
64860         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
64861           goto vdbe_return;
64862         }
64863         db->autoCommit = 1;
64864         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
64865           p->pc = pc;
64866           db->autoCommit = 0;
64867           p->rc = rc = SQLITE_BUSY;
64868           goto vdbe_return;
64869         }
64870         db->isTransactionSavepoint = 0;
64871         rc = p->rc;
64872       }else{
64873         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
64874         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
64875           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
64876           if( rc!=SQLITE_OK ){
64877             goto abort_due_to_error;
64878           }
64879         }
64880         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
64881           sqlite3ExpirePreparedStatements(db);
64882           sqlite3ResetInternalSchema(db, -1);
64883           db->flags = (db->flags | SQLITE_InternChanges);
64884         }
64885       }
64886
64887       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
64888       ** savepoints nested inside of the savepoint being operated on. */
64889       while( db->pSavepoint!=u.aq.pSavepoint ){
64890         u.aq.pTmp = db->pSavepoint;
64891         db->pSavepoint = u.aq.pTmp->pNext;
64892         sqlite3DbFree(db, u.aq.pTmp);
64893         db->nSavepoint--;
64894       }
64895
64896       /* If it is a RELEASE, then destroy the savepoint being operated on
64897       ** too. If it is a ROLLBACK TO, then set the number of deferred
64898       ** constraint violations present in the database to the value stored
64899       ** when the savepoint was created.  */
64900       if( u.aq.p1==SAVEPOINT_RELEASE ){
64901         assert( u.aq.pSavepoint==db->pSavepoint );
64902         db->pSavepoint = u.aq.pSavepoint->pNext;
64903         sqlite3DbFree(db, u.aq.pSavepoint);
64904         if( !isTransaction ){
64905           db->nSavepoint--;
64906         }
64907       }else{
64908         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
64909       }
64910     }
64911   }
64912
64913   break;
64914 }
64915
64916 /* Opcode: AutoCommit P1 P2 * * *
64917 **
64918 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
64919 ** back any currently active btree transactions. If there are any active
64920 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
64921 ** there are active writing VMs or active VMs that use shared cache.
64922 **
64923 ** This instruction causes the VM to halt.
64924 */
64925 case OP_AutoCommit: {
64926 #if 0  /* local variables moved into u.ar */
64927   int desiredAutoCommit;
64928   int iRollback;
64929   int turnOnAC;
64930 #endif /* local variables moved into u.ar */
64931
64932   u.ar.desiredAutoCommit = pOp->p1;
64933   u.ar.iRollback = pOp->p2;
64934   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
64935   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
64936   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
64937   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
64938
64939   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
64940     /* If this instruction implements a ROLLBACK and other VMs are
64941     ** still running, and a transaction is active, return an error indicating
64942     ** that the other VMs must complete first.
64943     */
64944     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
64945         "SQL statements in progress");
64946     rc = SQLITE_BUSY;
64947   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
64948     /* If this instruction implements a COMMIT and other VMs are writing
64949     ** return an error indicating that the other VMs must complete first.
64950     */
64951     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
64952         "SQL statements in progress");
64953     rc = SQLITE_BUSY;
64954   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
64955     if( u.ar.iRollback ){
64956       assert( u.ar.desiredAutoCommit==1 );
64957       sqlite3RollbackAll(db);
64958       db->autoCommit = 1;
64959     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
64960       goto vdbe_return;
64961     }else{
64962       db->autoCommit = (u8)u.ar.desiredAutoCommit;
64963       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
64964         p->pc = pc;
64965         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
64966         p->rc = rc = SQLITE_BUSY;
64967         goto vdbe_return;
64968       }
64969     }
64970     assert( db->nStatement==0 );
64971     sqlite3CloseSavepoints(db);
64972     if( p->rc==SQLITE_OK ){
64973       rc = SQLITE_DONE;
64974     }else{
64975       rc = SQLITE_ERROR;
64976     }
64977     goto vdbe_return;
64978   }else{
64979     sqlite3SetString(&p->zErrMsg, db,
64980         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
64981         (u.ar.iRollback)?"cannot rollback - no transaction is active":
64982                    "cannot commit - no transaction is active"));
64983
64984     rc = SQLITE_ERROR;
64985   }
64986   break;
64987 }
64988
64989 /* Opcode: Transaction P1 P2 * * *
64990 **
64991 ** Begin a transaction.  The transaction ends when a Commit or Rollback
64992 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
64993 ** transaction might also be rolled back if an error is encountered.
64994 **
64995 ** P1 is the index of the database file on which the transaction is
64996 ** started.  Index 0 is the main database file and index 1 is the
64997 ** file used for temporary tables.  Indices of 2 or more are used for
64998 ** attached databases.
64999 **
65000 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
65001 ** obtained on the database file when a write-transaction is started.  No
65002 ** other process can start another write transaction while this transaction is
65003 ** underway.  Starting a write transaction also creates a rollback journal. A
65004 ** write transaction must be started before any changes can be made to the
65005 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
65006 ** on the file.
65007 **
65008 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
65009 ** true (this flag is set if the Vdbe may modify more than one row and may
65010 ** throw an ABORT exception), a statement transaction may also be opened.
65011 ** More specifically, a statement transaction is opened iff the database
65012 ** connection is currently not in autocommit mode, or if there are other
65013 ** active statements. A statement transaction allows the affects of this
65014 ** VDBE to be rolled back after an error without having to roll back the
65015 ** entire transaction. If no error is encountered, the statement transaction
65016 ** will automatically commit when the VDBE halts.
65017 **
65018 ** If P2 is zero, then a read-lock is obtained on the database file.
65019 */
65020 case OP_Transaction: {
65021 #if 0  /* local variables moved into u.as */
65022   Btree *pBt;
65023 #endif /* local variables moved into u.as */
65024
65025   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65026   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65027   u.as.pBt = db->aDb[pOp->p1].pBt;
65028
65029   if( u.as.pBt ){
65030     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65031     if( rc==SQLITE_BUSY ){
65032       p->pc = pc;
65033       p->rc = rc = SQLITE_BUSY;
65034       goto vdbe_return;
65035     }
65036     if( rc!=SQLITE_OK ){
65037       goto abort_due_to_error;
65038     }
65039
65040     if( pOp->p2 && p->usesStmtJournal
65041      && (db->autoCommit==0 || db->activeVdbeCnt>1)
65042     ){
65043       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65044       if( p->iStatement==0 ){
65045         assert( db->nStatement>=0 && db->nSavepoint>=0 );
65046         db->nStatement++;
65047         p->iStatement = db->nSavepoint + db->nStatement;
65048       }
65049       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65050
65051       /* Store the current value of the database handles deferred constraint
65052       ** counter. If the statement transaction needs to be rolled back,
65053       ** the value of this counter needs to be restored too.  */
65054       p->nStmtDefCons = db->nDeferredCons;
65055     }
65056   }
65057   break;
65058 }
65059
65060 /* Opcode: ReadCookie P1 P2 P3 * *
65061 **
65062 ** Read cookie number P3 from database P1 and write it into register P2.
65063 ** P3==1 is the schema version.  P3==2 is the database format.
65064 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
65065 ** the main database file and P1==1 is the database file used to store
65066 ** temporary tables.
65067 **
65068 ** There must be a read-lock on the database (either a transaction
65069 ** must be started or there must be an open cursor) before
65070 ** executing this instruction.
65071 */
65072 case OP_ReadCookie: {               /* out2-prerelease */
65073 #if 0  /* local variables moved into u.at */
65074   int iMeta;
65075   int iDb;
65076   int iCookie;
65077 #endif /* local variables moved into u.at */
65078
65079   u.at.iDb = pOp->p1;
65080   u.at.iCookie = pOp->p3;
65081   assert( pOp->p3<SQLITE_N_BTREE_META );
65082   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65083   assert( db->aDb[u.at.iDb].pBt!=0 );
65084   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65085
65086   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65087   pOut->u.i = u.at.iMeta;
65088   break;
65089 }
65090
65091 /* Opcode: SetCookie P1 P2 P3 * *
65092 **
65093 ** Write the content of register P3 (interpreted as an integer)
65094 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
65095 ** P2==2 is the database format. P2==3 is the recommended pager cache 
65096 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
65097 ** database file used to store temporary tables.
65098 **
65099 ** A transaction must be started before executing this opcode.
65100 */
65101 case OP_SetCookie: {       /* in3 */
65102 #if 0  /* local variables moved into u.au */
65103   Db *pDb;
65104 #endif /* local variables moved into u.au */
65105   assert( pOp->p2<SQLITE_N_BTREE_META );
65106   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65107   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65108   u.au.pDb = &db->aDb[pOp->p1];
65109   assert( u.au.pDb->pBt!=0 );
65110   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65111   pIn3 = &aMem[pOp->p3];
65112   sqlite3VdbeMemIntegerify(pIn3);
65113   /* See note about index shifting on OP_ReadCookie */
65114   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65115   if( pOp->p2==BTREE_SCHEMA_VERSION ){
65116     /* When the schema cookie changes, record the new cookie internally */
65117     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65118     db->flags |= SQLITE_InternChanges;
65119   }else if( pOp->p2==BTREE_FILE_FORMAT ){
65120     /* Record changes in the file format */
65121     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65122   }
65123   if( pOp->p1==1 ){
65124     /* Invalidate all prepared statements whenever the TEMP database
65125     ** schema is changed.  Ticket #1644 */
65126     sqlite3ExpirePreparedStatements(db);
65127     p->expired = 0;
65128   }
65129   break;
65130 }
65131
65132 /* Opcode: VerifyCookie P1 P2 P3 * *
65133 **
65134 ** Check the value of global database parameter number 0 (the
65135 ** schema version) and make sure it is equal to P2 and that the
65136 ** generation counter on the local schema parse equals P3.
65137 **
65138 ** P1 is the database number which is 0 for the main database file
65139 ** and 1 for the file holding temporary tables and some higher number
65140 ** for auxiliary databases.
65141 **
65142 ** The cookie changes its value whenever the database schema changes.
65143 ** This operation is used to detect when that the cookie has changed
65144 ** and that the current process needs to reread the schema.
65145 **
65146 ** Either a transaction needs to have been started or an OP_Open needs
65147 ** to be executed (to establish a read lock) before this opcode is
65148 ** invoked.
65149 */
65150 case OP_VerifyCookie: {
65151 #if 0  /* local variables moved into u.av */
65152   int iMeta;
65153   int iGen;
65154   Btree *pBt;
65155 #endif /* local variables moved into u.av */
65156
65157   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65158   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65159   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65160   u.av.pBt = db->aDb[pOp->p1].pBt;
65161   if( u.av.pBt ){
65162     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65163     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65164   }else{
65165     u.av.iGen = u.av.iMeta = 0;
65166   }
65167   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65168     sqlite3DbFree(db, p->zErrMsg);
65169     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65170     /* If the schema-cookie from the database file matches the cookie
65171     ** stored with the in-memory representation of the schema, do
65172     ** not reload the schema from the database file.
65173     **
65174     ** If virtual-tables are in use, this is not just an optimization.
65175     ** Often, v-tables store their data in other SQLite tables, which
65176     ** are queried from within xNext() and other v-table methods using
65177     ** prepared queries. If such a query is out-of-date, we do not want to
65178     ** discard the database schema, as the user code implementing the
65179     ** v-table would have to be ready for the sqlite3_vtab structure itself
65180     ** to be invalidated whenever sqlite3_step() is called from within
65181     ** a v-table method.
65182     */
65183     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65184       sqlite3ResetInternalSchema(db, pOp->p1);
65185     }
65186
65187     p->expired = 1;
65188     rc = SQLITE_SCHEMA;
65189   }
65190   break;
65191 }
65192
65193 /* Opcode: OpenRead P1 P2 P3 P4 P5
65194 **
65195 ** Open a read-only cursor for the database table whose root page is
65196 ** P2 in a database file.  The database file is determined by P3. 
65197 ** P3==0 means the main database, P3==1 means the database used for 
65198 ** temporary tables, and P3>1 means used the corresponding attached
65199 ** database.  Give the new cursor an identifier of P1.  The P1
65200 ** values need not be contiguous but all P1 values should be small integers.
65201 ** It is an error for P1 to be negative.
65202 **
65203 ** If P5!=0 then use the content of register P2 as the root page, not
65204 ** the value of P2 itself.
65205 **
65206 ** There will be a read lock on the database whenever there is an
65207 ** open cursor.  If the database was unlocked prior to this instruction
65208 ** then a read lock is acquired as part of this instruction.  A read
65209 ** lock allows other processes to read the database but prohibits
65210 ** any other process from modifying the database.  The read lock is
65211 ** released when all cursors are closed.  If this instruction attempts
65212 ** to get a read lock but fails, the script terminates with an
65213 ** SQLITE_BUSY error code.
65214 **
65215 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65216 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65217 ** structure, then said structure defines the content and collating 
65218 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65219 ** value, it is set to the number of columns in the table.
65220 **
65221 ** See also OpenWrite.
65222 */
65223 /* Opcode: OpenWrite P1 P2 P3 P4 P5
65224 **
65225 ** Open a read/write cursor named P1 on the table or index whose root
65226 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
65227 ** root page.
65228 **
65229 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65230 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65231 ** structure, then said structure defines the content and collating 
65232 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65233 ** value, it is set to the number of columns in the table, or to the
65234 ** largest index of any column of the table that is actually used.
65235 **
65236 ** This instruction works just like OpenRead except that it opens the cursor
65237 ** in read/write mode.  For a given table, there can be one or more read-only
65238 ** cursors or a single read/write cursor but not both.
65239 **
65240 ** See also OpenRead.
65241 */
65242 case OP_OpenRead:
65243 case OP_OpenWrite: {
65244 #if 0  /* local variables moved into u.aw */
65245   int nField;
65246   KeyInfo *pKeyInfo;
65247   int p2;
65248   int iDb;
65249   int wrFlag;
65250   Btree *pX;
65251   VdbeCursor *pCur;
65252   Db *pDb;
65253 #endif /* local variables moved into u.aw */
65254
65255   if( p->expired ){
65256     rc = SQLITE_ABORT;
65257     break;
65258   }
65259
65260   u.aw.nField = 0;
65261   u.aw.pKeyInfo = 0;
65262   u.aw.p2 = pOp->p2;
65263   u.aw.iDb = pOp->p3;
65264   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65265   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65266   u.aw.pDb = &db->aDb[u.aw.iDb];
65267   u.aw.pX = u.aw.pDb->pBt;
65268   assert( u.aw.pX!=0 );
65269   if( pOp->opcode==OP_OpenWrite ){
65270     u.aw.wrFlag = 1;
65271     assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65272     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65273       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65274     }
65275   }else{
65276     u.aw.wrFlag = 0;
65277   }
65278   if( pOp->p5 ){
65279     assert( u.aw.p2>0 );
65280     assert( u.aw.p2<=p->nMem );
65281     pIn2 = &aMem[u.aw.p2];
65282     assert( memIsValid(pIn2) );
65283     assert( (pIn2->flags & MEM_Int)!=0 );
65284     sqlite3VdbeMemIntegerify(pIn2);
65285     u.aw.p2 = (int)pIn2->u.i;
65286     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65287     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65288     ** If there were a failure, the prepared statement would have halted
65289     ** before reaching this instruction. */
65290     if( NEVER(u.aw.p2<2) ) {
65291       rc = SQLITE_CORRUPT_BKPT;
65292       goto abort_due_to_error;
65293     }
65294   }
65295   if( pOp->p4type==P4_KEYINFO ){
65296     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65297     u.aw.pKeyInfo->enc = ENC(p->db);
65298     u.aw.nField = u.aw.pKeyInfo->nField+1;
65299   }else if( pOp->p4type==P4_INT32 ){
65300     u.aw.nField = pOp->p4.i;
65301   }
65302   assert( pOp->p1>=0 );
65303   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65304   if( u.aw.pCur==0 ) goto no_mem;
65305   u.aw.pCur->nullRow = 1;
65306   u.aw.pCur->isOrdered = 1;
65307   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65308   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65309
65310   /* Since it performs no memory allocation or IO, the only values that
65311   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65312   ** SQLITE_EMPTY is only returned when attempting to open the table
65313   ** rooted at page 1 of a zero-byte database.  */
65314   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65315   if( rc==SQLITE_EMPTY ){
65316     u.aw.pCur->pCursor = 0;
65317     rc = SQLITE_OK;
65318   }
65319
65320   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65321   ** SQLite used to check if the root-page flags were sane at this point
65322   ** and report database corruption if they were not, but this check has
65323   ** since moved into the btree layer.  */
65324   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65325   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65326   break;
65327 }
65328
65329 /* Opcode: OpenEphemeral P1 P2 * P4 *
65330 **
65331 ** Open a new cursor P1 to a transient table.
65332 ** The cursor is always opened read/write even if 
65333 ** the main database is read-only.  The ephemeral
65334 ** table is deleted automatically when the cursor is closed.
65335 **
65336 ** P2 is the number of columns in the ephemeral table.
65337 ** The cursor points to a BTree table if P4==0 and to a BTree index
65338 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
65339 ** that defines the format of keys in the index.
65340 **
65341 ** This opcode was once called OpenTemp.  But that created
65342 ** confusion because the term "temp table", might refer either
65343 ** to a TEMP table at the SQL level, or to a table opened by
65344 ** this opcode.  Then this opcode was call OpenVirtual.  But
65345 ** that created confusion with the whole virtual-table idea.
65346 */
65347 /* Opcode: OpenAutoindex P1 P2 * P4 *
65348 **
65349 ** This opcode works the same as OP_OpenEphemeral.  It has a
65350 ** different name to distinguish its use.  Tables created using
65351 ** by this opcode will be used for automatically created transient
65352 ** indices in joins.
65353 */
65354 case OP_OpenAutoindex: 
65355 case OP_OpenEphemeral: {
65356 #if 0  /* local variables moved into u.ax */
65357   VdbeCursor *pCx;
65358 #endif /* local variables moved into u.ax */
65359   static const int vfsFlags =
65360       SQLITE_OPEN_READWRITE |
65361       SQLITE_OPEN_CREATE |
65362       SQLITE_OPEN_EXCLUSIVE |
65363       SQLITE_OPEN_DELETEONCLOSE |
65364       SQLITE_OPEN_TRANSIENT_DB;
65365
65366   assert( pOp->p1>=0 );
65367   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65368   if( u.ax.pCx==0 ) goto no_mem;
65369   u.ax.pCx->nullRow = 1;
65370   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
65371                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65372   if( rc==SQLITE_OK ){
65373     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65374   }
65375   if( rc==SQLITE_OK ){
65376     /* If a transient index is required, create it by calling
65377     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65378     ** opening it. If a transient table is required, just use the
65379     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65380     */
65381     if( pOp->p4.pKeyInfo ){
65382       int pgno;
65383       assert( pOp->p4type==P4_KEYINFO );
65384       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65385       if( rc==SQLITE_OK ){
65386         assert( pgno==MASTER_ROOT+1 );
65387         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65388                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65389         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65390         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65391       }
65392       u.ax.pCx->isTable = 0;
65393     }else{
65394       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65395       u.ax.pCx->isTable = 1;
65396     }
65397   }
65398   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65399   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65400   break;
65401 }
65402
65403 /* Opcode: OpenPseudo P1 P2 P3 * *
65404 **
65405 ** Open a new cursor that points to a fake table that contains a single
65406 ** row of data.  The content of that one row in the content of memory
65407 ** register P2.  In other words, cursor P1 becomes an alias for the 
65408 ** MEM_Blob content contained in register P2.
65409 **
65410 ** A pseudo-table created by this opcode is used to hold a single
65411 ** row output from the sorter so that the row can be decomposed into
65412 ** individual columns using the OP_Column opcode.  The OP_Column opcode
65413 ** is the only cursor opcode that works with a pseudo-table.
65414 **
65415 ** P3 is the number of fields in the records that will be stored by
65416 ** the pseudo-table.
65417 */
65418 case OP_OpenPseudo: {
65419 #if 0  /* local variables moved into u.ay */
65420   VdbeCursor *pCx;
65421 #endif /* local variables moved into u.ay */
65422
65423   assert( pOp->p1>=0 );
65424   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
65425   if( u.ay.pCx==0 ) goto no_mem;
65426   u.ay.pCx->nullRow = 1;
65427   u.ay.pCx->pseudoTableReg = pOp->p2;
65428   u.ay.pCx->isTable = 1;
65429   u.ay.pCx->isIndex = 0;
65430   break;
65431 }
65432
65433 /* Opcode: Close P1 * * * *
65434 **
65435 ** Close a cursor previously opened as P1.  If P1 is not
65436 ** currently open, this instruction is a no-op.
65437 */
65438 case OP_Close: {
65439   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65440   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
65441   p->apCsr[pOp->p1] = 0;
65442   break;
65443 }
65444
65445 /* Opcode: SeekGe P1 P2 P3 P4 *
65446 **
65447 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65448 ** use the value in register P3 as the key.  If cursor P1 refers 
65449 ** to an SQL index, then P3 is the first in an array of P4 registers 
65450 ** that are used as an unpacked index key. 
65451 **
65452 ** Reposition cursor P1 so that  it points to the smallest entry that 
65453 ** is greater than or equal to the key value. If there are no records 
65454 ** greater than or equal to the key and P2 is not zero, then jump to P2.
65455 **
65456 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
65457 */
65458 /* Opcode: SeekGt P1 P2 P3 P4 *
65459 **
65460 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65461 ** use the value in register P3 as a key. If cursor P1 refers 
65462 ** to an SQL index, then P3 is the first in an array of P4 registers 
65463 ** that are used as an unpacked index key. 
65464 **
65465 ** Reposition cursor P1 so that  it points to the smallest entry that 
65466 ** is greater than the key value. If there are no records greater than 
65467 ** the key and P2 is not zero, then jump to P2.
65468 **
65469 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
65470 */
65471 /* Opcode: SeekLt P1 P2 P3 P4 * 
65472 **
65473 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65474 ** use the value in register P3 as a key. If cursor P1 refers 
65475 ** to an SQL index, then P3 is the first in an array of P4 registers 
65476 ** that are used as an unpacked index key. 
65477 **
65478 ** Reposition cursor P1 so that  it points to the largest entry that 
65479 ** is less than the key value. If there are no records less than 
65480 ** the key and P2 is not zero, then jump to P2.
65481 **
65482 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
65483 */
65484 /* Opcode: SeekLe P1 P2 P3 P4 *
65485 **
65486 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
65487 ** use the value in register P3 as a key. If cursor P1 refers 
65488 ** to an SQL index, then P3 is the first in an array of P4 registers 
65489 ** that are used as an unpacked index key. 
65490 **
65491 ** Reposition cursor P1 so that it points to the largest entry that 
65492 ** is less than or equal to the key value. If there are no records 
65493 ** less than or equal to the key and P2 is not zero, then jump to P2.
65494 **
65495 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
65496 */
65497 case OP_SeekLt:         /* jump, in3 */
65498 case OP_SeekLe:         /* jump, in3 */
65499 case OP_SeekGe:         /* jump, in3 */
65500 case OP_SeekGt: {       /* jump, in3 */
65501 #if 0  /* local variables moved into u.az */
65502   int res;
65503   int oc;
65504   VdbeCursor *pC;
65505   UnpackedRecord r;
65506   int nField;
65507   i64 iKey;      /* The rowid we are to seek to */
65508 #endif /* local variables moved into u.az */
65509
65510   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65511   assert( pOp->p2!=0 );
65512   u.az.pC = p->apCsr[pOp->p1];
65513   assert( u.az.pC!=0 );
65514   assert( u.az.pC->pseudoTableReg==0 );
65515   assert( OP_SeekLe == OP_SeekLt+1 );
65516   assert( OP_SeekGe == OP_SeekLt+2 );
65517   assert( OP_SeekGt == OP_SeekLt+3 );
65518   assert( u.az.pC->isOrdered );
65519   if( u.az.pC->pCursor!=0 ){
65520     u.az.oc = pOp->opcode;
65521     u.az.pC->nullRow = 0;
65522     if( u.az.pC->isTable ){
65523       /* The input value in P3 might be of any type: integer, real, string,
65524       ** blob, or NULL.  But it needs to be an integer before we can do
65525       ** the seek, so covert it. */
65526       pIn3 = &aMem[pOp->p3];
65527       applyNumericAffinity(pIn3);
65528       u.az.iKey = sqlite3VdbeIntValue(pIn3);
65529       u.az.pC->rowidIsValid = 0;
65530
65531       /* If the P3 value could not be converted into an integer without
65532       ** loss of information, then special processing is required... */
65533       if( (pIn3->flags & MEM_Int)==0 ){
65534         if( (pIn3->flags & MEM_Real)==0 ){
65535           /* If the P3 value cannot be converted into any kind of a number,
65536           ** then the seek is not possible, so jump to P2 */
65537           pc = pOp->p2 - 1;
65538           break;
65539         }
65540         /* If we reach this point, then the P3 value must be a floating
65541         ** point number. */
65542         assert( (pIn3->flags & MEM_Real)!=0 );
65543
65544         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
65545           /* The P3 value is too large in magnitude to be expressed as an
65546           ** integer. */
65547           u.az.res = 1;
65548           if( pIn3->r<0 ){
65549             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65550               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
65551               if( rc!=SQLITE_OK ) goto abort_due_to_error;
65552             }
65553           }else{
65554             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65555               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
65556               if( rc!=SQLITE_OK ) goto abort_due_to_error;
65557             }
65558           }
65559           if( u.az.res ){
65560             pc = pOp->p2 - 1;
65561           }
65562           break;
65563         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
65564           /* Use the ceiling() function to convert real->int */
65565           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
65566         }else{
65567           /* Use the floor() function to convert real->int */
65568           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
65569           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
65570         }
65571       }
65572       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
65573       if( rc!=SQLITE_OK ){
65574         goto abort_due_to_error;
65575       }
65576       if( u.az.res==0 ){
65577         u.az.pC->rowidIsValid = 1;
65578         u.az.pC->lastRowid = u.az.iKey;
65579       }
65580     }else{
65581       u.az.nField = pOp->p4.i;
65582       assert( pOp->p4type==P4_INT32 );
65583       assert( u.az.nField>0 );
65584       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
65585       u.az.r.nField = (u16)u.az.nField;
65586
65587       /* The next line of code computes as follows, only faster:
65588       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
65589       **     u.az.r.flags = UNPACKED_INCRKEY;
65590       **   }else{
65591       **     u.az.r.flags = 0;
65592       **   }
65593       */
65594       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
65595       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
65596       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
65597       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
65598       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
65599
65600       u.az.r.aMem = &aMem[pOp->p3];
65601 #ifdef SQLITE_DEBUG
65602       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
65603 #endif
65604       ExpandBlob(u.az.r.aMem);
65605       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
65606       if( rc!=SQLITE_OK ){
65607         goto abort_due_to_error;
65608       }
65609       u.az.pC->rowidIsValid = 0;
65610     }
65611     u.az.pC->deferredMoveto = 0;
65612     u.az.pC->cacheStatus = CACHE_STALE;
65613 #ifdef SQLITE_TEST
65614     sqlite3_search_count++;
65615 #endif
65616     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65617       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
65618         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
65619         if( rc!=SQLITE_OK ) goto abort_due_to_error;
65620         u.az.pC->rowidIsValid = 0;
65621       }else{
65622         u.az.res = 0;
65623       }
65624     }else{
65625       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65626       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
65627         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
65628         if( rc!=SQLITE_OK ) goto abort_due_to_error;
65629         u.az.pC->rowidIsValid = 0;
65630       }else{
65631         /* u.az.res might be negative because the table is empty.  Check to
65632         ** see if this is the case.
65633         */
65634         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
65635       }
65636     }
65637     assert( pOp->p2>0 );
65638     if( u.az.res ){
65639       pc = pOp->p2 - 1;
65640     }
65641   }else{
65642     /* This happens when attempting to open the sqlite3_master table
65643     ** for read access returns SQLITE_EMPTY. In this case always
65644     ** take the jump (since there are no records in the table).
65645     */
65646     pc = pOp->p2 - 1;
65647   }
65648   break;
65649 }
65650
65651 /* Opcode: Seek P1 P2 * * *
65652 **
65653 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
65654 ** for P1 to move so that it points to the rowid given by P2.
65655 **
65656 ** This is actually a deferred seek.  Nothing actually happens until
65657 ** the cursor is used to read a record.  That way, if no reads
65658 ** occur, no unnecessary I/O happens.
65659 */
65660 case OP_Seek: {    /* in2 */
65661 #if 0  /* local variables moved into u.ba */
65662   VdbeCursor *pC;
65663 #endif /* local variables moved into u.ba */
65664
65665   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65666   u.ba.pC = p->apCsr[pOp->p1];
65667   assert( u.ba.pC!=0 );
65668   if( ALWAYS(u.ba.pC->pCursor!=0) ){
65669     assert( u.ba.pC->isTable );
65670     u.ba.pC->nullRow = 0;
65671     pIn2 = &aMem[pOp->p2];
65672     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
65673     u.ba.pC->rowidIsValid = 0;
65674     u.ba.pC->deferredMoveto = 1;
65675   }
65676   break;
65677 }
65678   
65679
65680 /* Opcode: Found P1 P2 P3 P4 *
65681 **
65682 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65683 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65684 ** record.
65685 **
65686 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65687 ** is a prefix of any entry in P1 then a jump is made to P2 and
65688 ** P1 is left pointing at the matching entry.
65689 */
65690 /* Opcode: NotFound P1 P2 P3 P4 *
65691 **
65692 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
65693 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65694 ** record.
65695 ** 
65696 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
65697 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
65698 ** does contain an entry whose prefix matches the P3/P4 record then control
65699 ** falls through to the next instruction and P1 is left pointing at the
65700 ** matching entry.
65701 **
65702 ** See also: Found, NotExists, IsUnique
65703 */
65704 case OP_NotFound:       /* jump, in3 */
65705 case OP_Found: {        /* jump, in3 */
65706 #if 0  /* local variables moved into u.bb */
65707   int alreadyExists;
65708   VdbeCursor *pC;
65709   int res;
65710   UnpackedRecord *pIdxKey;
65711   UnpackedRecord r;
65712   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65713 #endif /* local variables moved into u.bb */
65714
65715 #ifdef SQLITE_TEST
65716   sqlite3_found_count++;
65717 #endif
65718
65719   u.bb.alreadyExists = 0;
65720   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65721   assert( pOp->p4type==P4_INT32 );
65722   u.bb.pC = p->apCsr[pOp->p1];
65723   assert( u.bb.pC!=0 );
65724   pIn3 = &aMem[pOp->p3];
65725   if( ALWAYS(u.bb.pC->pCursor!=0) ){
65726
65727     assert( u.bb.pC->isTable==0 );
65728     if( pOp->p4.i>0 ){
65729       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
65730       u.bb.r.nField = (u16)pOp->p4.i;
65731       u.bb.r.aMem = pIn3;
65732 #ifdef SQLITE_DEBUG
65733       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
65734 #endif
65735       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
65736       u.bb.pIdxKey = &u.bb.r;
65737     }else{
65738       assert( pIn3->flags & MEM_Blob );
65739       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
65740       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
65741                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
65742       if( u.bb.pIdxKey==0 ){
65743         goto no_mem;
65744       }
65745       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
65746     }
65747     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
65748     if( pOp->p4.i==0 ){
65749       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
65750     }
65751     if( rc!=SQLITE_OK ){
65752       break;
65753     }
65754     u.bb.alreadyExists = (u.bb.res==0);
65755     u.bb.pC->deferredMoveto = 0;
65756     u.bb.pC->cacheStatus = CACHE_STALE;
65757   }
65758   if( pOp->opcode==OP_Found ){
65759     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
65760   }else{
65761     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
65762   }
65763   break;
65764 }
65765
65766 /* Opcode: IsUnique P1 P2 P3 P4 *
65767 **
65768 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
65769 ** no data and where the key are records generated by OP_MakeRecord with
65770 ** the list field being the integer ROWID of the entry that the index
65771 ** entry refers to.
65772 **
65773 ** The P3 register contains an integer record number. Call this record 
65774 ** number R. Register P4 is the first in a set of N contiguous registers
65775 ** that make up an unpacked index key that can be used with cursor P1.
65776 ** The value of N can be inferred from the cursor. N includes the rowid
65777 ** value appended to the end of the index record. This rowid value may
65778 ** or may not be the same as R.
65779 **
65780 ** If any of the N registers beginning with register P4 contains a NULL
65781 ** value, jump immediately to P2.
65782 **
65783 ** Otherwise, this instruction checks if cursor P1 contains an entry
65784 ** where the first (N-1) fields match but the rowid value at the end
65785 ** of the index entry is not R. If there is no such entry, control jumps
65786 ** to instruction P2. Otherwise, the rowid of the conflicting index
65787 ** entry is copied to register P3 and control falls through to the next
65788 ** instruction.
65789 **
65790 ** See also: NotFound, NotExists, Found
65791 */
65792 case OP_IsUnique: {        /* jump, in3 */
65793 #if 0  /* local variables moved into u.bc */
65794   u16 ii;
65795   VdbeCursor *pCx;
65796   BtCursor *pCrsr;
65797   u16 nField;
65798   Mem *aMx;
65799   UnpackedRecord r;                  /* B-Tree index search key */
65800   i64 R;                             /* Rowid stored in register P3 */
65801 #endif /* local variables moved into u.bc */
65802
65803   pIn3 = &aMem[pOp->p3];
65804   u.bc.aMx = &aMem[pOp->p4.i];
65805   /* Assert that the values of parameters P1 and P4 are in range. */
65806   assert( pOp->p4type==P4_INT32 );
65807   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
65808   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65809
65810   /* Find the index cursor. */
65811   u.bc.pCx = p->apCsr[pOp->p1];
65812   assert( u.bc.pCx->deferredMoveto==0 );
65813   u.bc.pCx->seekResult = 0;
65814   u.bc.pCx->cacheStatus = CACHE_STALE;
65815   u.bc.pCrsr = u.bc.pCx->pCursor;
65816
65817   /* If any of the values are NULL, take the jump. */
65818   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
65819   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
65820     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
65821       pc = pOp->p2 - 1;
65822       u.bc.pCrsr = 0;
65823       break;
65824     }
65825   }
65826   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
65827
65828   if( u.bc.pCrsr!=0 ){
65829     /* Populate the index search key. */
65830     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
65831     u.bc.r.nField = u.bc.nField + 1;
65832     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
65833     u.bc.r.aMem = u.bc.aMx;
65834 #ifdef SQLITE_DEBUG
65835     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
65836 #endif
65837
65838     /* Extract the value of u.bc.R from register P3. */
65839     sqlite3VdbeMemIntegerify(pIn3);
65840     u.bc.R = pIn3->u.i;
65841
65842     /* Search the B-Tree index. If no conflicting record is found, jump
65843     ** to P2. Otherwise, copy the rowid of the conflicting record to
65844     ** register P3 and fall through to the next instruction.  */
65845     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
65846     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
65847       pc = pOp->p2 - 1;
65848     }else{
65849       pIn3->u.i = u.bc.r.rowid;
65850     }
65851   }
65852   break;
65853 }
65854
65855 /* Opcode: NotExists P1 P2 P3 * *
65856 **
65857 ** Use the content of register P3 as a integer key.  If a record 
65858 ** with that key does not exist in table of P1, then jump to P2. 
65859 ** If the record does exist, then fall through.  The cursor is left 
65860 ** pointing to the record if it exists.
65861 **
65862 ** The difference between this operation and NotFound is that this
65863 ** operation assumes the key is an integer and that P1 is a table whereas
65864 ** NotFound assumes key is a blob constructed from MakeRecord and
65865 ** P1 is an index.
65866 **
65867 ** See also: Found, NotFound, IsUnique
65868 */
65869 case OP_NotExists: {        /* jump, in3 */
65870 #if 0  /* local variables moved into u.bd */
65871   VdbeCursor *pC;
65872   BtCursor *pCrsr;
65873   int res;
65874   u64 iKey;
65875 #endif /* local variables moved into u.bd */
65876
65877   pIn3 = &aMem[pOp->p3];
65878   assert( pIn3->flags & MEM_Int );
65879   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65880   u.bd.pC = p->apCsr[pOp->p1];
65881   assert( u.bd.pC!=0 );
65882   assert( u.bd.pC->isTable );
65883   assert( u.bd.pC->pseudoTableReg==0 );
65884   u.bd.pCrsr = u.bd.pC->pCursor;
65885   if( u.bd.pCrsr!=0 ){
65886     u.bd.res = 0;
65887     u.bd.iKey = pIn3->u.i;
65888     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
65889     u.bd.pC->lastRowid = pIn3->u.i;
65890     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
65891     u.bd.pC->nullRow = 0;
65892     u.bd.pC->cacheStatus = CACHE_STALE;
65893     u.bd.pC->deferredMoveto = 0;
65894     if( u.bd.res!=0 ){
65895       pc = pOp->p2 - 1;
65896       assert( u.bd.pC->rowidIsValid==0 );
65897     }
65898     u.bd.pC->seekResult = u.bd.res;
65899   }else{
65900     /* This happens when an attempt to open a read cursor on the
65901     ** sqlite_master table returns SQLITE_EMPTY.
65902     */
65903     pc = pOp->p2 - 1;
65904     assert( u.bd.pC->rowidIsValid==0 );
65905     u.bd.pC->seekResult = 0;
65906   }
65907   break;
65908 }
65909
65910 /* Opcode: Sequence P1 P2 * * *
65911 **
65912 ** Find the next available sequence number for cursor P1.
65913 ** Write the sequence number into register P2.
65914 ** The sequence number on the cursor is incremented after this
65915 ** instruction.  
65916 */
65917 case OP_Sequence: {           /* out2-prerelease */
65918   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65919   assert( p->apCsr[pOp->p1]!=0 );
65920   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
65921   break;
65922 }
65923
65924
65925 /* Opcode: NewRowid P1 P2 P3 * *
65926 **
65927 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
65928 ** The record number is not previously used as a key in the database
65929 ** table that cursor P1 points to.  The new record number is written
65930 ** written to register P2.
65931 **
65932 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
65933 ** the largest previously generated record number. No new record numbers are
65934 ** allowed to be less than this value. When this value reaches its maximum, 
65935 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
65936 ** generated record number. This P3 mechanism is used to help implement the
65937 ** AUTOINCREMENT feature.
65938 */
65939 case OP_NewRowid: {           /* out2-prerelease */
65940 #if 0  /* local variables moved into u.be */
65941   i64 v;                 /* The new rowid */
65942   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65943   int res;               /* Result of an sqlite3BtreeLast() */
65944   int cnt;               /* Counter to limit the number of searches */
65945   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65946   VdbeFrame *pFrame;     /* Root frame of VDBE */
65947 #endif /* local variables moved into u.be */
65948
65949   u.be.v = 0;
65950   u.be.res = 0;
65951   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65952   u.be.pC = p->apCsr[pOp->p1];
65953   assert( u.be.pC!=0 );
65954   if( NEVER(u.be.pC->pCursor==0) ){
65955     /* The zero initialization above is all that is needed */
65956   }else{
65957     /* The next rowid or record number (different terms for the same
65958     ** thing) is obtained in a two-step algorithm.
65959     **
65960     ** First we attempt to find the largest existing rowid and add one
65961     ** to that.  But if the largest existing rowid is already the maximum
65962     ** positive integer, we have to fall through to the second
65963     ** probabilistic algorithm
65964     **
65965     ** The second algorithm is to select a rowid at random and see if
65966     ** it already exists in the table.  If it does not exist, we have
65967     ** succeeded.  If the random rowid does exist, we select a new one
65968     ** and try again, up to 100 times.
65969     */
65970     assert( u.be.pC->isTable );
65971
65972 #ifdef SQLITE_32BIT_ROWID
65973 #   define MAX_ROWID 0x7fffffff
65974 #else
65975     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
65976     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
65977     ** to provide the constant while making all compilers happy.
65978     */
65979 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
65980 #endif
65981
65982     if( !u.be.pC->useRandomRowid ){
65983       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
65984       if( u.be.v==0 ){
65985         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
65986         if( rc!=SQLITE_OK ){
65987           goto abort_due_to_error;
65988         }
65989         if( u.be.res ){
65990           u.be.v = 1;   /* IMP: R-61914-48074 */
65991         }else{
65992           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
65993           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
65994           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
65995           if( u.be.v==MAX_ROWID ){
65996             u.be.pC->useRandomRowid = 1;
65997           }else{
65998             u.be.v++;   /* IMP: R-29538-34987 */
65999           }
66000         }
66001       }
66002
66003 #ifndef SQLITE_OMIT_AUTOINCREMENT
66004       if( pOp->p3 ){
66005         /* Assert that P3 is a valid memory cell. */
66006         assert( pOp->p3>0 );
66007         if( p->pFrame ){
66008           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
66009           /* Assert that P3 is a valid memory cell. */
66010           assert( pOp->p3<=u.be.pFrame->nMem );
66011           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66012         }else{
66013           /* Assert that P3 is a valid memory cell. */
66014           assert( pOp->p3<=p->nMem );
66015           u.be.pMem = &aMem[pOp->p3];
66016           memAboutToChange(p, u.be.pMem);
66017         }
66018         assert( memIsValid(u.be.pMem) );
66019
66020         REGISTER_TRACE(pOp->p3, u.be.pMem);
66021         sqlite3VdbeMemIntegerify(u.be.pMem);
66022         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
66023         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66024           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
66025           goto abort_due_to_error;
66026         }
66027         if( u.be.v<u.be.pMem->u.i+1 ){
66028           u.be.v = u.be.pMem->u.i + 1;
66029         }
66030         u.be.pMem->u.i = u.be.v;
66031       }
66032 #endif
66033
66034       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66035     }
66036     if( u.be.pC->useRandomRowid ){
66037       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66038       ** largest possible integer (9223372036854775807) then the database
66039       ** engine starts picking positive candidate ROWIDs at random until
66040       ** it finds one that is not previously used. */
66041       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
66042                              ** an AUTOINCREMENT table. */
66043       /* on the first attempt, simply do one more than previous */
66044       u.be.v = db->lastRowid;
66045       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66046       u.be.v++; /* ensure non-zero */
66047       u.be.cnt = 0;
66048       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66049                                                  0, &u.be.res))==SQLITE_OK)
66050             && (u.be.res==0)
66051             && (++u.be.cnt<100)){
66052         /* collision - try another random rowid */
66053         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66054         if( u.be.cnt<5 ){
66055           /* try "small" random rowids for the initial attempts */
66056           u.be.v &= 0xffffff;
66057         }else{
66058           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66059         }
66060         u.be.v++; /* ensure non-zero */
66061       }
66062       if( rc==SQLITE_OK && u.be.res==0 ){
66063         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
66064         goto abort_due_to_error;
66065       }
66066       assert( u.be.v>0 );  /* EV: R-40812-03570 */
66067     }
66068     u.be.pC->rowidIsValid = 0;
66069     u.be.pC->deferredMoveto = 0;
66070     u.be.pC->cacheStatus = CACHE_STALE;
66071   }
66072   pOut->u.i = u.be.v;
66073   break;
66074 }
66075
66076 /* Opcode: Insert P1 P2 P3 P4 P5
66077 **
66078 ** Write an entry into the table of cursor P1.  A new entry is
66079 ** created if it doesn't already exist or the data for an existing
66080 ** entry is overwritten.  The data is the value MEM_Blob stored in register
66081 ** number P2. The key is stored in register P3. The key must
66082 ** be a MEM_Int.
66083 **
66084 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66085 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
66086 ** then rowid is stored for subsequent return by the
66087 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66088 **
66089 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66090 ** the last seek operation (OP_NotExists) was a success, then this
66091 ** operation will not attempt to find the appropriate row before doing
66092 ** the insert but will instead overwrite the row that the cursor is
66093 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
66094 ** has already positioned the cursor correctly.  This is an optimization
66095 ** that boosts performance by avoiding redundant seeks.
66096 **
66097 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66098 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
66099 ** is part of an INSERT operation.  The difference is only important to
66100 ** the update hook.
66101 **
66102 ** Parameter P4 may point to a string containing the table-name, or
66103 ** may be NULL. If it is not NULL, then the update-hook 
66104 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66105 **
66106 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66107 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
66108 ** and register P2 becomes ephemeral.  If the cursor is changed, the
66109 ** value of register P2 will then change.  Make sure this does not
66110 ** cause any problems.)
66111 **
66112 ** This instruction only works on tables.  The equivalent instruction
66113 ** for indices is OP_IdxInsert.
66114 */
66115 /* Opcode: InsertInt P1 P2 P3 P4 P5
66116 **
66117 ** This works exactly like OP_Insert except that the key is the
66118 ** integer value P3, not the value of the integer stored in register P3.
66119 */
66120 case OP_Insert: 
66121 case OP_InsertInt: {
66122 #if 0  /* local variables moved into u.bf */
66123   Mem *pData;       /* MEM cell holding data for the record to be inserted */
66124   Mem *pKey;        /* MEM cell holding key  for the record */
66125   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
66126   VdbeCursor *pC;   /* Cursor to table into which insert is written */
66127   int nZero;        /* Number of zero-bytes to append */
66128   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
66129   const char *zDb;  /* database name - used by the update hook */
66130   const char *zTbl; /* Table name - used by the opdate hook */
66131   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66132 #endif /* local variables moved into u.bf */
66133
66134   u.bf.pData = &aMem[pOp->p2];
66135   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66136   assert( memIsValid(u.bf.pData) );
66137   u.bf.pC = p->apCsr[pOp->p1];
66138   assert( u.bf.pC!=0 );
66139   assert( u.bf.pC->pCursor!=0 );
66140   assert( u.bf.pC->pseudoTableReg==0 );
66141   assert( u.bf.pC->isTable );
66142   REGISTER_TRACE(pOp->p2, u.bf.pData);
66143
66144   if( pOp->opcode==OP_Insert ){
66145     u.bf.pKey = &aMem[pOp->p3];
66146     assert( u.bf.pKey->flags & MEM_Int );
66147     assert( memIsValid(u.bf.pKey) );
66148     REGISTER_TRACE(pOp->p3, u.bf.pKey);
66149     u.bf.iKey = u.bf.pKey->u.i;
66150   }else{
66151     assert( pOp->opcode==OP_InsertInt );
66152     u.bf.iKey = pOp->p3;
66153   }
66154
66155   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66156   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
66157   if( u.bf.pData->flags & MEM_Null ){
66158     u.bf.pData->z = 0;
66159     u.bf.pData->n = 0;
66160   }else{
66161     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66162   }
66163   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66164   if( u.bf.pData->flags & MEM_Zero ){
66165     u.bf.nZero = u.bf.pData->u.nZero;
66166   }else{
66167     u.bf.nZero = 0;
66168   }
66169   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66170   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66171                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66172                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66173   );
66174   u.bf.pC->rowidIsValid = 0;
66175   u.bf.pC->deferredMoveto = 0;
66176   u.bf.pC->cacheStatus = CACHE_STALE;
66177
66178   /* Invoke the update-hook if required. */
66179   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66180     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66181     u.bf.zTbl = pOp->p4.z;
66182     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66183     assert( u.bf.pC->isTable );
66184     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66185     assert( u.bf.pC->iDb>=0 );
66186   }
66187   break;
66188 }
66189
66190 /* Opcode: Delete P1 P2 * P4 *
66191 **
66192 ** Delete the record at which the P1 cursor is currently pointing.
66193 **
66194 ** The cursor will be left pointing at either the next or the previous
66195 ** record in the table. If it is left pointing at the next record, then
66196 ** the next Next instruction will be a no-op.  Hence it is OK to delete
66197 ** a record from within an Next loop.
66198 **
66199 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66200 ** incremented (otherwise not).
66201 **
66202 ** P1 must not be pseudo-table.  It has to be a real table with
66203 ** multiple rows.
66204 **
66205 ** If P4 is not NULL, then it is the name of the table that P1 is
66206 ** pointing to.  The update hook will be invoked, if it exists.
66207 ** If P4 is not NULL then the P1 cursor must have been positioned
66208 ** using OP_NotFound prior to invoking this opcode.
66209 */
66210 case OP_Delete: {
66211 #if 0  /* local variables moved into u.bg */
66212   i64 iKey;
66213   VdbeCursor *pC;
66214 #endif /* local variables moved into u.bg */
66215
66216   u.bg.iKey = 0;
66217   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66218   u.bg.pC = p->apCsr[pOp->p1];
66219   assert( u.bg.pC!=0 );
66220   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
66221
66222   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66223   ** row being deleted.
66224   */
66225   if( db->xUpdateCallback && pOp->p4.z ){
66226     assert( u.bg.pC->isTable );
66227     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
66228     u.bg.iKey = u.bg.pC->lastRowid;
66229   }
66230
66231   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66232   ** OP_Column on the same table without any intervening operations that
66233   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
66234   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66235   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
66236   ** to guard against future changes to the code generator.
66237   **/
66238   assert( u.bg.pC->deferredMoveto==0 );
66239   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66240   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66241
66242   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66243   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66244   u.bg.pC->cacheStatus = CACHE_STALE;
66245
66246   /* Invoke the update-hook if required. */
66247   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66248     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66249     const char *zTbl = pOp->p4.z;
66250     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66251     assert( u.bg.pC->iDb>=0 );
66252   }
66253   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66254   break;
66255 }
66256 /* Opcode: ResetCount * * * * *
66257 **
66258 ** The value of the change counter is copied to the database handle
66259 ** change counter (returned by subsequent calls to sqlite3_changes()).
66260 ** Then the VMs internal change counter resets to 0.
66261 ** This is used by trigger programs.
66262 */
66263 case OP_ResetCount: {
66264   sqlite3VdbeSetChanges(db, p->nChange);
66265   p->nChange = 0;
66266   break;
66267 }
66268
66269 /* Opcode: RowData P1 P2 * * *
66270 **
66271 ** Write into register P2 the complete row data for cursor P1.
66272 ** There is no interpretation of the data.  
66273 ** It is just copied onto the P2 register exactly as 
66274 ** it is found in the database file.
66275 **
66276 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66277 ** of a real table, not a pseudo-table.
66278 */
66279 /* Opcode: RowKey P1 P2 * * *
66280 **
66281 ** Write into register P2 the complete row key for cursor P1.
66282 ** There is no interpretation of the data.  
66283 ** The key is copied onto the P3 register exactly as 
66284 ** it is found in the database file.
66285 **
66286 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66287 ** of a real table, not a pseudo-table.
66288 */
66289 case OP_RowKey:
66290 case OP_RowData: {
66291 #if 0  /* local variables moved into u.bh */
66292   VdbeCursor *pC;
66293   BtCursor *pCrsr;
66294   u32 n;
66295   i64 n64;
66296 #endif /* local variables moved into u.bh */
66297
66298   pOut = &aMem[pOp->p2];
66299   memAboutToChange(p, pOut);
66300
66301   /* Note that RowKey and RowData are really exactly the same instruction */
66302   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66303   u.bh.pC = p->apCsr[pOp->p1];
66304   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66305   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66306   assert( u.bh.pC!=0 );
66307   assert( u.bh.pC->nullRow==0 );
66308   assert( u.bh.pC->pseudoTableReg==0 );
66309   assert( u.bh.pC->pCursor!=0 );
66310   u.bh.pCrsr = u.bh.pC->pCursor;
66311   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66312
66313   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66314   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66315   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
66316   ** a no-op and can never fail.  But we leave it in place as a safety.
66317   */
66318   assert( u.bh.pC->deferredMoveto==0 );
66319   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66320   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66321
66322   if( u.bh.pC->isIndex ){
66323     assert( !u.bh.pC->isTable );
66324     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66325     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
66326     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66327       goto too_big;
66328     }
66329     u.bh.n = (u32)u.bh.n64;
66330   }else{
66331     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66332     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
66333     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66334       goto too_big;
66335     }
66336   }
66337   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66338     goto no_mem;
66339   }
66340   pOut->n = u.bh.n;
66341   MemSetTypeFlag(pOut, MEM_Blob);
66342   if( u.bh.pC->isIndex ){
66343     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66344   }else{
66345     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66346   }
66347   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
66348   UPDATE_MAX_BLOBSIZE(pOut);
66349   break;
66350 }
66351
66352 /* Opcode: Rowid P1 P2 * * *
66353 **
66354 ** Store in register P2 an integer which is the key of the table entry that
66355 ** P1 is currently point to.
66356 **
66357 ** P1 can be either an ordinary table or a virtual table.  There used to
66358 ** be a separate OP_VRowid opcode for use with virtual tables, but this
66359 ** one opcode now works for both table types.
66360 */
66361 case OP_Rowid: {                 /* out2-prerelease */
66362 #if 0  /* local variables moved into u.bi */
66363   VdbeCursor *pC;
66364   i64 v;
66365   sqlite3_vtab *pVtab;
66366   const sqlite3_module *pModule;
66367 #endif /* local variables moved into u.bi */
66368
66369   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66370   u.bi.pC = p->apCsr[pOp->p1];
66371   assert( u.bi.pC!=0 );
66372   assert( u.bi.pC->pseudoTableReg==0 );
66373   if( u.bi.pC->nullRow ){
66374     pOut->flags = MEM_Null;
66375     break;
66376   }else if( u.bi.pC->deferredMoveto ){
66377     u.bi.v = u.bi.pC->movetoTarget;
66378 #ifndef SQLITE_OMIT_VIRTUALTABLE
66379   }else if( u.bi.pC->pVtabCursor ){
66380     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66381     u.bi.pModule = u.bi.pVtab->pModule;
66382     assert( u.bi.pModule->xRowid );
66383     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66384     importVtabErrMsg(p, u.bi.pVtab);
66385 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66386   }else{
66387     assert( u.bi.pC->pCursor!=0 );
66388     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66389     if( rc ) goto abort_due_to_error;
66390     if( u.bi.pC->rowidIsValid ){
66391       u.bi.v = u.bi.pC->lastRowid;
66392     }else{
66393       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66394       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
66395     }
66396   }
66397   pOut->u.i = u.bi.v;
66398   break;
66399 }
66400
66401 /* Opcode: NullRow P1 * * * *
66402 **
66403 ** Move the cursor P1 to a null row.  Any OP_Column operations
66404 ** that occur while the cursor is on the null row will always
66405 ** write a NULL.
66406 */
66407 case OP_NullRow: {
66408 #if 0  /* local variables moved into u.bj */
66409   VdbeCursor *pC;
66410 #endif /* local variables moved into u.bj */
66411
66412   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66413   u.bj.pC = p->apCsr[pOp->p1];
66414   assert( u.bj.pC!=0 );
66415   u.bj.pC->nullRow = 1;
66416   u.bj.pC->rowidIsValid = 0;
66417   if( u.bj.pC->pCursor ){
66418     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
66419   }
66420   break;
66421 }
66422
66423 /* Opcode: Last P1 P2 * * *
66424 **
66425 ** The next use of the Rowid or Column or Next instruction for P1 
66426 ** will refer to the last entry in the database table or index.
66427 ** If the table or index is empty and P2>0, then jump immediately to P2.
66428 ** If P2 is 0 or if the table or index is not empty, fall through
66429 ** to the following instruction.
66430 */
66431 case OP_Last: {        /* jump */
66432 #if 0  /* local variables moved into u.bk */
66433   VdbeCursor *pC;
66434   BtCursor *pCrsr;
66435   int res;
66436 #endif /* local variables moved into u.bk */
66437
66438   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66439   u.bk.pC = p->apCsr[pOp->p1];
66440   assert( u.bk.pC!=0 );
66441   u.bk.pCrsr = u.bk.pC->pCursor;
66442   if( u.bk.pCrsr==0 ){
66443     u.bk.res = 1;
66444   }else{
66445     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
66446   }
66447   u.bk.pC->nullRow = (u8)u.bk.res;
66448   u.bk.pC->deferredMoveto = 0;
66449   u.bk.pC->rowidIsValid = 0;
66450   u.bk.pC->cacheStatus = CACHE_STALE;
66451   if( pOp->p2>0 && u.bk.res ){
66452     pc = pOp->p2 - 1;
66453   }
66454   break;
66455 }
66456
66457
66458 /* Opcode: Sort P1 P2 * * *
66459 **
66460 ** This opcode does exactly the same thing as OP_Rewind except that
66461 ** it increments an undocumented global variable used for testing.
66462 **
66463 ** Sorting is accomplished by writing records into a sorting index,
66464 ** then rewinding that index and playing it back from beginning to
66465 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
66466 ** rewinding so that the global variable will be incremented and
66467 ** regression tests can determine whether or not the optimizer is
66468 ** correctly optimizing out sorts.
66469 */
66470 case OP_Sort: {        /* jump */
66471 #ifdef SQLITE_TEST
66472   sqlite3_sort_count++;
66473   sqlite3_search_count--;
66474 #endif
66475   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
66476   /* Fall through into OP_Rewind */
66477 }
66478 /* Opcode: Rewind P1 P2 * * *
66479 **
66480 ** The next use of the Rowid or Column or Next instruction for P1 
66481 ** will refer to the first entry in the database table or index.
66482 ** If the table or index is empty and P2>0, then jump immediately to P2.
66483 ** If P2 is 0 or if the table or index is not empty, fall through
66484 ** to the following instruction.
66485 */
66486 case OP_Rewind: {        /* jump */
66487 #if 0  /* local variables moved into u.bl */
66488   VdbeCursor *pC;
66489   BtCursor *pCrsr;
66490   int res;
66491 #endif /* local variables moved into u.bl */
66492
66493   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66494   u.bl.pC = p->apCsr[pOp->p1];
66495   assert( u.bl.pC!=0 );
66496   u.bl.res = 1;
66497   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
66498     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
66499     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
66500     u.bl.pC->deferredMoveto = 0;
66501     u.bl.pC->cacheStatus = CACHE_STALE;
66502     u.bl.pC->rowidIsValid = 0;
66503   }
66504   u.bl.pC->nullRow = (u8)u.bl.res;
66505   assert( pOp->p2>0 && pOp->p2<p->nOp );
66506   if( u.bl.res ){
66507     pc = pOp->p2 - 1;
66508   }
66509   break;
66510 }
66511
66512 /* Opcode: Next P1 P2 * * P5
66513 **
66514 ** Advance cursor P1 so that it points to the next key/data pair in its
66515 ** table or index.  If there are no more key/value pairs then fall through
66516 ** to the following instruction.  But if the cursor advance was successful,
66517 ** jump immediately to P2.
66518 **
66519 ** The P1 cursor must be for a real table, not a pseudo-table.
66520 **
66521 ** If P5 is positive and the jump is taken, then event counter
66522 ** number P5-1 in the prepared statement is incremented.
66523 **
66524 ** See also: Prev
66525 */
66526 /* Opcode: Prev P1 P2 * * P5
66527 **
66528 ** Back up cursor P1 so that it points to the previous key/data pair in its
66529 ** table or index.  If there is no previous key/value pairs then fall through
66530 ** to the following instruction.  But if the cursor backup was successful,
66531 ** jump immediately to P2.
66532 **
66533 ** The P1 cursor must be for a real table, not a pseudo-table.
66534 **
66535 ** If P5 is positive and the jump is taken, then event counter
66536 ** number P5-1 in the prepared statement is incremented.
66537 */
66538 case OP_Prev:          /* jump */
66539 case OP_Next: {        /* jump */
66540 #if 0  /* local variables moved into u.bm */
66541   VdbeCursor *pC;
66542   BtCursor *pCrsr;
66543   int res;
66544 #endif /* local variables moved into u.bm */
66545
66546   CHECK_FOR_INTERRUPT;
66547   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66548   assert( pOp->p5<=ArraySize(p->aCounter) );
66549   u.bm.pC = p->apCsr[pOp->p1];
66550   if( u.bm.pC==0 ){
66551     break;  /* See ticket #2273 */
66552   }
66553   u.bm.pCrsr = u.bm.pC->pCursor;
66554   if( u.bm.pCrsr==0 ){
66555     u.bm.pC->nullRow = 1;
66556     break;
66557   }
66558   u.bm.res = 1;
66559   assert( u.bm.pC->deferredMoveto==0 );
66560   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
66561                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
66562   u.bm.pC->nullRow = (u8)u.bm.res;
66563   u.bm.pC->cacheStatus = CACHE_STALE;
66564   if( u.bm.res==0 ){
66565     pc = pOp->p2 - 1;
66566     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
66567 #ifdef SQLITE_TEST
66568     sqlite3_search_count++;
66569 #endif
66570   }
66571   u.bm.pC->rowidIsValid = 0;
66572   break;
66573 }
66574
66575 /* Opcode: IdxInsert P1 P2 P3 * P5
66576 **
66577 ** Register P2 holds a SQL index key made using the
66578 ** MakeRecord instructions.  This opcode writes that key
66579 ** into the index P1.  Data for the entry is nil.
66580 **
66581 ** P3 is a flag that provides a hint to the b-tree layer that this
66582 ** insert is likely to be an append.
66583 **
66584 ** This instruction only works for indices.  The equivalent instruction
66585 ** for tables is OP_Insert.
66586 */
66587 case OP_IdxInsert: {        /* in2 */
66588 #if 0  /* local variables moved into u.bn */
66589   VdbeCursor *pC;
66590   BtCursor *pCrsr;
66591   int nKey;
66592   const char *zKey;
66593 #endif /* local variables moved into u.bn */
66594
66595   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66596   u.bn.pC = p->apCsr[pOp->p1];
66597   assert( u.bn.pC!=0 );
66598   pIn2 = &aMem[pOp->p2];
66599   assert( pIn2->flags & MEM_Blob );
66600   u.bn.pCrsr = u.bn.pC->pCursor;
66601   if( ALWAYS(u.bn.pCrsr!=0) ){
66602     assert( u.bn.pC->isTable==0 );
66603     rc = ExpandBlob(pIn2);
66604     if( rc==SQLITE_OK ){
66605       u.bn.nKey = pIn2->n;
66606       u.bn.zKey = pIn2->z;
66607       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
66608           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
66609       );
66610       assert( u.bn.pC->deferredMoveto==0 );
66611       u.bn.pC->cacheStatus = CACHE_STALE;
66612     }
66613   }
66614   break;
66615 }
66616
66617 /* Opcode: IdxDelete P1 P2 P3 * *
66618 **
66619 ** The content of P3 registers starting at register P2 form
66620 ** an unpacked index key. This opcode removes that entry from the 
66621 ** index opened by cursor P1.
66622 */
66623 case OP_IdxDelete: {
66624 #if 0  /* local variables moved into u.bo */
66625   VdbeCursor *pC;
66626   BtCursor *pCrsr;
66627   int res;
66628   UnpackedRecord r;
66629 #endif /* local variables moved into u.bo */
66630
66631   assert( pOp->p3>0 );
66632   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
66633   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66634   u.bo.pC = p->apCsr[pOp->p1];
66635   assert( u.bo.pC!=0 );
66636   u.bo.pCrsr = u.bo.pC->pCursor;
66637   if( ALWAYS(u.bo.pCrsr!=0) ){
66638     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
66639     u.bo.r.nField = (u16)pOp->p3;
66640     u.bo.r.flags = 0;
66641     u.bo.r.aMem = &aMem[pOp->p2];
66642 #ifdef SQLITE_DEBUG
66643     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
66644 #endif
66645     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
66646     if( rc==SQLITE_OK && u.bo.res==0 ){
66647       rc = sqlite3BtreeDelete(u.bo.pCrsr);
66648     }
66649     assert( u.bo.pC->deferredMoveto==0 );
66650     u.bo.pC->cacheStatus = CACHE_STALE;
66651   }
66652   break;
66653 }
66654
66655 /* Opcode: IdxRowid P1 P2 * * *
66656 **
66657 ** Write into register P2 an integer which is the last entry in the record at
66658 ** the end of the index key pointed to by cursor P1.  This integer should be
66659 ** the rowid of the table entry to which this index entry points.
66660 **
66661 ** See also: Rowid, MakeRecord.
66662 */
66663 case OP_IdxRowid: {              /* out2-prerelease */
66664 #if 0  /* local variables moved into u.bp */
66665   BtCursor *pCrsr;
66666   VdbeCursor *pC;
66667   i64 rowid;
66668 #endif /* local variables moved into u.bp */
66669
66670   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66671   u.bp.pC = p->apCsr[pOp->p1];
66672   assert( u.bp.pC!=0 );
66673   u.bp.pCrsr = u.bp.pC->pCursor;
66674   pOut->flags = MEM_Null;
66675   if( ALWAYS(u.bp.pCrsr!=0) ){
66676     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
66677     if( NEVER(rc) ) goto abort_due_to_error;
66678     assert( u.bp.pC->deferredMoveto==0 );
66679     assert( u.bp.pC->isTable==0 );
66680     if( !u.bp.pC->nullRow ){
66681       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
66682       if( rc!=SQLITE_OK ){
66683         goto abort_due_to_error;
66684       }
66685       pOut->u.i = u.bp.rowid;
66686       pOut->flags = MEM_Int;
66687     }
66688   }
66689   break;
66690 }
66691
66692 /* Opcode: IdxGE P1 P2 P3 P4 P5
66693 **
66694 ** The P4 register values beginning with P3 form an unpacked index 
66695 ** key that omits the ROWID.  Compare this key value against the index 
66696 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66697 **
66698 ** If the P1 index entry is greater than or equal to the key value
66699 ** then jump to P2.  Otherwise fall through to the next instruction.
66700 **
66701 ** If P5 is non-zero then the key value is increased by an epsilon 
66702 ** prior to the comparison.  This make the opcode work like IdxGT except
66703 ** that if the key from register P3 is a prefix of the key in the cursor,
66704 ** the result is false whereas it would be true with IdxGT.
66705 */
66706 /* Opcode: IdxLT P1 P2 P3 P4 P5
66707 **
66708 ** The P4 register values beginning with P3 form an unpacked index 
66709 ** key that omits the ROWID.  Compare this key value against the index 
66710 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
66711 **
66712 ** If the P1 index entry is less than the key value then jump to P2.
66713 ** Otherwise fall through to the next instruction.
66714 **
66715 ** If P5 is non-zero then the key value is increased by an epsilon prior 
66716 ** to the comparison.  This makes the opcode work like IdxLE.
66717 */
66718 case OP_IdxLT:          /* jump */
66719 case OP_IdxGE: {        /* jump */
66720 #if 0  /* local variables moved into u.bq */
66721   VdbeCursor *pC;
66722   int res;
66723   UnpackedRecord r;
66724 #endif /* local variables moved into u.bq */
66725
66726   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66727   u.bq.pC = p->apCsr[pOp->p1];
66728   assert( u.bq.pC!=0 );
66729   assert( u.bq.pC->isOrdered );
66730   if( ALWAYS(u.bq.pC->pCursor!=0) ){
66731     assert( u.bq.pC->deferredMoveto==0 );
66732     assert( pOp->p5==0 || pOp->p5==1 );
66733     assert( pOp->p4type==P4_INT32 );
66734     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
66735     u.bq.r.nField = (u16)pOp->p4.i;
66736     if( pOp->p5 ){
66737       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
66738     }else{
66739       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
66740     }
66741     u.bq.r.aMem = &aMem[pOp->p3];
66742 #ifdef SQLITE_DEBUG
66743     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
66744 #endif
66745     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
66746     if( pOp->opcode==OP_IdxLT ){
66747       u.bq.res = -u.bq.res;
66748     }else{
66749       assert( pOp->opcode==OP_IdxGE );
66750       u.bq.res++;
66751     }
66752     if( u.bq.res>0 ){
66753       pc = pOp->p2 - 1 ;
66754     }
66755   }
66756   break;
66757 }
66758
66759 /* Opcode: Destroy P1 P2 P3 * *
66760 **
66761 ** Delete an entire database table or index whose root page in the database
66762 ** file is given by P1.
66763 **
66764 ** The table being destroyed is in the main database file if P3==0.  If
66765 ** P3==1 then the table to be clear is in the auxiliary database file
66766 ** that is used to store tables create using CREATE TEMPORARY TABLE.
66767 **
66768 ** If AUTOVACUUM is enabled then it is possible that another root page
66769 ** might be moved into the newly deleted root page in order to keep all
66770 ** root pages contiguous at the beginning of the database.  The former
66771 ** value of the root page that moved - its value before the move occurred -
66772 ** is stored in register P2.  If no page 
66773 ** movement was required (because the table being dropped was already 
66774 ** the last one in the database) then a zero is stored in register P2.
66775 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
66776 **
66777 ** See also: Clear
66778 */
66779 case OP_Destroy: {     /* out2-prerelease */
66780 #if 0  /* local variables moved into u.br */
66781   int iMoved;
66782   int iCnt;
66783   Vdbe *pVdbe;
66784   int iDb;
66785 #endif /* local variables moved into u.br */
66786 #ifndef SQLITE_OMIT_VIRTUALTABLE
66787   u.br.iCnt = 0;
66788   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
66789     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
66790       u.br.iCnt++;
66791     }
66792   }
66793 #else
66794   u.br.iCnt = db->activeVdbeCnt;
66795 #endif
66796   pOut->flags = MEM_Null;
66797   if( u.br.iCnt>1 ){
66798     rc = SQLITE_LOCKED;
66799     p->errorAction = OE_Abort;
66800   }else{
66801     u.br.iDb = pOp->p3;
66802     assert( u.br.iCnt==1 );
66803     assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
66804     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
66805     pOut->flags = MEM_Int;
66806     pOut->u.i = u.br.iMoved;
66807 #ifndef SQLITE_OMIT_AUTOVACUUM
66808     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
66809       sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
66810       /* All OP_Destroy operations occur on the same btree */
66811       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
66812       resetSchemaOnFault = u.br.iDb+1;
66813     }
66814 #endif
66815   }
66816   break;
66817 }
66818
66819 /* Opcode: Clear P1 P2 P3
66820 **
66821 ** Delete all contents of the database table or index whose root page
66822 ** in the database file is given by P1.  But, unlike Destroy, do not
66823 ** remove the table or index from the database file.
66824 **
66825 ** The table being clear is in the main database file if P2==0.  If
66826 ** P2==1 then the table to be clear is in the auxiliary database file
66827 ** that is used to store tables create using CREATE TEMPORARY TABLE.
66828 **
66829 ** If the P3 value is non-zero, then the table referred to must be an
66830 ** intkey table (an SQL table, not an index). In this case the row change 
66831 ** count is incremented by the number of rows in the table being cleared. 
66832 ** If P3 is greater than zero, then the value stored in register P3 is
66833 ** also incremented by the number of rows in the table being cleared.
66834 **
66835 ** See also: Destroy
66836 */
66837 case OP_Clear: {
66838 #if 0  /* local variables moved into u.bs */
66839   int nChange;
66840 #endif /* local variables moved into u.bs */
66841
66842   u.bs.nChange = 0;
66843   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
66844   rc = sqlite3BtreeClearTable(
66845       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
66846   );
66847   if( pOp->p3 ){
66848     p->nChange += u.bs.nChange;
66849     if( pOp->p3>0 ){
66850       assert( memIsValid(&aMem[pOp->p3]) );
66851       memAboutToChange(p, &aMem[pOp->p3]);
66852       aMem[pOp->p3].u.i += u.bs.nChange;
66853     }
66854   }
66855   break;
66856 }
66857
66858 /* Opcode: CreateTable P1 P2 * * *
66859 **
66860 ** Allocate a new table in the main database file if P1==0 or in the
66861 ** auxiliary database file if P1==1 or in an attached database if
66862 ** P1>1.  Write the root page number of the new table into
66863 ** register P2
66864 **
66865 ** The difference between a table and an index is this:  A table must
66866 ** have a 4-byte integer key and can have arbitrary data.  An index
66867 ** has an arbitrary key but no data.
66868 **
66869 ** See also: CreateIndex
66870 */
66871 /* Opcode: CreateIndex P1 P2 * * *
66872 **
66873 ** Allocate a new index in the main database file if P1==0 or in the
66874 ** auxiliary database file if P1==1 or in an attached database if
66875 ** P1>1.  Write the root page number of the new table into
66876 ** register P2.
66877 **
66878 ** See documentation on OP_CreateTable for additional information.
66879 */
66880 case OP_CreateIndex:            /* out2-prerelease */
66881 case OP_CreateTable: {          /* out2-prerelease */
66882 #if 0  /* local variables moved into u.bt */
66883   int pgno;
66884   int flags;
66885   Db *pDb;
66886 #endif /* local variables moved into u.bt */
66887
66888   u.bt.pgno = 0;
66889   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66890   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66891   u.bt.pDb = &db->aDb[pOp->p1];
66892   assert( u.bt.pDb->pBt!=0 );
66893   if( pOp->opcode==OP_CreateTable ){
66894     /* u.bt.flags = BTREE_INTKEY; */
66895     u.bt.flags = BTREE_INTKEY;
66896   }else{
66897     u.bt.flags = BTREE_BLOBKEY;
66898   }
66899   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
66900   pOut->u.i = u.bt.pgno;
66901   break;
66902 }
66903
66904 /* Opcode: ParseSchema P1 * * P4 *
66905 **
66906 ** Read and parse all entries from the SQLITE_MASTER table of database P1
66907 ** that match the WHERE clause P4. 
66908 **
66909 ** This opcode invokes the parser to create a new virtual machine,
66910 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
66911 */
66912 case OP_ParseSchema: {
66913 #if 0  /* local variables moved into u.bu */
66914   int iDb;
66915   const char *zMaster;
66916   char *zSql;
66917   InitData initData;
66918 #endif /* local variables moved into u.bu */
66919
66920   /* Any prepared statement that invokes this opcode will hold mutexes
66921   ** on every btree.  This is a prerequisite for invoking
66922   ** sqlite3InitCallback().
66923   */
66924 #ifdef SQLITE_DEBUG
66925   for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
66926     assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
66927   }
66928 #endif
66929
66930   u.bu.iDb = pOp->p1;
66931   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
66932   assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
66933   /* Used to be a conditional */ {
66934     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
66935     u.bu.initData.db = db;
66936     u.bu.initData.iDb = pOp->p1;
66937     u.bu.initData.pzErrMsg = &p->zErrMsg;
66938     u.bu.zSql = sqlite3MPrintf(db,
66939        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
66940        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
66941     if( u.bu.zSql==0 ){
66942       rc = SQLITE_NOMEM;
66943     }else{
66944       assert( db->init.busy==0 );
66945       db->init.busy = 1;
66946       u.bu.initData.rc = SQLITE_OK;
66947       assert( !db->mallocFailed );
66948       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
66949       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
66950       sqlite3DbFree(db, u.bu.zSql);
66951       db->init.busy = 0;
66952     }
66953   }
66954   if( rc==SQLITE_NOMEM ){
66955     goto no_mem;
66956   }
66957   break;
66958 }
66959
66960 #if !defined(SQLITE_OMIT_ANALYZE)
66961 /* Opcode: LoadAnalysis P1 * * * *
66962 **
66963 ** Read the sqlite_stat1 table for database P1 and load the content
66964 ** of that table into the internal index hash table.  This will cause
66965 ** the analysis to be used when preparing all subsequent queries.
66966 */
66967 case OP_LoadAnalysis: {
66968   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66969   rc = sqlite3AnalysisLoad(db, pOp->p1);
66970   break;  
66971 }
66972 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
66973
66974 /* Opcode: DropTable P1 * * P4 *
66975 **
66976 ** Remove the internal (in-memory) data structures that describe
66977 ** the table named P4 in database P1.  This is called after a table
66978 ** is dropped in order to keep the internal representation of the
66979 ** schema consistent with what is on disk.
66980 */
66981 case OP_DropTable: {
66982   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
66983   break;
66984 }
66985
66986 /* Opcode: DropIndex P1 * * P4 *
66987 **
66988 ** Remove the internal (in-memory) data structures that describe
66989 ** the index named P4 in database P1.  This is called after an index
66990 ** is dropped in order to keep the internal representation of the
66991 ** schema consistent with what is on disk.
66992 */
66993 case OP_DropIndex: {
66994   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
66995   break;
66996 }
66997
66998 /* Opcode: DropTrigger P1 * * P4 *
66999 **
67000 ** Remove the internal (in-memory) data structures that describe
67001 ** the trigger named P4 in database P1.  This is called after a trigger
67002 ** is dropped in order to keep the internal representation of the
67003 ** schema consistent with what is on disk.
67004 */
67005 case OP_DropTrigger: {
67006   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
67007   break;
67008 }
67009
67010
67011 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67012 /* Opcode: IntegrityCk P1 P2 P3 * P5
67013 **
67014 ** Do an analysis of the currently open database.  Store in
67015 ** register P1 the text of an error message describing any problems.
67016 ** If no problems are found, store a NULL in register P1.
67017 **
67018 ** The register P3 contains the maximum number of allowed errors.
67019 ** At most reg(P3) errors will be reported.
67020 ** In other words, the analysis stops as soon as reg(P1) errors are 
67021 ** seen.  Reg(P1) is updated with the number of errors remaining.
67022 **
67023 ** The root page numbers of all tables in the database are integer
67024 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
67025 ** total.
67026 **
67027 ** If P5 is not zero, the check is done on the auxiliary database
67028 ** file, not the main database file.
67029 **
67030 ** This opcode is used to implement the integrity_check pragma.
67031 */
67032 case OP_IntegrityCk: {
67033 #if 0  /* local variables moved into u.bv */
67034   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
67035   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
67036   int j;          /* Loop counter */
67037   int nErr;       /* Number of errors reported */
67038   char *z;        /* Text of the error report */
67039   Mem *pnErr;     /* Register keeping track of errors remaining */
67040 #endif /* local variables moved into u.bv */
67041
67042   u.bv.nRoot = pOp->p2;
67043   assert( u.bv.nRoot>0 );
67044   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67045   if( u.bv.aRoot==0 ) goto no_mem;
67046   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67047   u.bv.pnErr = &aMem[pOp->p3];
67048   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67049   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67050   pIn1 = &aMem[pOp->p1];
67051   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67052     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67053   }
67054   u.bv.aRoot[u.bv.j] = 0;
67055   assert( pOp->p5<db->nDb );
67056   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67057   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67058                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
67059   sqlite3DbFree(db, u.bv.aRoot);
67060   u.bv.pnErr->u.i -= u.bv.nErr;
67061   sqlite3VdbeMemSetNull(pIn1);
67062   if( u.bv.nErr==0 ){
67063     assert( u.bv.z==0 );
67064   }else if( u.bv.z==0 ){
67065     goto no_mem;
67066   }else{
67067     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67068   }
67069   UPDATE_MAX_BLOBSIZE(pIn1);
67070   sqlite3VdbeChangeEncoding(pIn1, encoding);
67071   break;
67072 }
67073 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67074
67075 /* Opcode: RowSetAdd P1 P2 * * *
67076 **
67077 ** Insert the integer value held by register P2 into a boolean index
67078 ** held in register P1.
67079 **
67080 ** An assertion fails if P2 is not an integer.
67081 */
67082 case OP_RowSetAdd: {       /* in1, in2 */
67083   pIn1 = &aMem[pOp->p1];
67084   pIn2 = &aMem[pOp->p2];
67085   assert( (pIn2->flags & MEM_Int)!=0 );
67086   if( (pIn1->flags & MEM_RowSet)==0 ){
67087     sqlite3VdbeMemSetRowSet(pIn1);
67088     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67089   }
67090   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67091   break;
67092 }
67093
67094 /* Opcode: RowSetRead P1 P2 P3 * *
67095 **
67096 ** Extract the smallest value from boolean index P1 and put that value into
67097 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
67098 ** unchanged and jump to instruction P2.
67099 */
67100 case OP_RowSetRead: {       /* jump, in1, out3 */
67101 #if 0  /* local variables moved into u.bw */
67102   i64 val;
67103 #endif /* local variables moved into u.bw */
67104   CHECK_FOR_INTERRUPT;
67105   pIn1 = &aMem[pOp->p1];
67106   if( (pIn1->flags & MEM_RowSet)==0
67107    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67108   ){
67109     /* The boolean index is empty */
67110     sqlite3VdbeMemSetNull(pIn1);
67111     pc = pOp->p2 - 1;
67112   }else{
67113     /* A value was pulled from the index */
67114     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67115   }
67116   break;
67117 }
67118
67119 /* Opcode: RowSetTest P1 P2 P3 P4
67120 **
67121 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
67122 ** contains a RowSet object and that RowSet object contains
67123 ** the value held in P3, jump to register P2. Otherwise, insert the
67124 ** integer in P3 into the RowSet and continue on to the
67125 ** next opcode.
67126 **
67127 ** The RowSet object is optimized for the case where successive sets
67128 ** of integers, where each set contains no duplicates. Each set
67129 ** of values is identified by a unique P4 value. The first set
67130 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
67131 ** non-negative.  For non-negative values of P4 only the lower 4
67132 ** bits are significant.
67133 **
67134 ** This allows optimizations: (a) when P4==0 there is no need to test
67135 ** the rowset object for P3, as it is guaranteed not to contain it,
67136 ** (b) when P4==-1 there is no need to insert the value, as it will
67137 ** never be tested for, and (c) when a value that is part of set X is
67138 ** inserted, there is no need to search to see if the same value was
67139 ** previously inserted as part of set X (only if it was previously
67140 ** inserted as part of some other set).
67141 */
67142 case OP_RowSetTest: {                     /* jump, in1, in3 */
67143 #if 0  /* local variables moved into u.bx */
67144   int iSet;
67145   int exists;
67146 #endif /* local variables moved into u.bx */
67147
67148   pIn1 = &aMem[pOp->p1];
67149   pIn3 = &aMem[pOp->p3];
67150   u.bx.iSet = pOp->p4.i;
67151   assert( pIn3->flags&MEM_Int );
67152
67153   /* If there is anything other than a rowset object in memory cell P1,
67154   ** delete it now and initialize P1 with an empty rowset
67155   */
67156   if( (pIn1->flags & MEM_RowSet)==0 ){
67157     sqlite3VdbeMemSetRowSet(pIn1);
67158     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67159   }
67160
67161   assert( pOp->p4type==P4_INT32 );
67162   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67163   if( u.bx.iSet ){
67164     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67165                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67166                                pIn3->u.i);
67167     if( u.bx.exists ){
67168       pc = pOp->p2 - 1;
67169       break;
67170     }
67171   }
67172   if( u.bx.iSet>=0 ){
67173     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67174   }
67175   break;
67176 }
67177
67178
67179 #ifndef SQLITE_OMIT_TRIGGER
67180
67181 /* Opcode: Program P1 P2 P3 P4 *
67182 **
67183 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
67184 **
67185 ** P1 contains the address of the memory cell that contains the first memory 
67186 ** cell in an array of values used as arguments to the sub-program. P2 
67187 ** contains the address to jump to if the sub-program throws an IGNORE 
67188 ** exception using the RAISE() function. Register P3 contains the address 
67189 ** of a memory cell in this (the parent) VM that is used to allocate the 
67190 ** memory required by the sub-vdbe at runtime.
67191 **
67192 ** P4 is a pointer to the VM containing the trigger program.
67193 */
67194 case OP_Program: {        /* jump */
67195 #if 0  /* local variables moved into u.by */
67196   int nMem;               /* Number of memory registers for sub-program */
67197   int nByte;              /* Bytes of runtime space required for sub-program */
67198   Mem *pRt;               /* Register to allocate runtime space */
67199   Mem *pMem;              /* Used to iterate through memory cells */
67200   Mem *pEnd;              /* Last memory cell in new array */
67201   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
67202   SubProgram *pProgram;   /* Sub-program to execute */
67203   void *t;                /* Token identifying trigger */
67204 #endif /* local variables moved into u.by */
67205
67206   u.by.pProgram = pOp->p4.pProgram;
67207   u.by.pRt = &aMem[pOp->p3];
67208   assert( memIsValid(u.by.pRt) );
67209   assert( u.by.pProgram->nOp>0 );
67210
67211   /* If the p5 flag is clear, then recursive invocation of triggers is
67212   ** disabled for backwards compatibility (p5 is set if this sub-program
67213   ** is really a trigger, not a foreign key action, and the flag set
67214   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67215   **
67216   ** It is recursive invocation of triggers, at the SQL level, that is
67217   ** disabled. In some cases a single trigger may generate more than one
67218   ** SubProgram (if the trigger may be executed with more than one different
67219   ** ON CONFLICT algorithm). SubProgram structures associated with a
67220   ** single trigger all have the same value for the SubProgram.token
67221   ** variable.  */
67222   if( pOp->p5 ){
67223     u.by.t = u.by.pProgram->token;
67224     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67225     if( u.by.pFrame ) break;
67226   }
67227
67228   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67229     rc = SQLITE_ERROR;
67230     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67231     break;
67232   }
67233
67234   /* Register u.by.pRt is used to store the memory required to save the state
67235   ** of the current program, and the memory required at runtime to execute
67236   ** the trigger program. If this trigger has been fired before, then u.by.pRt
67237   ** is already allocated. Otherwise, it must be initialized.  */
67238   if( (u.by.pRt->flags&MEM_Frame)==0 ){
67239     /* SubProgram.nMem is set to the number of memory cells used by the
67240     ** program stored in SubProgram.aOp. As well as these, one memory
67241     ** cell is required for each cursor used by the program. Set local
67242     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67243     */
67244     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67245     u.by.nByte = ROUND8(sizeof(VdbeFrame))
67246               + u.by.nMem * sizeof(Mem)
67247               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67248     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67249     if( !u.by.pFrame ){
67250       goto no_mem;
67251     }
67252     sqlite3VdbeMemRelease(u.by.pRt);
67253     u.by.pRt->flags = MEM_Frame;
67254     u.by.pRt->u.pFrame = u.by.pFrame;
67255
67256     u.by.pFrame->v = p;
67257     u.by.pFrame->nChildMem = u.by.nMem;
67258     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67259     u.by.pFrame->pc = pc;
67260     u.by.pFrame->aMem = p->aMem;
67261     u.by.pFrame->nMem = p->nMem;
67262     u.by.pFrame->apCsr = p->apCsr;
67263     u.by.pFrame->nCursor = p->nCursor;
67264     u.by.pFrame->aOp = p->aOp;
67265     u.by.pFrame->nOp = p->nOp;
67266     u.by.pFrame->token = u.by.pProgram->token;
67267
67268     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67269     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67270       u.by.pMem->flags = MEM_Null;
67271       u.by.pMem->db = db;
67272     }
67273   }else{
67274     u.by.pFrame = u.by.pRt->u.pFrame;
67275     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67276     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67277     assert( pc==u.by.pFrame->pc );
67278   }
67279
67280   p->nFrame++;
67281   u.by.pFrame->pParent = p->pFrame;
67282   u.by.pFrame->lastRowid = db->lastRowid;
67283   u.by.pFrame->nChange = p->nChange;
67284   p->nChange = 0;
67285   p->pFrame = u.by.pFrame;
67286   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67287   p->nMem = u.by.pFrame->nChildMem;
67288   p->nCursor = (u16)u.by.pFrame->nChildCsr;
67289   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67290   p->aOp = aOp = u.by.pProgram->aOp;
67291   p->nOp = u.by.pProgram->nOp;
67292   pc = -1;
67293
67294   break;
67295 }
67296
67297 /* Opcode: Param P1 P2 * * *
67298 **
67299 ** This opcode is only ever present in sub-programs called via the 
67300 ** OP_Program instruction. Copy a value currently stored in a memory 
67301 ** cell of the calling (parent) frame to cell P2 in the current frames 
67302 ** address space. This is used by trigger programs to access the new.* 
67303 ** and old.* values.
67304 **
67305 ** The address of the cell in the parent frame is determined by adding
67306 ** the value of the P1 argument to the value of the P1 argument to the
67307 ** calling OP_Program instruction.
67308 */
67309 case OP_Param: {           /* out2-prerelease */
67310 #if 0  /* local variables moved into u.bz */
67311   VdbeFrame *pFrame;
67312   Mem *pIn;
67313 #endif /* local variables moved into u.bz */
67314   u.bz.pFrame = p->pFrame;
67315   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67316   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67317   break;
67318 }
67319
67320 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
67321
67322 #ifndef SQLITE_OMIT_FOREIGN_KEY
67323 /* Opcode: FkCounter P1 P2 * * *
67324 **
67325 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67326 ** If P1 is non-zero, the database constraint counter is incremented 
67327 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
67328 ** statement counter is incremented (immediate foreign key constraints).
67329 */
67330 case OP_FkCounter: {
67331   if( pOp->p1 ){
67332     db->nDeferredCons += pOp->p2;
67333   }else{
67334     p->nFkConstraint += pOp->p2;
67335   }
67336   break;
67337 }
67338
67339 /* Opcode: FkIfZero P1 P2 * * *
67340 **
67341 ** This opcode tests if a foreign key constraint-counter is currently zero.
67342 ** If so, jump to instruction P2. Otherwise, fall through to the next 
67343 ** instruction.
67344 **
67345 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
67346 ** is zero (the one that counts deferred constraint violations). If P1 is
67347 ** zero, the jump is taken if the statement constraint-counter is zero
67348 ** (immediate foreign key constraint violations).
67349 */
67350 case OP_FkIfZero: {         /* jump */
67351   if( pOp->p1 ){
67352     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67353   }else{
67354     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67355   }
67356   break;
67357 }
67358 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67359
67360 #ifndef SQLITE_OMIT_AUTOINCREMENT
67361 /* Opcode: MemMax P1 P2 * * *
67362 **
67363 ** P1 is a register in the root frame of this VM (the root frame is
67364 ** different from the current frame if this instruction is being executed
67365 ** within a sub-program). Set the value of register P1 to the maximum of 
67366 ** its current value and the value in register P2.
67367 **
67368 ** This instruction throws an error if the memory cell is not initially
67369 ** an integer.
67370 */
67371 case OP_MemMax: {        /* in2 */
67372 #if 0  /* local variables moved into u.ca */
67373   Mem *pIn1;
67374   VdbeFrame *pFrame;
67375 #endif /* local variables moved into u.ca */
67376   if( p->pFrame ){
67377     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67378     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67379   }else{
67380     u.ca.pIn1 = &aMem[pOp->p1];
67381   }
67382   assert( memIsValid(u.ca.pIn1) );
67383   sqlite3VdbeMemIntegerify(u.ca.pIn1);
67384   pIn2 = &aMem[pOp->p2];
67385   sqlite3VdbeMemIntegerify(pIn2);
67386   if( u.ca.pIn1->u.i<pIn2->u.i){
67387     u.ca.pIn1->u.i = pIn2->u.i;
67388   }
67389   break;
67390 }
67391 #endif /* SQLITE_OMIT_AUTOINCREMENT */
67392
67393 /* Opcode: IfPos P1 P2 * * *
67394 **
67395 ** If the value of register P1 is 1 or greater, jump to P2.
67396 **
67397 ** It is illegal to use this instruction on a register that does
67398 ** not contain an integer.  An assertion fault will result if you try.
67399 */
67400 case OP_IfPos: {        /* jump, in1 */
67401   pIn1 = &aMem[pOp->p1];
67402   assert( pIn1->flags&MEM_Int );
67403   if( pIn1->u.i>0 ){
67404      pc = pOp->p2 - 1;
67405   }
67406   break;
67407 }
67408
67409 /* Opcode: IfNeg P1 P2 * * *
67410 **
67411 ** If the value of register P1 is less than zero, jump to P2. 
67412 **
67413 ** It is illegal to use this instruction on a register that does
67414 ** not contain an integer.  An assertion fault will result if you try.
67415 */
67416 case OP_IfNeg: {        /* jump, in1 */
67417   pIn1 = &aMem[pOp->p1];
67418   assert( pIn1->flags&MEM_Int );
67419   if( pIn1->u.i<0 ){
67420      pc = pOp->p2 - 1;
67421   }
67422   break;
67423 }
67424
67425 /* Opcode: IfZero P1 P2 P3 * *
67426 **
67427 ** The register P1 must contain an integer.  Add literal P3 to the
67428 ** value in register P1.  If the result is exactly 0, jump to P2. 
67429 **
67430 ** It is illegal to use this instruction on a register that does
67431 ** not contain an integer.  An assertion fault will result if you try.
67432 */
67433 case OP_IfZero: {        /* jump, in1 */
67434   pIn1 = &aMem[pOp->p1];
67435   assert( pIn1->flags&MEM_Int );
67436   pIn1->u.i += pOp->p3;
67437   if( pIn1->u.i==0 ){
67438      pc = pOp->p2 - 1;
67439   }
67440   break;
67441 }
67442
67443 /* Opcode: AggStep * P2 P3 P4 P5
67444 **
67445 ** Execute the step function for an aggregate.  The
67446 ** function has P5 arguments.   P4 is a pointer to the FuncDef
67447 ** structure that specifies the function.  Use register
67448 ** P3 as the accumulator.
67449 **
67450 ** The P5 arguments are taken from register P2 and its
67451 ** successors.
67452 */
67453 case OP_AggStep: {
67454 #if 0  /* local variables moved into u.cb */
67455   int n;
67456   int i;
67457   Mem *pMem;
67458   Mem *pRec;
67459   sqlite3_context ctx;
67460   sqlite3_value **apVal;
67461 #endif /* local variables moved into u.cb */
67462
67463   u.cb.n = pOp->p5;
67464   assert( u.cb.n>=0 );
67465   u.cb.pRec = &aMem[pOp->p2];
67466   u.cb.apVal = p->apArg;
67467   assert( u.cb.apVal || u.cb.n==0 );
67468   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
67469     assert( memIsValid(u.cb.pRec) );
67470     u.cb.apVal[u.cb.i] = u.cb.pRec;
67471     memAboutToChange(p, u.cb.pRec);
67472     sqlite3VdbeMemStoreType(u.cb.pRec);
67473   }
67474   u.cb.ctx.pFunc = pOp->p4.pFunc;
67475   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67476   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
67477   u.cb.pMem->n++;
67478   u.cb.ctx.s.flags = MEM_Null;
67479   u.cb.ctx.s.z = 0;
67480   u.cb.ctx.s.zMalloc = 0;
67481   u.cb.ctx.s.xDel = 0;
67482   u.cb.ctx.s.db = db;
67483   u.cb.ctx.isError = 0;
67484   u.cb.ctx.pColl = 0;
67485   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67486     assert( pOp>p->aOp );
67487     assert( pOp[-1].p4type==P4_COLLSEQ );
67488     assert( pOp[-1].opcode==OP_CollSeq );
67489     u.cb.ctx.pColl = pOp[-1].p4.pColl;
67490   }
67491   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
67492   if( u.cb.ctx.isError ){
67493     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
67494     rc = u.cb.ctx.isError;
67495   }
67496
67497   sqlite3VdbeMemRelease(&u.cb.ctx.s);
67498
67499   break;
67500 }
67501
67502 /* Opcode: AggFinal P1 P2 * P4 *
67503 **
67504 ** Execute the finalizer function for an aggregate.  P1 is
67505 ** the memory location that is the accumulator for the aggregate.
67506 **
67507 ** P2 is the number of arguments that the step function takes and
67508 ** P4 is a pointer to the FuncDef for this function.  The P2
67509 ** argument is not used by this opcode.  It is only there to disambiguate
67510 ** functions that can take varying numbers of arguments.  The
67511 ** P4 argument is only needed for the degenerate case where
67512 ** the step function was not previously called.
67513 */
67514 case OP_AggFinal: {
67515 #if 0  /* local variables moved into u.cc */
67516   Mem *pMem;
67517 #endif /* local variables moved into u.cc */
67518   assert( pOp->p1>0 && pOp->p1<=p->nMem );
67519   u.cc.pMem = &aMem[pOp->p1];
67520   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
67521   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
67522   if( rc ){
67523     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
67524   }
67525   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
67526   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
67527   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
67528     goto too_big;
67529   }
67530   break;
67531 }
67532
67533 #ifndef SQLITE_OMIT_WAL
67534 /* Opcode: Checkpoint P1 P2 P3 * *
67535 **
67536 ** Checkpoint database P1. This is a no-op if P1 is not currently in
67537 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
67538 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
67539 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
67540 ** WAL after the checkpoint into mem[P3+1] and the number of pages
67541 ** in the WAL that have been checkpointed after the checkpoint
67542 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
67543 ** mem[P3+2] are initialized to -1.
67544 */
67545 case OP_Checkpoint: {
67546 #if 0  /* local variables moved into u.cd */
67547   int i;                          /* Loop counter */
67548   int aRes[3];                    /* Results */
67549   Mem *pMem;                      /* Write results here */
67550 #endif /* local variables moved into u.cd */
67551
67552   u.cd.aRes[0] = 0;
67553   u.cd.aRes[1] = u.cd.aRes[2] = -1;
67554   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
67555        || pOp->p2==SQLITE_CHECKPOINT_FULL
67556        || pOp->p2==SQLITE_CHECKPOINT_RESTART
67557   );
67558   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
67559   if( rc==SQLITE_BUSY ){
67560     rc = SQLITE_OK;
67561     u.cd.aRes[0] = 1;
67562   }
67563   for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
67564     sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
67565   }
67566   break;
67567 };  
67568 #endif
67569
67570 #ifndef SQLITE_OMIT_PRAGMA
67571 /* Opcode: JournalMode P1 P2 P3 * P5
67572 **
67573 ** Change the journal mode of database P1 to P3. P3 must be one of the
67574 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
67575 ** modes (delete, truncate, persist, off and memory), this is a simple
67576 ** operation. No IO is required.
67577 **
67578 ** If changing into or out of WAL mode the procedure is more complicated.
67579 **
67580 ** Write a string containing the final journal-mode to register P2.
67581 */
67582 case OP_JournalMode: {    /* out2-prerelease */
67583 #if 0  /* local variables moved into u.ce */
67584   Btree *pBt;                     /* Btree to change journal mode of */
67585   Pager *pPager;                  /* Pager associated with pBt */
67586   int eNew;                       /* New journal mode */
67587   int eOld;                       /* The old journal mode */
67588   const char *zFilename;          /* Name of database file for pPager */
67589 #endif /* local variables moved into u.ce */
67590
67591   u.ce.eNew = pOp->p3;
67592   assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
67593        || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
67594        || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
67595        || u.ce.eNew==PAGER_JOURNALMODE_OFF
67596        || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
67597        || u.ce.eNew==PAGER_JOURNALMODE_WAL
67598        || u.ce.eNew==PAGER_JOURNALMODE_QUERY
67599   );
67600   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67601
67602   u.ce.pBt = db->aDb[pOp->p1].pBt;
67603   u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
67604   u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
67605   if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
67606   if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
67607
67608 #ifndef SQLITE_OMIT_WAL
67609   u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
67610
67611   /* Do not allow a transition to journal_mode=WAL for a database
67612   ** in temporary storage or if the VFS does not support shared memory
67613   */
67614   if( u.ce.eNew==PAGER_JOURNALMODE_WAL
67615    && (u.ce.zFilename[0]==0                         /* Temp file */
67616        || !sqlite3PagerWalSupported(u.ce.pPager))   /* No shared-memory support */
67617   ){
67618     u.ce.eNew = u.ce.eOld;
67619   }
67620
67621   if( (u.ce.eNew!=u.ce.eOld)
67622    && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
67623   ){
67624     if( !db->autoCommit || db->activeVdbeCnt>1 ){
67625       rc = SQLITE_ERROR;
67626       sqlite3SetString(&p->zErrMsg, db,
67627           "cannot change %s wal mode from within a transaction",
67628           (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
67629       );
67630       break;
67631     }else{
67632
67633       if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
67634         /* If leaving WAL mode, close the log file. If successful, the call
67635         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
67636         ** file. An EXCLUSIVE lock may still be held on the database file
67637         ** after a successful return.
67638         */
67639         rc = sqlite3PagerCloseWal(u.ce.pPager);
67640         if( rc==SQLITE_OK ){
67641           sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67642         }
67643       }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
67644         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
67645         ** as an intermediate */
67646         sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
67647       }
67648
67649       /* Open a transaction on the database file. Regardless of the journal
67650       ** mode, this transaction always uses a rollback journal.
67651       */
67652       assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
67653       if( rc==SQLITE_OK ){
67654         rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
67655       }
67656     }
67657   }
67658 #endif /* ifndef SQLITE_OMIT_WAL */
67659
67660   if( rc ){
67661     u.ce.eNew = u.ce.eOld;
67662   }
67663   u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67664
67665   pOut = &aMem[pOp->p2];
67666   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67667   pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
67668   pOut->n = sqlite3Strlen30(pOut->z);
67669   pOut->enc = SQLITE_UTF8;
67670   sqlite3VdbeChangeEncoding(pOut, encoding);
67671   break;
67672 };
67673 #endif /* SQLITE_OMIT_PRAGMA */
67674
67675 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
67676 /* Opcode: Vacuum * * * * *
67677 **
67678 ** Vacuum the entire database.  This opcode will cause other virtual
67679 ** machines to be created and run.  It may not be called from within
67680 ** a transaction.
67681 */
67682 case OP_Vacuum: {
67683   rc = sqlite3RunVacuum(&p->zErrMsg, db);
67684   break;
67685 }
67686 #endif
67687
67688 #if !defined(SQLITE_OMIT_AUTOVACUUM)
67689 /* Opcode: IncrVacuum P1 P2 * * *
67690 **
67691 ** Perform a single step of the incremental vacuum procedure on
67692 ** the P1 database. If the vacuum has finished, jump to instruction
67693 ** P2. Otherwise, fall through to the next instruction.
67694 */
67695 case OP_IncrVacuum: {        /* jump */
67696 #if 0  /* local variables moved into u.cf */
67697   Btree *pBt;
67698 #endif /* local variables moved into u.cf */
67699
67700   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67701   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67702   u.cf.pBt = db->aDb[pOp->p1].pBt;
67703   rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
67704   if( rc==SQLITE_DONE ){
67705     pc = pOp->p2 - 1;
67706     rc = SQLITE_OK;
67707   }
67708   break;
67709 }
67710 #endif
67711
67712 /* Opcode: Expire P1 * * * *
67713 **
67714 ** Cause precompiled statements to become expired. An expired statement
67715 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
67716 ** (via sqlite3_step()).
67717 ** 
67718 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
67719 ** then only the currently executing statement is affected. 
67720 */
67721 case OP_Expire: {
67722   if( !pOp->p1 ){
67723     sqlite3ExpirePreparedStatements(db);
67724   }else{
67725     p->expired = 1;
67726   }
67727   break;
67728 }
67729
67730 #ifndef SQLITE_OMIT_SHARED_CACHE
67731 /* Opcode: TableLock P1 P2 P3 P4 *
67732 **
67733 ** Obtain a lock on a particular table. This instruction is only used when
67734 ** the shared-cache feature is enabled. 
67735 **
67736 ** P1 is the index of the database in sqlite3.aDb[] of the database
67737 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
67738 ** a write lock if P3==1.
67739 **
67740 ** P2 contains the root-page of the table to lock.
67741 **
67742 ** P4 contains a pointer to the name of the table being locked. This is only
67743 ** used to generate an error message if the lock cannot be obtained.
67744 */
67745 case OP_TableLock: {
67746   u8 isWriteLock = (u8)pOp->p3;
67747   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
67748     int p1 = pOp->p1; 
67749     assert( p1>=0 && p1<db->nDb );
67750     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
67751     assert( isWriteLock==0 || isWriteLock==1 );
67752     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
67753     if( (rc&0xFF)==SQLITE_LOCKED ){
67754       const char *z = pOp->p4.z;
67755       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
67756     }
67757   }
67758   break;
67759 }
67760 #endif /* SQLITE_OMIT_SHARED_CACHE */
67761
67762 #ifndef SQLITE_OMIT_VIRTUALTABLE
67763 /* Opcode: VBegin * * * P4 *
67764 **
67765 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
67766 ** xBegin method for that table.
67767 **
67768 ** Also, whether or not P4 is set, check that this is not being called from
67769 ** within a callback to a virtual table xSync() method. If it is, the error
67770 ** code will be set to SQLITE_LOCKED.
67771 */
67772 case OP_VBegin: {
67773 #if 0  /* local variables moved into u.cg */
67774   VTable *pVTab;
67775 #endif /* local variables moved into u.cg */
67776   u.cg.pVTab = pOp->p4.pVtab;
67777   rc = sqlite3VtabBegin(db, u.cg.pVTab);
67778   if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
67779   break;
67780 }
67781 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67782
67783 #ifndef SQLITE_OMIT_VIRTUALTABLE
67784 /* Opcode: VCreate P1 * * P4 *
67785 **
67786 ** P4 is the name of a virtual table in database P1. Call the xCreate method
67787 ** for that table.
67788 */
67789 case OP_VCreate: {
67790   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
67791   break;
67792 }
67793 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67794
67795 #ifndef SQLITE_OMIT_VIRTUALTABLE
67796 /* Opcode: VDestroy P1 * * P4 *
67797 **
67798 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
67799 ** of that table.
67800 */
67801 case OP_VDestroy: {
67802   p->inVtabMethod = 2;
67803   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
67804   p->inVtabMethod = 0;
67805   break;
67806 }
67807 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67808
67809 #ifndef SQLITE_OMIT_VIRTUALTABLE
67810 /* Opcode: VOpen P1 * * P4 *
67811 **
67812 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
67813 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
67814 ** table and stores that cursor in P1.
67815 */
67816 case OP_VOpen: {
67817 #if 0  /* local variables moved into u.ch */
67818   VdbeCursor *pCur;
67819   sqlite3_vtab_cursor *pVtabCursor;
67820   sqlite3_vtab *pVtab;
67821   sqlite3_module *pModule;
67822 #endif /* local variables moved into u.ch */
67823
67824   u.ch.pCur = 0;
67825   u.ch.pVtabCursor = 0;
67826   u.ch.pVtab = pOp->p4.pVtab->pVtab;
67827   u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
67828   assert(u.ch.pVtab && u.ch.pModule);
67829   rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
67830   importVtabErrMsg(p, u.ch.pVtab);
67831   if( SQLITE_OK==rc ){
67832     /* Initialize sqlite3_vtab_cursor base class */
67833     u.ch.pVtabCursor->pVtab = u.ch.pVtab;
67834
67835     /* Initialise vdbe cursor object */
67836     u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
67837     if( u.ch.pCur ){
67838       u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
67839       u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
67840     }else{
67841       db->mallocFailed = 1;
67842       u.ch.pModule->xClose(u.ch.pVtabCursor);
67843     }
67844   }
67845   break;
67846 }
67847 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67848
67849 #ifndef SQLITE_OMIT_VIRTUALTABLE
67850 /* Opcode: VFilter P1 P2 P3 P4 *
67851 **
67852 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
67853 ** the filtered result set is empty.
67854 **
67855 ** P4 is either NULL or a string that was generated by the xBestIndex
67856 ** method of the module.  The interpretation of the P4 string is left
67857 ** to the module implementation.
67858 **
67859 ** This opcode invokes the xFilter method on the virtual table specified
67860 ** by P1.  The integer query plan parameter to xFilter is stored in register
67861 ** P3. Register P3+1 stores the argc parameter to be passed to the
67862 ** xFilter method. Registers P3+2..P3+1+argc are the argc
67863 ** additional parameters which are passed to
67864 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
67865 **
67866 ** A jump is made to P2 if the result set after filtering would be empty.
67867 */
67868 case OP_VFilter: {   /* jump */
67869 #if 0  /* local variables moved into u.ci */
67870   int nArg;
67871   int iQuery;
67872   const sqlite3_module *pModule;
67873   Mem *pQuery;
67874   Mem *pArgc;
67875   sqlite3_vtab_cursor *pVtabCursor;
67876   sqlite3_vtab *pVtab;
67877   VdbeCursor *pCur;
67878   int res;
67879   int i;
67880   Mem **apArg;
67881 #endif /* local variables moved into u.ci */
67882
67883   u.ci.pQuery = &aMem[pOp->p3];
67884   u.ci.pArgc = &u.ci.pQuery[1];
67885   u.ci.pCur = p->apCsr[pOp->p1];
67886   assert( memIsValid(u.ci.pQuery) );
67887   REGISTER_TRACE(pOp->p3, u.ci.pQuery);
67888   assert( u.ci.pCur->pVtabCursor );
67889   u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
67890   u.ci.pVtab = u.ci.pVtabCursor->pVtab;
67891   u.ci.pModule = u.ci.pVtab->pModule;
67892
67893   /* Grab the index number and argc parameters */
67894   assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
67895   u.ci.nArg = (int)u.ci.pArgc->u.i;
67896   u.ci.iQuery = (int)u.ci.pQuery->u.i;
67897
67898   /* Invoke the xFilter method */
67899   {
67900     u.ci.res = 0;
67901     u.ci.apArg = p->apArg;
67902     for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
67903       u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
67904       sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
67905     }
67906
67907     p->inVtabMethod = 1;
67908     rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
67909     p->inVtabMethod = 0;
67910     importVtabErrMsg(p, u.ci.pVtab);
67911     if( rc==SQLITE_OK ){
67912       u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
67913     }
67914
67915     if( u.ci.res ){
67916       pc = pOp->p2 - 1;
67917     }
67918   }
67919   u.ci.pCur->nullRow = 0;
67920
67921   break;
67922 }
67923 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67924
67925 #ifndef SQLITE_OMIT_VIRTUALTABLE
67926 /* Opcode: VColumn P1 P2 P3 * *
67927 **
67928 ** Store the value of the P2-th column of
67929 ** the row of the virtual-table that the 
67930 ** P1 cursor is pointing to into register P3.
67931 */
67932 case OP_VColumn: {
67933 #if 0  /* local variables moved into u.cj */
67934   sqlite3_vtab *pVtab;
67935   const sqlite3_module *pModule;
67936   Mem *pDest;
67937   sqlite3_context sContext;
67938 #endif /* local variables moved into u.cj */
67939
67940   VdbeCursor *pCur = p->apCsr[pOp->p1];
67941   assert( pCur->pVtabCursor );
67942   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67943   u.cj.pDest = &aMem[pOp->p3];
67944   memAboutToChange(p, u.cj.pDest);
67945   if( pCur->nullRow ){
67946     sqlite3VdbeMemSetNull(u.cj.pDest);
67947     break;
67948   }
67949   u.cj.pVtab = pCur->pVtabCursor->pVtab;
67950   u.cj.pModule = u.cj.pVtab->pModule;
67951   assert( u.cj.pModule->xColumn );
67952   memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
67953
67954   /* The output cell may already have a buffer allocated. Move
67955   ** the current contents to u.cj.sContext.s so in case the user-function
67956   ** can use the already allocated buffer instead of allocating a
67957   ** new one.
67958   */
67959   sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
67960   MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
67961
67962   rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
67963   importVtabErrMsg(p, u.cj.pVtab);
67964   if( u.cj.sContext.isError ){
67965     rc = u.cj.sContext.isError;
67966   }
67967
67968   /* Copy the result of the function to the P3 register. We
67969   ** do this regardless of whether or not an error occurred to ensure any
67970   ** dynamic allocation in u.cj.sContext.s (a Mem struct) is  released.
67971   */
67972   sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
67973   sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
67974   REGISTER_TRACE(pOp->p3, u.cj.pDest);
67975   UPDATE_MAX_BLOBSIZE(u.cj.pDest);
67976
67977   if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
67978     goto too_big;
67979   }
67980   break;
67981 }
67982 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67983
67984 #ifndef SQLITE_OMIT_VIRTUALTABLE
67985 /* Opcode: VNext P1 P2 * * *
67986 **
67987 ** Advance virtual table P1 to the next row in its result set and
67988 ** jump to instruction P2.  Or, if the virtual table has reached
67989 ** the end of its result set, then fall through to the next instruction.
67990 */
67991 case OP_VNext: {   /* jump */
67992 #if 0  /* local variables moved into u.ck */
67993   sqlite3_vtab *pVtab;
67994   const sqlite3_module *pModule;
67995   int res;
67996   VdbeCursor *pCur;
67997 #endif /* local variables moved into u.ck */
67998
67999   u.ck.res = 0;
68000   u.ck.pCur = p->apCsr[pOp->p1];
68001   assert( u.ck.pCur->pVtabCursor );
68002   if( u.ck.pCur->nullRow ){
68003     break;
68004   }
68005   u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
68006   u.ck.pModule = u.ck.pVtab->pModule;
68007   assert( u.ck.pModule->xNext );
68008
68009   /* Invoke the xNext() method of the module. There is no way for the
68010   ** underlying implementation to return an error if one occurs during
68011   ** xNext(). Instead, if an error occurs, true is returned (indicating that
68012   ** data is available) and the error code returned when xColumn or
68013   ** some other method is next invoked on the save virtual table cursor.
68014   */
68015   p->inVtabMethod = 1;
68016   rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68017   p->inVtabMethod = 0;
68018   importVtabErrMsg(p, u.ck.pVtab);
68019   if( rc==SQLITE_OK ){
68020     u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68021   }
68022
68023   if( !u.ck.res ){
68024     /* If there is data, jump to P2 */
68025     pc = pOp->p2 - 1;
68026   }
68027   break;
68028 }
68029 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68030
68031 #ifndef SQLITE_OMIT_VIRTUALTABLE
68032 /* Opcode: VRename P1 * * P4 *
68033 **
68034 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68035 ** This opcode invokes the corresponding xRename method. The value
68036 ** in register P1 is passed as the zName argument to the xRename method.
68037 */
68038 case OP_VRename: {
68039 #if 0  /* local variables moved into u.cl */
68040   sqlite3_vtab *pVtab;
68041   Mem *pName;
68042 #endif /* local variables moved into u.cl */
68043
68044   u.cl.pVtab = pOp->p4.pVtab->pVtab;
68045   u.cl.pName = &aMem[pOp->p1];
68046   assert( u.cl.pVtab->pModule->xRename );
68047   assert( memIsValid(u.cl.pName) );
68048   REGISTER_TRACE(pOp->p1, u.cl.pName);
68049   assert( u.cl.pName->flags & MEM_Str );
68050   rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68051   importVtabErrMsg(p, u.cl.pVtab);
68052   p->expired = 0;
68053
68054   break;
68055 }
68056 #endif
68057
68058 #ifndef SQLITE_OMIT_VIRTUALTABLE
68059 /* Opcode: VUpdate P1 P2 P3 P4 *
68060 **
68061 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68062 ** This opcode invokes the corresponding xUpdate method. P2 values
68063 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
68064 ** invocation. The value in register (P3+P2-1) corresponds to the 
68065 ** p2th element of the argv array passed to xUpdate.
68066 **
68067 ** The xUpdate method will do a DELETE or an INSERT or both.
68068 ** The argv[0] element (which corresponds to memory cell P3)
68069 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
68070 ** deletion occurs.  The argv[1] element is the rowid of the new 
68071 ** row.  This can be NULL to have the virtual table select the new 
68072 ** rowid for itself.  The subsequent elements in the array are 
68073 ** the values of columns in the new row.
68074 **
68075 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
68076 ** a row to delete.
68077 **
68078 ** P1 is a boolean flag. If it is set to true and the xUpdate call
68079 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
68080 ** is set to the value of the rowid for the row just inserted.
68081 */
68082 case OP_VUpdate: {
68083 #if 0  /* local variables moved into u.cm */
68084   sqlite3_vtab *pVtab;
68085   sqlite3_module *pModule;
68086   int nArg;
68087   int i;
68088   sqlite_int64 rowid;
68089   Mem **apArg;
68090   Mem *pX;
68091 #endif /* local variables moved into u.cm */
68092
68093   u.cm.pVtab = pOp->p4.pVtab->pVtab;
68094   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68095   u.cm.nArg = pOp->p2;
68096   assert( pOp->p4type==P4_VTAB );
68097   if( ALWAYS(u.cm.pModule->xUpdate) ){
68098     u.cm.apArg = p->apArg;
68099     u.cm.pX = &aMem[pOp->p3];
68100     for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68101       assert( memIsValid(u.cm.pX) );
68102       memAboutToChange(p, u.cm.pX);
68103       sqlite3VdbeMemStoreType(u.cm.pX);
68104       u.cm.apArg[u.cm.i] = u.cm.pX;
68105       u.cm.pX++;
68106     }
68107     rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68108     importVtabErrMsg(p, u.cm.pVtab);
68109     if( rc==SQLITE_OK && pOp->p1 ){
68110       assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68111       db->lastRowid = u.cm.rowid;
68112     }
68113     p->nChange++;
68114   }
68115   break;
68116 }
68117 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68118
68119 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68120 /* Opcode: Pagecount P1 P2 * * *
68121 **
68122 ** Write the current number of pages in database P1 to memory cell P2.
68123 */
68124 case OP_Pagecount: {            /* out2-prerelease */
68125   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68126   break;
68127 }
68128 #endif
68129
68130
68131 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68132 /* Opcode: MaxPgcnt P1 P2 P3 * *
68133 **
68134 ** Try to set the maximum page count for database P1 to the value in P3.
68135 ** Do not let the maximum page count fall below the current page count and
68136 ** do not change the maximum page count value if P3==0.
68137 **
68138 ** Store the maximum page count after the change in register P2.
68139 */
68140 case OP_MaxPgcnt: {            /* out2-prerelease */
68141   unsigned int newMax;
68142   Btree *pBt;
68143
68144   pBt = db->aDb[pOp->p1].pBt;
68145   newMax = 0;
68146   if( pOp->p3 ){
68147     newMax = sqlite3BtreeLastPage(pBt);
68148     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68149   }
68150   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68151   break;
68152 }
68153 #endif
68154
68155
68156 #ifndef SQLITE_OMIT_TRACE
68157 /* Opcode: Trace * * * P4 *
68158 **
68159 ** If tracing is enabled (by the sqlite3_trace()) interface, then
68160 ** the UTF-8 string contained in P4 is emitted on the trace callback.
68161 */
68162 case OP_Trace: {
68163 #if 0  /* local variables moved into u.cn */
68164   char *zTrace;
68165 #endif /* local variables moved into u.cn */
68166
68167   u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
68168   if( u.cn.zTrace ){
68169     if( db->xTrace ){
68170       char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68171       db->xTrace(db->pTraceArg, z);
68172       sqlite3DbFree(db, z);
68173     }
68174 #ifdef SQLITE_DEBUG
68175     if( (db->flags & SQLITE_SqlTrace)!=0 ){
68176       sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68177     }
68178 #endif /* SQLITE_DEBUG */
68179   }
68180   break;
68181 }
68182 #endif
68183
68184
68185 /* Opcode: Noop * * * * *
68186 **
68187 ** Do nothing.  This instruction is often useful as a jump
68188 ** destination.
68189 */
68190 /*
68191 ** The magic Explain opcode are only inserted when explain==2 (which
68192 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68193 ** This opcode records information from the optimizer.  It is the
68194 ** the same as a no-op.  This opcodesnever appears in a real VM program.
68195 */
68196 default: {          /* This is really OP_Noop and OP_Explain */
68197   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68198   break;
68199 }
68200
68201 /*****************************************************************************
68202 ** The cases of the switch statement above this line should all be indented
68203 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
68204 ** readability.  From this point on down, the normal indentation rules are
68205 ** restored.
68206 *****************************************************************************/
68207     }
68208
68209 #ifdef VDBE_PROFILE
68210     {
68211       u64 elapsed = sqlite3Hwtime() - start;
68212       pOp->cycles += elapsed;
68213       pOp->cnt++;
68214 #if 0
68215         fprintf(stdout, "%10llu ", elapsed);
68216         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68217 #endif
68218     }
68219 #endif
68220
68221     /* The following code adds nothing to the actual functionality
68222     ** of the program.  It is only here for testing and debugging.
68223     ** On the other hand, it does burn CPU cycles every time through
68224     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
68225     */
68226 #ifndef NDEBUG
68227     assert( pc>=-1 && pc<p->nOp );
68228
68229 #ifdef SQLITE_DEBUG
68230     if( p->trace ){
68231       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68232       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68233         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68234       }
68235       if( pOp->opflags & OPFLG_OUT3 ){
68236         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68237       }
68238     }
68239 #endif  /* SQLITE_DEBUG */
68240 #endif  /* NDEBUG */
68241   }  /* The end of the for(;;) loop the loops through opcodes */
68242
68243   /* If we reach this point, it means that execution is finished with
68244   ** an error of some kind.
68245   */
68246 vdbe_error_halt:
68247   assert( rc );
68248   p->rc = rc;
68249   testcase( sqlite3GlobalConfig.xLog!=0 );
68250   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
68251                    pc, p->zSql, p->zErrMsg);
68252   sqlite3VdbeHalt(p);
68253   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68254   rc = SQLITE_ERROR;
68255   if( resetSchemaOnFault>0 ){
68256     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68257   }
68258
68259   /* This is the only way out of this procedure.  We have to
68260   ** release the mutexes on btrees that were acquired at the
68261   ** top. */
68262 vdbe_return:
68263   sqlite3VdbeLeave(p);
68264   return rc;
68265
68266   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68267   ** is encountered.
68268   */
68269 too_big:
68270   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68271   rc = SQLITE_TOOBIG;
68272   goto vdbe_error_halt;
68273
68274   /* Jump to here if a malloc() fails.
68275   */
68276 no_mem:
68277   db->mallocFailed = 1;
68278   sqlite3SetString(&p->zErrMsg, db, "out of memory");
68279   rc = SQLITE_NOMEM;
68280   goto vdbe_error_halt;
68281
68282   /* Jump to here for any other kind of fatal error.  The "rc" variable
68283   ** should hold the error number.
68284   */
68285 abort_due_to_error:
68286   assert( p->zErrMsg==0 );
68287   if( db->mallocFailed ) rc = SQLITE_NOMEM;
68288   if( rc!=SQLITE_IOERR_NOMEM ){
68289     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68290   }
68291   goto vdbe_error_halt;
68292
68293   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68294   ** flag.
68295   */
68296 abort_due_to_interrupt:
68297   assert( db->u1.isInterrupted );
68298   rc = SQLITE_INTERRUPT;
68299   p->rc = rc;
68300   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68301   goto vdbe_error_halt;
68302 }
68303
68304 /************** End of vdbe.c ************************************************/
68305 /************** Begin file vdbeblob.c ****************************************/
68306 /*
68307 ** 2007 May 1
68308 **
68309 ** The author disclaims copyright to this source code.  In place of
68310 ** a legal notice, here is a blessing:
68311 **
68312 **    May you do good and not evil.
68313 **    May you find forgiveness for yourself and forgive others.
68314 **    May you share freely, never taking more than you give.
68315 **
68316 *************************************************************************
68317 **
68318 ** This file contains code used to implement incremental BLOB I/O.
68319 */
68320
68321
68322 #ifndef SQLITE_OMIT_INCRBLOB
68323
68324 /*
68325 ** Valid sqlite3_blob* handles point to Incrblob structures.
68326 */
68327 typedef struct Incrblob Incrblob;
68328 struct Incrblob {
68329   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
68330   int nByte;              /* Size of open blob, in bytes */
68331   int iOffset;            /* Byte offset of blob in cursor data */
68332   int iCol;               /* Table column this handle is open on */
68333   BtCursor *pCsr;         /* Cursor pointing at blob row */
68334   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
68335   sqlite3 *db;            /* The associated database */
68336 };
68337
68338
68339 /*
68340 ** This function is used by both blob_open() and blob_reopen(). It seeks
68341 ** the b-tree cursor associated with blob handle p to point to row iRow.
68342 ** If successful, SQLITE_OK is returned and subsequent calls to
68343 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68344 **
68345 ** If an error occurs, or if the specified row does not exist or does not
68346 ** contain a value of type TEXT or BLOB in the column nominated when the
68347 ** blob handle was opened, then an error code is returned and *pzErr may
68348 ** be set to point to a buffer containing an error message. It is the
68349 ** responsibility of the caller to free the error message buffer using
68350 ** sqlite3DbFree().
68351 **
68352 ** If an error does occur, then the b-tree cursor is closed. All subsequent
68353 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
68354 ** immediately return SQLITE_ABORT.
68355 */
68356 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68357   int rc;                         /* Error code */
68358   char *zErr = 0;                 /* Error message */
68359   Vdbe *v = (Vdbe *)p->pStmt;
68360
68361   /* Set the value of the SQL statements only variable to integer iRow. 
68362   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
68363   ** triggering asserts related to mutexes.
68364   */
68365   assert( v->aVar[0].flags&MEM_Int );
68366   v->aVar[0].u.i = iRow;
68367
68368   rc = sqlite3_step(p->pStmt);
68369   if( rc==SQLITE_ROW ){
68370     u32 type = v->apCsr[0]->aType[p->iCol];
68371     if( type<12 ){
68372       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68373           type==0?"null": type==7?"real": "integer"
68374       );
68375       rc = SQLITE_ERROR;
68376       sqlite3_finalize(p->pStmt);
68377       p->pStmt = 0;
68378     }else{
68379       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68380       p->nByte = sqlite3VdbeSerialTypeLen(type);
68381       p->pCsr =  v->apCsr[0]->pCursor;
68382       sqlite3BtreeEnterCursor(p->pCsr);
68383       sqlite3BtreeCacheOverflow(p->pCsr);
68384       sqlite3BtreeLeaveCursor(p->pCsr);
68385     }
68386   }
68387
68388   if( rc==SQLITE_ROW ){
68389     rc = SQLITE_OK;
68390   }else if( p->pStmt ){
68391     rc = sqlite3_finalize(p->pStmt);
68392     p->pStmt = 0;
68393     if( rc==SQLITE_OK ){
68394       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68395       rc = SQLITE_ERROR;
68396     }else{
68397       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
68398     }
68399   }
68400
68401   assert( rc!=SQLITE_OK || zErr==0 );
68402   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
68403
68404   *pzErr = zErr;
68405   return rc;
68406 }
68407
68408 /*
68409 ** Open a blob handle.
68410 */
68411 SQLITE_API int sqlite3_blob_open(
68412   sqlite3* db,            /* The database connection */
68413   const char *zDb,        /* The attached database containing the blob */
68414   const char *zTable,     /* The table containing the blob */
68415   const char *zColumn,    /* The column containing the blob */
68416   sqlite_int64 iRow,      /* The row containing the glob */
68417   int flags,              /* True -> read/write access, false -> read-only */
68418   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
68419 ){
68420   int nAttempt = 0;
68421   int iCol;               /* Index of zColumn in row-record */
68422
68423   /* This VDBE program seeks a btree cursor to the identified 
68424   ** db/table/row entry. The reason for using a vdbe program instead
68425   ** of writing code to use the b-tree layer directly is that the
68426   ** vdbe program will take advantage of the various transaction,
68427   ** locking and error handling infrastructure built into the vdbe.
68428   **
68429   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
68430   ** Code external to the Vdbe then "borrows" the b-tree cursor and
68431   ** uses it to implement the blob_read(), blob_write() and 
68432   ** blob_bytes() functions.
68433   **
68434   ** The sqlite3_blob_close() function finalizes the vdbe program,
68435   ** which closes the b-tree cursor and (possibly) commits the 
68436   ** transaction.
68437   */
68438   static const VdbeOpList openBlob[] = {
68439     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
68440     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
68441     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
68442
68443     /* One of the following two instructions is replaced by an OP_Noop. */
68444     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
68445     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
68446
68447     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
68448     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
68449     {OP_Column, 0, 0, 1},          /* 7  */
68450     {OP_ResultRow, 1, 0, 0},       /* 8  */
68451     {OP_Goto, 0, 5, 0},            /* 9  */
68452     {OP_Close, 0, 0, 0},           /* 10 */
68453     {OP_Halt, 0, 0, 0},            /* 11 */
68454   };
68455
68456   int rc = SQLITE_OK;
68457   char *zErr = 0;
68458   Table *pTab;
68459   Parse *pParse = 0;
68460   Incrblob *pBlob = 0;
68461
68462   flags = !!flags;                /* flags = (flags ? 1 : 0); */
68463   *ppBlob = 0;
68464
68465   sqlite3_mutex_enter(db->mutex);
68466
68467   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
68468   if( !pBlob ) goto blob_open_out;
68469   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
68470   if( !pParse ) goto blob_open_out;
68471
68472   do {
68473     memset(pParse, 0, sizeof(Parse));
68474     pParse->db = db;
68475     sqlite3DbFree(db, zErr);
68476     zErr = 0;
68477
68478     sqlite3BtreeEnterAll(db);
68479     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
68480     if( pTab && IsVirtual(pTab) ){
68481       pTab = 0;
68482       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
68483     }
68484 #ifndef SQLITE_OMIT_VIEW
68485     if( pTab && pTab->pSelect ){
68486       pTab = 0;
68487       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
68488     }
68489 #endif
68490     if( !pTab ){
68491       if( pParse->zErrMsg ){
68492         sqlite3DbFree(db, zErr);
68493         zErr = pParse->zErrMsg;
68494         pParse->zErrMsg = 0;
68495       }
68496       rc = SQLITE_ERROR;
68497       sqlite3BtreeLeaveAll(db);
68498       goto blob_open_out;
68499     }
68500
68501     /* Now search pTab for the exact column. */
68502     for(iCol=0; iCol<pTab->nCol; iCol++) {
68503       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
68504         break;
68505       }
68506     }
68507     if( iCol==pTab->nCol ){
68508       sqlite3DbFree(db, zErr);
68509       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
68510       rc = SQLITE_ERROR;
68511       sqlite3BtreeLeaveAll(db);
68512       goto blob_open_out;
68513     }
68514
68515     /* If the value is being opened for writing, check that the
68516     ** column is not indexed, and that it is not part of a foreign key. 
68517     ** It is against the rules to open a column to which either of these
68518     ** descriptions applies for writing.  */
68519     if( flags ){
68520       const char *zFault = 0;
68521       Index *pIdx;
68522 #ifndef SQLITE_OMIT_FOREIGN_KEY
68523       if( db->flags&SQLITE_ForeignKeys ){
68524         /* Check that the column is not part of an FK child key definition. It
68525         ** is not necessary to check if it is part of a parent key, as parent
68526         ** key columns must be indexed. The check below will pick up this 
68527         ** case.  */
68528         FKey *pFKey;
68529         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
68530           int j;
68531           for(j=0; j<pFKey->nCol; j++){
68532             if( pFKey->aCol[j].iFrom==iCol ){
68533               zFault = "foreign key";
68534             }
68535           }
68536         }
68537       }
68538 #endif
68539       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68540         int j;
68541         for(j=0; j<pIdx->nColumn; j++){
68542           if( pIdx->aiColumn[j]==iCol ){
68543             zFault = "indexed";
68544           }
68545         }
68546       }
68547       if( zFault ){
68548         sqlite3DbFree(db, zErr);
68549         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
68550         rc = SQLITE_ERROR;
68551         sqlite3BtreeLeaveAll(db);
68552         goto blob_open_out;
68553       }
68554     }
68555
68556     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
68557     assert( pBlob->pStmt || db->mallocFailed );
68558     if( pBlob->pStmt ){
68559       Vdbe *v = (Vdbe *)pBlob->pStmt;
68560       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68561
68562       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
68563
68564
68565       /* Configure the OP_Transaction */
68566       sqlite3VdbeChangeP1(v, 0, iDb);
68567       sqlite3VdbeChangeP2(v, 0, flags);
68568
68569       /* Configure the OP_VerifyCookie */
68570       sqlite3VdbeChangeP1(v, 1, iDb);
68571       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
68572       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
68573
68574       /* Make sure a mutex is held on the table to be accessed */
68575       sqlite3VdbeUsesBtree(v, iDb); 
68576
68577       /* Configure the OP_TableLock instruction */
68578 #ifdef SQLITE_OMIT_SHARED_CACHE
68579       sqlite3VdbeChangeToNoop(v, 2, 1);
68580 #else
68581       sqlite3VdbeChangeP1(v, 2, iDb);
68582       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
68583       sqlite3VdbeChangeP3(v, 2, flags);
68584       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
68585 #endif
68586
68587       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
68588       ** parameter of the other to pTab->tnum.  */
68589       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
68590       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
68591       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
68592
68593       /* Configure the number of columns. Configure the cursor to
68594       ** think that the table has one more column than it really
68595       ** does. An OP_Column to retrieve this imaginary column will
68596       ** always return an SQL NULL. This is useful because it means
68597       ** we can invoke OP_Column to fill in the vdbe cursors type 
68598       ** and offset cache without causing any IO.
68599       */
68600       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
68601       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
68602       if( !db->mallocFailed ){
68603         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
68604       }
68605     }
68606    
68607     pBlob->flags = flags;
68608     pBlob->iCol = iCol;
68609     pBlob->db = db;
68610     sqlite3BtreeLeaveAll(db);
68611     if( db->mallocFailed ){
68612       goto blob_open_out;
68613     }
68614     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
68615     rc = blobSeekToRow(pBlob, iRow, &zErr);
68616   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
68617
68618 blob_open_out:
68619   if( rc==SQLITE_OK && db->mallocFailed==0 ){
68620     *ppBlob = (sqlite3_blob *)pBlob;
68621   }else{
68622     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
68623     sqlite3DbFree(db, pBlob);
68624   }
68625   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68626   sqlite3DbFree(db, zErr);
68627   sqlite3StackFree(db, pParse);
68628   rc = sqlite3ApiExit(db, rc);
68629   sqlite3_mutex_leave(db->mutex);
68630   return rc;
68631 }
68632
68633 /*
68634 ** Close a blob handle that was previously created using
68635 ** sqlite3_blob_open().
68636 */
68637 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
68638   Incrblob *p = (Incrblob *)pBlob;
68639   int rc;
68640   sqlite3 *db;
68641
68642   if( p ){
68643     db = p->db;
68644     sqlite3_mutex_enter(db->mutex);
68645     rc = sqlite3_finalize(p->pStmt);
68646     sqlite3DbFree(db, p);
68647     sqlite3_mutex_leave(db->mutex);
68648   }else{
68649     rc = SQLITE_OK;
68650   }
68651   return rc;
68652 }
68653
68654 /*
68655 ** Perform a read or write operation on a blob
68656 */
68657 static int blobReadWrite(
68658   sqlite3_blob *pBlob, 
68659   void *z, 
68660   int n, 
68661   int iOffset, 
68662   int (*xCall)(BtCursor*, u32, u32, void*)
68663 ){
68664   int rc;
68665   Incrblob *p = (Incrblob *)pBlob;
68666   Vdbe *v;
68667   sqlite3 *db;
68668
68669   if( p==0 ) return SQLITE_MISUSE_BKPT;
68670   db = p->db;
68671   sqlite3_mutex_enter(db->mutex);
68672   v = (Vdbe*)p->pStmt;
68673
68674   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
68675     /* Request is out of range. Return a transient error. */
68676     rc = SQLITE_ERROR;
68677     sqlite3Error(db, SQLITE_ERROR, 0);
68678   }else if( v==0 ){
68679     /* If there is no statement handle, then the blob-handle has
68680     ** already been invalidated. Return SQLITE_ABORT in this case.
68681     */
68682     rc = SQLITE_ABORT;
68683   }else{
68684     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
68685     ** returned, clean-up the statement handle.
68686     */
68687     assert( db == v->db );
68688     sqlite3BtreeEnterCursor(p->pCsr);
68689     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
68690     sqlite3BtreeLeaveCursor(p->pCsr);
68691     if( rc==SQLITE_ABORT ){
68692       sqlite3VdbeFinalize(v);
68693       p->pStmt = 0;
68694     }else{
68695       db->errCode = rc;
68696       v->rc = rc;
68697     }
68698   }
68699   rc = sqlite3ApiExit(db, rc);
68700   sqlite3_mutex_leave(db->mutex);
68701   return rc;
68702 }
68703
68704 /*
68705 ** Read data from a blob handle.
68706 */
68707 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
68708   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
68709 }
68710
68711 /*
68712 ** Write data to a blob handle.
68713 */
68714 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
68715   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
68716 }
68717
68718 /*
68719 ** Query a blob handle for the size of the data.
68720 **
68721 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
68722 ** so no mutex is required for access.
68723 */
68724 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
68725   Incrblob *p = (Incrblob *)pBlob;
68726   return (p && p->pStmt) ? p->nByte : 0;
68727 }
68728
68729 /*
68730 ** Move an existing blob handle to point to a different row of the same
68731 ** database table.
68732 **
68733 ** If an error occurs, or if the specified row does not exist or does not
68734 ** contain a blob or text value, then an error code is returned and the
68735 ** database handle error code and message set. If this happens, then all 
68736 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
68737 ** immediately return SQLITE_ABORT.
68738 */
68739 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
68740   int rc;
68741   Incrblob *p = (Incrblob *)pBlob;
68742   sqlite3 *db;
68743
68744   if( p==0 ) return SQLITE_MISUSE_BKPT;
68745   db = p->db;
68746   sqlite3_mutex_enter(db->mutex);
68747
68748   if( p->pStmt==0 ){
68749     /* If there is no statement handle, then the blob-handle has
68750     ** already been invalidated. Return SQLITE_ABORT in this case.
68751     */
68752     rc = SQLITE_ABORT;
68753   }else{
68754     char *zErr;
68755     rc = blobSeekToRow(p, iRow, &zErr);
68756     if( rc!=SQLITE_OK ){
68757       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68758       sqlite3DbFree(db, zErr);
68759     }
68760     assert( rc!=SQLITE_SCHEMA );
68761   }
68762
68763   rc = sqlite3ApiExit(db, rc);
68764   assert( rc==SQLITE_OK || p->pStmt==0 );
68765   sqlite3_mutex_leave(db->mutex);
68766   return rc;
68767 }
68768
68769 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
68770
68771 /************** End of vdbeblob.c ********************************************/
68772 /************** Begin file journal.c *****************************************/
68773 /*
68774 ** 2007 August 22
68775 **
68776 ** The author disclaims copyright to this source code.  In place of
68777 ** a legal notice, here is a blessing:
68778 **
68779 **    May you do good and not evil.
68780 **    May you find forgiveness for yourself and forgive others.
68781 **    May you share freely, never taking more than you give.
68782 **
68783 *************************************************************************
68784 **
68785 ** This file implements a special kind of sqlite3_file object used
68786 ** by SQLite to create journal files if the atomic-write optimization
68787 ** is enabled.
68788 **
68789 ** The distinctive characteristic of this sqlite3_file is that the
68790 ** actual on disk file is created lazily. When the file is created,
68791 ** the caller specifies a buffer size for an in-memory buffer to
68792 ** be used to service read() and write() requests. The actual file
68793 ** on disk is not created or populated until either:
68794 **
68795 **   1) The in-memory representation grows too large for the allocated 
68796 **      buffer, or
68797 **   2) The sqlite3JournalCreate() function is called.
68798 */
68799 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
68800
68801
68802 /*
68803 ** A JournalFile object is a subclass of sqlite3_file used by
68804 ** as an open file handle for journal files.
68805 */
68806 struct JournalFile {
68807   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
68808   int nBuf;                       /* Size of zBuf[] in bytes */
68809   char *zBuf;                     /* Space to buffer journal writes */
68810   int iSize;                      /* Amount of zBuf[] currently used */
68811   int flags;                      /* xOpen flags */
68812   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
68813   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
68814   const char *zJournal;           /* Name of the journal file */
68815 };
68816 typedef struct JournalFile JournalFile;
68817
68818 /*
68819 ** If it does not already exists, create and populate the on-disk file 
68820 ** for JournalFile p.
68821 */
68822 static int createFile(JournalFile *p){
68823   int rc = SQLITE_OK;
68824   if( !p->pReal ){
68825     sqlite3_file *pReal = (sqlite3_file *)&p[1];
68826     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
68827     if( rc==SQLITE_OK ){
68828       p->pReal = pReal;
68829       if( p->iSize>0 ){
68830         assert(p->iSize<=p->nBuf);
68831         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
68832       }
68833     }
68834   }
68835   return rc;
68836 }
68837
68838 /*
68839 ** Close the file.
68840 */
68841 static int jrnlClose(sqlite3_file *pJfd){
68842   JournalFile *p = (JournalFile *)pJfd;
68843   if( p->pReal ){
68844     sqlite3OsClose(p->pReal);
68845   }
68846   sqlite3_free(p->zBuf);
68847   return SQLITE_OK;
68848 }
68849
68850 /*
68851 ** Read data from the file.
68852 */
68853 static int jrnlRead(
68854   sqlite3_file *pJfd,    /* The journal file from which to read */
68855   void *zBuf,            /* Put the results here */
68856   int iAmt,              /* Number of bytes to read */
68857   sqlite_int64 iOfst     /* Begin reading at this offset */
68858 ){
68859   int rc = SQLITE_OK;
68860   JournalFile *p = (JournalFile *)pJfd;
68861   if( p->pReal ){
68862     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
68863   }else if( (iAmt+iOfst)>p->iSize ){
68864     rc = SQLITE_IOERR_SHORT_READ;
68865   }else{
68866     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
68867   }
68868   return rc;
68869 }
68870
68871 /*
68872 ** Write data to the file.
68873 */
68874 static int jrnlWrite(
68875   sqlite3_file *pJfd,    /* The journal file into which to write */
68876   const void *zBuf,      /* Take data to be written from here */
68877   int iAmt,              /* Number of bytes to write */
68878   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
68879 ){
68880   int rc = SQLITE_OK;
68881   JournalFile *p = (JournalFile *)pJfd;
68882   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
68883     rc = createFile(p);
68884   }
68885   if( rc==SQLITE_OK ){
68886     if( p->pReal ){
68887       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
68888     }else{
68889       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
68890       if( p->iSize<(iOfst+iAmt) ){
68891         p->iSize = (iOfst+iAmt);
68892       }
68893     }
68894   }
68895   return rc;
68896 }
68897
68898 /*
68899 ** Truncate the file.
68900 */
68901 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
68902   int rc = SQLITE_OK;
68903   JournalFile *p = (JournalFile *)pJfd;
68904   if( p->pReal ){
68905     rc = sqlite3OsTruncate(p->pReal, size);
68906   }else if( size<p->iSize ){
68907     p->iSize = size;
68908   }
68909   return rc;
68910 }
68911
68912 /*
68913 ** Sync the file.
68914 */
68915 static int jrnlSync(sqlite3_file *pJfd, int flags){
68916   int rc;
68917   JournalFile *p = (JournalFile *)pJfd;
68918   if( p->pReal ){
68919     rc = sqlite3OsSync(p->pReal, flags);
68920   }else{
68921     rc = SQLITE_OK;
68922   }
68923   return rc;
68924 }
68925
68926 /*
68927 ** Query the size of the file in bytes.
68928 */
68929 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
68930   int rc = SQLITE_OK;
68931   JournalFile *p = (JournalFile *)pJfd;
68932   if( p->pReal ){
68933     rc = sqlite3OsFileSize(p->pReal, pSize);
68934   }else{
68935     *pSize = (sqlite_int64) p->iSize;
68936   }
68937   return rc;
68938 }
68939
68940 /*
68941 ** Table of methods for JournalFile sqlite3_file object.
68942 */
68943 static struct sqlite3_io_methods JournalFileMethods = {
68944   1,             /* iVersion */
68945   jrnlClose,     /* xClose */
68946   jrnlRead,      /* xRead */
68947   jrnlWrite,     /* xWrite */
68948   jrnlTruncate,  /* xTruncate */
68949   jrnlSync,      /* xSync */
68950   jrnlFileSize,  /* xFileSize */
68951   0,             /* xLock */
68952   0,             /* xUnlock */
68953   0,             /* xCheckReservedLock */
68954   0,             /* xFileControl */
68955   0,             /* xSectorSize */
68956   0,             /* xDeviceCharacteristics */
68957   0,             /* xShmMap */
68958   0,             /* xShmLock */
68959   0,             /* xShmBarrier */
68960   0              /* xShmUnmap */
68961 };
68962
68963 /* 
68964 ** Open a journal file.
68965 */
68966 SQLITE_PRIVATE int sqlite3JournalOpen(
68967   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
68968   const char *zName,         /* Name of the journal file */
68969   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
68970   int flags,                 /* Opening flags */
68971   int nBuf                   /* Bytes buffered before opening the file */
68972 ){
68973   JournalFile *p = (JournalFile *)pJfd;
68974   memset(p, 0, sqlite3JournalSize(pVfs));
68975   if( nBuf>0 ){
68976     p->zBuf = sqlite3MallocZero(nBuf);
68977     if( !p->zBuf ){
68978       return SQLITE_NOMEM;
68979     }
68980   }else{
68981     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
68982   }
68983   p->pMethod = &JournalFileMethods;
68984   p->nBuf = nBuf;
68985   p->flags = flags;
68986   p->zJournal = zName;
68987   p->pVfs = pVfs;
68988   return SQLITE_OK;
68989 }
68990
68991 /*
68992 ** If the argument p points to a JournalFile structure, and the underlying
68993 ** file has not yet been created, create it now.
68994 */
68995 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
68996   if( p->pMethods!=&JournalFileMethods ){
68997     return SQLITE_OK;
68998   }
68999   return createFile((JournalFile *)p);
69000 }
69001
69002 /* 
69003 ** Return the number of bytes required to store a JournalFile that uses vfs
69004 ** pVfs to create the underlying on-disk files.
69005 */
69006 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
69007   return (pVfs->szOsFile+sizeof(JournalFile));
69008 }
69009 #endif
69010
69011 /************** End of journal.c *********************************************/
69012 /************** Begin file memjournal.c **************************************/
69013 /*
69014 ** 2008 October 7
69015 **
69016 ** The author disclaims copyright to this source code.  In place of
69017 ** a legal notice, here is a blessing:
69018 **
69019 **    May you do good and not evil.
69020 **    May you find forgiveness for yourself and forgive others.
69021 **    May you share freely, never taking more than you give.
69022 **
69023 *************************************************************************
69024 **
69025 ** This file contains code use to implement an in-memory rollback journal.
69026 ** The in-memory rollback journal is used to journal transactions for
69027 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69028 */
69029
69030 /* Forward references to internal structures */
69031 typedef struct MemJournal MemJournal;
69032 typedef struct FilePoint FilePoint;
69033 typedef struct FileChunk FileChunk;
69034
69035 /* Space to hold the rollback journal is allocated in increments of
69036 ** this many bytes.
69037 **
69038 ** The size chosen is a little less than a power of two.  That way,
69039 ** the FileChunk object will have a size that almost exactly fills
69040 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
69041 ** memory allocators.
69042 */
69043 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69044
69045 /* Macro to find the minimum of two numeric values.
69046 */
69047 #ifndef MIN
69048 # define MIN(x,y) ((x)<(y)?(x):(y))
69049 #endif
69050
69051 /*
69052 ** The rollback journal is composed of a linked list of these structures.
69053 */
69054 struct FileChunk {
69055   FileChunk *pNext;               /* Next chunk in the journal */
69056   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
69057 };
69058
69059 /*
69060 ** An instance of this object serves as a cursor into the rollback journal.
69061 ** The cursor can be either for reading or writing.
69062 */
69063 struct FilePoint {
69064   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
69065   FileChunk *pChunk;              /* Specific chunk into which cursor points */
69066 };
69067
69068 /*
69069 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
69070 ** is an instance of this class.
69071 */
69072 struct MemJournal {
69073   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
69074   FileChunk *pFirst;              /* Head of in-memory chunk-list */
69075   FilePoint endpoint;             /* Pointer to the end of the file */
69076   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
69077 };
69078
69079 /*
69080 ** Read data from the in-memory journal file.  This is the implementation
69081 ** of the sqlite3_vfs.xRead method.
69082 */
69083 static int memjrnlRead(
69084   sqlite3_file *pJfd,    /* The journal file from which to read */
69085   void *zBuf,            /* Put the results here */
69086   int iAmt,              /* Number of bytes to read */
69087   sqlite_int64 iOfst     /* Begin reading at this offset */
69088 ){
69089   MemJournal *p = (MemJournal *)pJfd;
69090   u8 *zOut = zBuf;
69091   int nRead = iAmt;
69092   int iChunkOffset;
69093   FileChunk *pChunk;
69094
69095   /* SQLite never tries to read past the end of a rollback journal file */
69096   assert( iOfst+iAmt<=p->endpoint.iOffset );
69097
69098   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69099     sqlite3_int64 iOff = 0;
69100     for(pChunk=p->pFirst; 
69101         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69102         pChunk=pChunk->pNext
69103     ){
69104       iOff += JOURNAL_CHUNKSIZE;
69105     }
69106   }else{
69107     pChunk = p->readpoint.pChunk;
69108   }
69109
69110   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69111   do {
69112     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69113     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69114     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69115     zOut += nCopy;
69116     nRead -= iSpace;
69117     iChunkOffset = 0;
69118   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69119   p->readpoint.iOffset = iOfst+iAmt;
69120   p->readpoint.pChunk = pChunk;
69121
69122   return SQLITE_OK;
69123 }
69124
69125 /*
69126 ** Write data to the file.
69127 */
69128 static int memjrnlWrite(
69129   sqlite3_file *pJfd,    /* The journal file into which to write */
69130   const void *zBuf,      /* Take data to be written from here */
69131   int iAmt,              /* Number of bytes to write */
69132   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69133 ){
69134   MemJournal *p = (MemJournal *)pJfd;
69135   int nWrite = iAmt;
69136   u8 *zWrite = (u8 *)zBuf;
69137
69138   /* An in-memory journal file should only ever be appended to. Random
69139   ** access writes are not required by sqlite.
69140   */
69141   assert( iOfst==p->endpoint.iOffset );
69142   UNUSED_PARAMETER(iOfst);
69143
69144   while( nWrite>0 ){
69145     FileChunk *pChunk = p->endpoint.pChunk;
69146     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69147     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69148
69149     if( iChunkOffset==0 ){
69150       /* New chunk is required to extend the file. */
69151       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69152       if( !pNew ){
69153         return SQLITE_IOERR_NOMEM;
69154       }
69155       pNew->pNext = 0;
69156       if( pChunk ){
69157         assert( p->pFirst );
69158         pChunk->pNext = pNew;
69159       }else{
69160         assert( !p->pFirst );
69161         p->pFirst = pNew;
69162       }
69163       p->endpoint.pChunk = pNew;
69164     }
69165
69166     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69167     zWrite += iSpace;
69168     nWrite -= iSpace;
69169     p->endpoint.iOffset += iSpace;
69170   }
69171
69172   return SQLITE_OK;
69173 }
69174
69175 /*
69176 ** Truncate the file.
69177 */
69178 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69179   MemJournal *p = (MemJournal *)pJfd;
69180   FileChunk *pChunk;
69181   assert(size==0);
69182   UNUSED_PARAMETER(size);
69183   pChunk = p->pFirst;
69184   while( pChunk ){
69185     FileChunk *pTmp = pChunk;
69186     pChunk = pChunk->pNext;
69187     sqlite3_free(pTmp);
69188   }
69189   sqlite3MemJournalOpen(pJfd);
69190   return SQLITE_OK;
69191 }
69192
69193 /*
69194 ** Close the file.
69195 */
69196 static int memjrnlClose(sqlite3_file *pJfd){
69197   memjrnlTruncate(pJfd, 0);
69198   return SQLITE_OK;
69199 }
69200
69201
69202 /*
69203 ** Sync the file.
69204 **
69205 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
69206 ** is never called in a working implementation.  This implementation
69207 ** exists purely as a contingency, in case some malfunction in some other
69208 ** part of SQLite causes Sync to be called by mistake.
69209 */
69210 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69211   UNUSED_PARAMETER2(NotUsed, NotUsed2);
69212   return SQLITE_OK;
69213 }
69214
69215 /*
69216 ** Query the size of the file in bytes.
69217 */
69218 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69219   MemJournal *p = (MemJournal *)pJfd;
69220   *pSize = (sqlite_int64) p->endpoint.iOffset;
69221   return SQLITE_OK;
69222 }
69223
69224 /*
69225 ** Table of methods for MemJournal sqlite3_file object.
69226 */
69227 static const struct sqlite3_io_methods MemJournalMethods = {
69228   1,                /* iVersion */
69229   memjrnlClose,     /* xClose */
69230   memjrnlRead,      /* xRead */
69231   memjrnlWrite,     /* xWrite */
69232   memjrnlTruncate,  /* xTruncate */
69233   memjrnlSync,      /* xSync */
69234   memjrnlFileSize,  /* xFileSize */
69235   0,                /* xLock */
69236   0,                /* xUnlock */
69237   0,                /* xCheckReservedLock */
69238   0,                /* xFileControl */
69239   0,                /* xSectorSize */
69240   0,                /* xDeviceCharacteristics */
69241   0,                /* xShmMap */
69242   0,                /* xShmLock */
69243   0,                /* xShmBarrier */
69244   0                 /* xShmUnlock */
69245 };
69246
69247 /* 
69248 ** Open a journal file.
69249 */
69250 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69251   MemJournal *p = (MemJournal *)pJfd;
69252   assert( EIGHT_BYTE_ALIGNMENT(p) );
69253   memset(p, 0, sqlite3MemJournalSize());
69254   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69255 }
69256
69257 /*
69258 ** Return true if the file-handle passed as an argument is 
69259 ** an in-memory journal 
69260 */
69261 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69262   return pJfd->pMethods==&MemJournalMethods;
69263 }
69264
69265 /* 
69266 ** Return the number of bytes required to store a MemJournal file descriptor.
69267 */
69268 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69269   return sizeof(MemJournal);
69270 }
69271
69272 /************** End of memjournal.c ******************************************/
69273 /************** Begin file walker.c ******************************************/
69274 /*
69275 ** 2008 August 16
69276 **
69277 ** The author disclaims copyright to this source code.  In place of
69278 ** a legal notice, here is a blessing:
69279 **
69280 **    May you do good and not evil.
69281 **    May you find forgiveness for yourself and forgive others.
69282 **    May you share freely, never taking more than you give.
69283 **
69284 *************************************************************************
69285 ** This file contains routines used for walking the parser tree for
69286 ** an SQL statement.
69287 */
69288
69289
69290 /*
69291 ** Walk an expression tree.  Invoke the callback once for each node
69292 ** of the expression, while decending.  (In other words, the callback
69293 ** is invoked before visiting children.)
69294 **
69295 ** The return value from the callback should be one of the WRC_*
69296 ** constants to specify how to proceed with the walk.
69297 **
69298 **    WRC_Continue      Continue descending down the tree.
69299 **
69300 **    WRC_Prune         Do not descend into child nodes.  But allow
69301 **                      the walk to continue with sibling nodes.
69302 **
69303 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
69304 **                      return the top-level walk call.
69305 **
69306 ** The return value from this routine is WRC_Abort to abandon the tree walk
69307 ** and WRC_Continue to continue.
69308 */
69309 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69310   int rc;
69311   if( pExpr==0 ) return WRC_Continue;
69312   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69313   testcase( ExprHasProperty(pExpr, EP_Reduced) );
69314   rc = pWalker->xExprCallback(pWalker, pExpr);
69315   if( rc==WRC_Continue
69316               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69317     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69318     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69319     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69320       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69321     }else{
69322       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69323     }
69324   }
69325   return rc & WRC_Abort;
69326 }
69327
69328 /*
69329 ** Call sqlite3WalkExpr() for every expression in list p or until
69330 ** an abort request is seen.
69331 */
69332 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69333   int i;
69334   struct ExprList_item *pItem;
69335   if( p ){
69336     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69337       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69338     }
69339   }
69340   return WRC_Continue;
69341 }
69342
69343 /*
69344 ** Walk all expressions associated with SELECT statement p.  Do
69345 ** not invoke the SELECT callback on p, but do (of course) invoke
69346 ** any expr callbacks and SELECT callbacks that come from subqueries.
69347 ** Return WRC_Abort or WRC_Continue.
69348 */
69349 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69350   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69351   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69352   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69353   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69354   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69355   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69356   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69357   return WRC_Continue;
69358 }
69359
69360 /*
69361 ** Walk the parse trees associated with all subqueries in the
69362 ** FROM clause of SELECT statement p.  Do not invoke the select
69363 ** callback on p, but do invoke it on each FROM clause subquery
69364 ** and on any subqueries further down in the tree.  Return 
69365 ** WRC_Abort or WRC_Continue;
69366 */
69367 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69368   SrcList *pSrc;
69369   int i;
69370   struct SrcList_item *pItem;
69371
69372   pSrc = p->pSrc;
69373   if( ALWAYS(pSrc) ){
69374     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69375       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69376         return WRC_Abort;
69377       }
69378     }
69379   }
69380   return WRC_Continue;
69381
69382
69383 /*
69384 ** Call sqlite3WalkExpr() for every expression in Select statement p.
69385 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69386 ** on the compound select chain, p->pPrior.
69387 **
69388 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
69389 ** there is an abort request.
69390 **
69391 ** If the Walker does not have an xSelectCallback() then this routine
69392 ** is a no-op returning WRC_Continue.
69393 */
69394 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
69395   int rc;
69396   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
69397   rc = WRC_Continue;
69398   while( p  ){
69399     rc = pWalker->xSelectCallback(pWalker, p);
69400     if( rc ) break;
69401     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
69402     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
69403     p = p->pPrior;
69404   }
69405   return rc & WRC_Abort;
69406 }
69407
69408 /************** End of walker.c **********************************************/
69409 /************** Begin file resolve.c *****************************************/
69410 /*
69411 ** 2008 August 18
69412 **
69413 ** The author disclaims copyright to this source code.  In place of
69414 ** a legal notice, here is a blessing:
69415 **
69416 **    May you do good and not evil.
69417 **    May you find forgiveness for yourself and forgive others.
69418 **    May you share freely, never taking more than you give.
69419 **
69420 *************************************************************************
69421 **
69422 ** This file contains routines used for walking the parser tree and
69423 ** resolve all identifiers by associating them with a particular
69424 ** table and column.
69425 */
69426
69427 /*
69428 ** Turn the pExpr expression into an alias for the iCol-th column of the
69429 ** result set in pEList.
69430 **
69431 ** If the result set column is a simple column reference, then this routine
69432 ** makes an exact copy.  But for any other kind of expression, this
69433 ** routine make a copy of the result set column as the argument to the
69434 ** TK_AS operator.  The TK_AS operator causes the expression to be
69435 ** evaluated just once and then reused for each alias.
69436 **
69437 ** The reason for suppressing the TK_AS term when the expression is a simple
69438 ** column reference is so that the column reference will be recognized as
69439 ** usable by indices within the WHERE clause processing logic. 
69440 **
69441 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
69442 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
69443 **
69444 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
69445 **
69446 ** Is equivalent to:
69447 **
69448 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
69449 **
69450 ** The result of random()%5 in the GROUP BY clause is probably different
69451 ** from the result in the result-set.  We might fix this someday.  Or
69452 ** then again, we might not...
69453 */
69454 static void resolveAlias(
69455   Parse *pParse,         /* Parsing context */
69456   ExprList *pEList,      /* A result set */
69457   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
69458   Expr *pExpr,           /* Transform this into an alias to the result set */
69459   const char *zType      /* "GROUP" or "ORDER" or "" */
69460 ){
69461   Expr *pOrig;           /* The iCol-th column of the result set */
69462   Expr *pDup;            /* Copy of pOrig */
69463   sqlite3 *db;           /* The database connection */
69464
69465   assert( iCol>=0 && iCol<pEList->nExpr );
69466   pOrig = pEList->a[iCol].pExpr;
69467   assert( pOrig!=0 );
69468   assert( pOrig->flags & EP_Resolved );
69469   db = pParse->db;
69470   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
69471     pDup = sqlite3ExprDup(db, pOrig, 0);
69472     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69473     if( pDup==0 ) return;
69474     if( pEList->a[iCol].iAlias==0 ){
69475       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
69476     }
69477     pDup->iTable = pEList->a[iCol].iAlias;
69478   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
69479     pDup = sqlite3ExprDup(db, pOrig, 0);
69480     if( pDup==0 ) return;
69481   }else{
69482     char *zToken = pOrig->u.zToken;
69483     assert( zToken!=0 );
69484     pOrig->u.zToken = 0;
69485     pDup = sqlite3ExprDup(db, pOrig, 0);
69486     pOrig->u.zToken = zToken;
69487     if( pDup==0 ) return;
69488     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
69489     pDup->flags2 |= EP2_MallocedToken;
69490     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
69491   }
69492   if( pExpr->flags & EP_ExpCollate ){
69493     pDup->pColl = pExpr->pColl;
69494     pDup->flags |= EP_ExpCollate;
69495   }
69496
69497   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
69498   ** prevents ExprDelete() from deleting the Expr structure itself,
69499   ** allowing it to be repopulated by the memcpy() on the following line.
69500   */
69501   ExprSetProperty(pExpr, EP_Static);
69502   sqlite3ExprDelete(db, pExpr);
69503   memcpy(pExpr, pDup, sizeof(*pExpr));
69504   sqlite3DbFree(db, pDup);
69505 }
69506
69507 /*
69508 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
69509 ** that name in the set of source tables in pSrcList and make the pExpr 
69510 ** expression node refer back to that source column.  The following changes
69511 ** are made to pExpr:
69512 **
69513 **    pExpr->iDb           Set the index in db->aDb[] of the database X
69514 **                         (even if X is implied).
69515 **    pExpr->iTable        Set to the cursor number for the table obtained
69516 **                         from pSrcList.
69517 **    pExpr->pTab          Points to the Table structure of X.Y (even if
69518 **                         X and/or Y are implied.)
69519 **    pExpr->iColumn       Set to the column number within the table.
69520 **    pExpr->op            Set to TK_COLUMN.
69521 **    pExpr->pLeft         Any expression this points to is deleted
69522 **    pExpr->pRight        Any expression this points to is deleted.
69523 **
69524 ** The zDb variable is the name of the database (the "X").  This value may be
69525 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
69526 ** can be used.  The zTable variable is the name of the table (the "Y").  This
69527 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
69528 ** means that the form of the name is Z and that columns from any table
69529 ** can be used.
69530 **
69531 ** If the name cannot be resolved unambiguously, leave an error message
69532 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
69533 */
69534 static int lookupName(
69535   Parse *pParse,       /* The parsing context */
69536   const char *zDb,     /* Name of the database containing table, or NULL */
69537   const char *zTab,    /* Name of table containing column, or NULL */
69538   const char *zCol,    /* Name of the column. */
69539   NameContext *pNC,    /* The name context used to resolve the name */
69540   Expr *pExpr          /* Make this EXPR node point to the selected column */
69541 ){
69542   int i, j;            /* Loop counters */
69543   int cnt = 0;                      /* Number of matching column names */
69544   int cntTab = 0;                   /* Number of matching table names */
69545   sqlite3 *db = pParse->db;         /* The database connection */
69546   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
69547   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
69548   NameContext *pTopNC = pNC;        /* First namecontext in the list */
69549   Schema *pSchema = 0;              /* Schema of the expression */
69550   int isTrigger = 0;
69551
69552   assert( pNC );     /* the name context cannot be NULL. */
69553   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
69554   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69555
69556   /* Initialize the node to no-match */
69557   pExpr->iTable = -1;
69558   pExpr->pTab = 0;
69559   ExprSetIrreducible(pExpr);
69560
69561   /* Start at the inner-most context and move outward until a match is found */
69562   while( pNC && cnt==0 ){
69563     ExprList *pEList;
69564     SrcList *pSrcList = pNC->pSrcList;
69565
69566     if( pSrcList ){
69567       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
69568         Table *pTab;
69569         int iDb;
69570         Column *pCol;
69571   
69572         pTab = pItem->pTab;
69573         assert( pTab!=0 && pTab->zName!=0 );
69574         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69575         assert( pTab->nCol>0 );
69576         if( zTab ){
69577           if( pItem->zAlias ){
69578             char *zTabName = pItem->zAlias;
69579             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
69580           }else{
69581             char *zTabName = pTab->zName;
69582             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
69583               continue;
69584             }
69585             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
69586               continue;
69587             }
69588           }
69589         }
69590         if( 0==(cntTab++) ){
69591           pExpr->iTable = pItem->iCursor;
69592           pExpr->pTab = pTab;
69593           pSchema = pTab->pSchema;
69594           pMatch = pItem;
69595         }
69596         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
69597           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69598             IdList *pUsing;
69599             cnt++;
69600             pExpr->iTable = pItem->iCursor;
69601             pExpr->pTab = pTab;
69602             pMatch = pItem;
69603             pSchema = pTab->pSchema;
69604             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
69605             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
69606             if( i<pSrcList->nSrc-1 ){
69607               if( pItem[1].jointype & JT_NATURAL ){
69608                 /* If this match occurred in the left table of a natural join,
69609                 ** then skip the right table to avoid a duplicate match */
69610                 pItem++;
69611                 i++;
69612               }else if( (pUsing = pItem[1].pUsing)!=0 ){
69613                 /* If this match occurs on a column that is in the USING clause
69614                 ** of a join, skip the search of the right table of the join
69615                 ** to avoid a duplicate match there. */
69616                 int k;
69617                 for(k=0; k<pUsing->nId; k++){
69618                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
69619                     pItem++;
69620                     i++;
69621                     break;
69622                   }
69623                 }
69624               }
69625             }
69626             break;
69627           }
69628         }
69629       }
69630     }
69631
69632 #ifndef SQLITE_OMIT_TRIGGER
69633     /* If we have not already resolved the name, then maybe 
69634     ** it is a new.* or old.* trigger argument reference
69635     */
69636     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
69637       int op = pParse->eTriggerOp;
69638       Table *pTab = 0;
69639       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
69640       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
69641         pExpr->iTable = 1;
69642         pTab = pParse->pTriggerTab;
69643       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
69644         pExpr->iTable = 0;
69645         pTab = pParse->pTriggerTab;
69646       }
69647
69648       if( pTab ){ 
69649         int iCol;
69650         pSchema = pTab->pSchema;
69651         cntTab++;
69652         for(iCol=0; iCol<pTab->nCol; iCol++){
69653           Column *pCol = &pTab->aCol[iCol];
69654           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69655             if( iCol==pTab->iPKey ){
69656               iCol = -1;
69657             }
69658             break;
69659           }
69660         }
69661         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
69662           iCol = -1;        /* IMP: R-44911-55124 */
69663         }
69664         if( iCol<pTab->nCol ){
69665           cnt++;
69666           if( iCol<0 ){
69667             pExpr->affinity = SQLITE_AFF_INTEGER;
69668           }else if( pExpr->iTable==0 ){
69669             testcase( iCol==31 );
69670             testcase( iCol==32 );
69671             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69672           }else{
69673             testcase( iCol==31 );
69674             testcase( iCol==32 );
69675             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69676           }
69677           pExpr->iColumn = (i16)iCol;
69678           pExpr->pTab = pTab;
69679           isTrigger = 1;
69680         }
69681       }
69682     }
69683 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
69684
69685     /*
69686     ** Perhaps the name is a reference to the ROWID
69687     */
69688     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
69689       cnt = 1;
69690       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
69691       pExpr->affinity = SQLITE_AFF_INTEGER;
69692     }
69693
69694     /*
69695     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
69696     ** might refer to an result-set alias.  This happens, for example, when
69697     ** we are resolving names in the WHERE clause of the following command:
69698     **
69699     **     SELECT a+b AS x FROM table WHERE x<10;
69700     **
69701     ** In cases like this, replace pExpr with a copy of the expression that
69702     ** forms the result set entry ("a+b" in the example) and return immediately.
69703     ** Note that the expression in the result set should have already been
69704     ** resolved by the time the WHERE clause is resolved.
69705     */
69706     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
69707       for(j=0; j<pEList->nExpr; j++){
69708         char *zAs = pEList->a[j].zName;
69709         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
69710           Expr *pOrig;
69711           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
69712           assert( pExpr->x.pList==0 );
69713           assert( pExpr->x.pSelect==0 );
69714           pOrig = pEList->a[j].pExpr;
69715           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
69716             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
69717             return WRC_Abort;
69718           }
69719           resolveAlias(pParse, pEList, j, pExpr, "");
69720           cnt = 1;
69721           pMatch = 0;
69722           assert( zTab==0 && zDb==0 );
69723           goto lookupname_end;
69724         }
69725       } 
69726     }
69727
69728     /* Advance to the next name context.  The loop will exit when either
69729     ** we have a match (cnt>0) or when we run out of name contexts.
69730     */
69731     if( cnt==0 ){
69732       pNC = pNC->pNext;
69733     }
69734   }
69735
69736   /*
69737   ** If X and Y are NULL (in other words if only the column name Z is
69738   ** supplied) and the value of Z is enclosed in double-quotes, then
69739   ** Z is a string literal if it doesn't match any column names.  In that
69740   ** case, we need to return right away and not make any changes to
69741   ** pExpr.
69742   **
69743   ** Because no reference was made to outer contexts, the pNC->nRef
69744   ** fields are not changed in any context.
69745   */
69746   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
69747     pExpr->op = TK_STRING;
69748     pExpr->pTab = 0;
69749     return WRC_Prune;
69750   }
69751
69752   /*
69753   ** cnt==0 means there was not match.  cnt>1 means there were two or
69754   ** more matches.  Either way, we have an error.
69755   */
69756   if( cnt!=1 ){
69757     const char *zErr;
69758     zErr = cnt==0 ? "no such column" : "ambiguous column name";
69759     if( zDb ){
69760       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
69761     }else if( zTab ){
69762       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
69763     }else{
69764       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
69765     }
69766     pParse->checkSchema = 1;
69767     pTopNC->nErr++;
69768   }
69769
69770   /* If a column from a table in pSrcList is referenced, then record
69771   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
69772   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
69773   ** column number is greater than the number of bits in the bitmask
69774   ** then set the high-order bit of the bitmask.
69775   */
69776   if( pExpr->iColumn>=0 && pMatch!=0 ){
69777     int n = pExpr->iColumn;
69778     testcase( n==BMS-1 );
69779     if( n>=BMS ){
69780       n = BMS-1;
69781     }
69782     assert( pMatch->iCursor==pExpr->iTable );
69783     pMatch->colUsed |= ((Bitmask)1)<<n;
69784   }
69785
69786   /* Clean up and return
69787   */
69788   sqlite3ExprDelete(db, pExpr->pLeft);
69789   pExpr->pLeft = 0;
69790   sqlite3ExprDelete(db, pExpr->pRight);
69791   pExpr->pRight = 0;
69792   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
69793 lookupname_end:
69794   if( cnt==1 ){
69795     assert( pNC!=0 );
69796     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
69797     /* Increment the nRef value on all name contexts from TopNC up to
69798     ** the point where the name matched. */
69799     for(;;){
69800       assert( pTopNC!=0 );
69801       pTopNC->nRef++;
69802       if( pTopNC==pNC ) break;
69803       pTopNC = pTopNC->pNext;
69804     }
69805     return WRC_Prune;
69806   } else {
69807     return WRC_Abort;
69808   }
69809 }
69810
69811 /*
69812 ** Allocate and return a pointer to an expression to load the column iCol
69813 ** from datasource iSrc in SrcList pSrc.
69814 */
69815 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
69816   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
69817   if( p ){
69818     struct SrcList_item *pItem = &pSrc->a[iSrc];
69819     p->pTab = pItem->pTab;
69820     p->iTable = pItem->iCursor;
69821     if( p->pTab->iPKey==iCol ){
69822       p->iColumn = -1;
69823     }else{
69824       p->iColumn = (ynVar)iCol;
69825       testcase( iCol==BMS );
69826       testcase( iCol==BMS-1 );
69827       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
69828     }
69829     ExprSetProperty(p, EP_Resolved);
69830   }
69831   return p;
69832 }
69833
69834 /*
69835 ** This routine is callback for sqlite3WalkExpr().
69836 **
69837 ** Resolve symbolic names into TK_COLUMN operators for the current
69838 ** node in the expression tree.  Return 0 to continue the search down
69839 ** the tree or 2 to abort the tree walk.
69840 **
69841 ** This routine also does error checking and name resolution for
69842 ** function names.  The operator for aggregate functions is changed
69843 ** to TK_AGG_FUNCTION.
69844 */
69845 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
69846   NameContext *pNC;
69847   Parse *pParse;
69848
69849   pNC = pWalker->u.pNC;
69850   assert( pNC!=0 );
69851   pParse = pNC->pParse;
69852   assert( pParse==pWalker->pParse );
69853
69854   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
69855   ExprSetProperty(pExpr, EP_Resolved);
69856 #ifndef NDEBUG
69857   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
69858     SrcList *pSrcList = pNC->pSrcList;
69859     int i;
69860     for(i=0; i<pNC->pSrcList->nSrc; i++){
69861       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
69862     }
69863   }
69864 #endif
69865   switch( pExpr->op ){
69866
69867 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
69868     /* The special operator TK_ROW means use the rowid for the first
69869     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
69870     ** clause processing on UPDATE and DELETE statements.
69871     */
69872     case TK_ROW: {
69873       SrcList *pSrcList = pNC->pSrcList;
69874       struct SrcList_item *pItem;
69875       assert( pSrcList && pSrcList->nSrc==1 );
69876       pItem = pSrcList->a; 
69877       pExpr->op = TK_COLUMN;
69878       pExpr->pTab = pItem->pTab;
69879       pExpr->iTable = pItem->iCursor;
69880       pExpr->iColumn = -1;
69881       pExpr->affinity = SQLITE_AFF_INTEGER;
69882       break;
69883     }
69884 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
69885
69886     /* A lone identifier is the name of a column.
69887     */
69888     case TK_ID: {
69889       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
69890     }
69891   
69892     /* A table name and column name:     ID.ID
69893     ** Or a database, table and column:  ID.ID.ID
69894     */
69895     case TK_DOT: {
69896       const char *zColumn;
69897       const char *zTable;
69898       const char *zDb;
69899       Expr *pRight;
69900
69901       /* if( pSrcList==0 ) break; */
69902       pRight = pExpr->pRight;
69903       if( pRight->op==TK_ID ){
69904         zDb = 0;
69905         zTable = pExpr->pLeft->u.zToken;
69906         zColumn = pRight->u.zToken;
69907       }else{
69908         assert( pRight->op==TK_DOT );
69909         zDb = pExpr->pLeft->u.zToken;
69910         zTable = pRight->pLeft->u.zToken;
69911         zColumn = pRight->pRight->u.zToken;
69912       }
69913       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
69914     }
69915
69916     /* Resolve function names
69917     */
69918     case TK_CONST_FUNC:
69919     case TK_FUNCTION: {
69920       ExprList *pList = pExpr->x.pList;    /* The argument list */
69921       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
69922       int no_such_func = 0;       /* True if no such function exists */
69923       int wrong_num_args = 0;     /* True if wrong number of arguments */
69924       int is_agg = 0;             /* True if is an aggregate function */
69925       int auth;                   /* Authorization to use the function */
69926       int nId;                    /* Number of characters in function name */
69927       const char *zId;            /* The function name. */
69928       FuncDef *pDef;              /* Information about the function */
69929       u8 enc = ENC(pParse->db);   /* The database encoding */
69930
69931       testcase( pExpr->op==TK_CONST_FUNC );
69932       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69933       zId = pExpr->u.zToken;
69934       nId = sqlite3Strlen30(zId);
69935       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
69936       if( pDef==0 ){
69937         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
69938         if( pDef==0 ){
69939           no_such_func = 1;
69940         }else{
69941           wrong_num_args = 1;
69942         }
69943       }else{
69944         is_agg = pDef->xFunc==0;
69945       }
69946 #ifndef SQLITE_OMIT_AUTHORIZATION
69947       if( pDef ){
69948         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
69949         if( auth!=SQLITE_OK ){
69950           if( auth==SQLITE_DENY ){
69951             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
69952                                     pDef->zName);
69953             pNC->nErr++;
69954           }
69955           pExpr->op = TK_NULL;
69956           return WRC_Prune;
69957         }
69958       }
69959 #endif
69960       if( is_agg && !pNC->allowAgg ){
69961         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
69962         pNC->nErr++;
69963         is_agg = 0;
69964       }else if( no_such_func ){
69965         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
69966         pNC->nErr++;
69967       }else if( wrong_num_args ){
69968         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
69969              nId, zId);
69970         pNC->nErr++;
69971       }
69972       if( is_agg ){
69973         pExpr->op = TK_AGG_FUNCTION;
69974         pNC->hasAgg = 1;
69975       }
69976       if( is_agg ) pNC->allowAgg = 0;
69977       sqlite3WalkExprList(pWalker, pList);
69978       if( is_agg ) pNC->allowAgg = 1;
69979       /* FIX ME:  Compute pExpr->affinity based on the expected return
69980       ** type of the function 
69981       */
69982       return WRC_Prune;
69983     }
69984 #ifndef SQLITE_OMIT_SUBQUERY
69985     case TK_SELECT:
69986     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
69987 #endif
69988     case TK_IN: {
69989       testcase( pExpr->op==TK_IN );
69990       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69991         int nRef = pNC->nRef;
69992 #ifndef SQLITE_OMIT_CHECK
69993         if( pNC->isCheck ){
69994           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
69995         }
69996 #endif
69997         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
69998         assert( pNC->nRef>=nRef );
69999         if( nRef!=pNC->nRef ){
70000           ExprSetProperty(pExpr, EP_VarSelect);
70001         }
70002       }
70003       break;
70004     }
70005 #ifndef SQLITE_OMIT_CHECK
70006     case TK_VARIABLE: {
70007       if( pNC->isCheck ){
70008         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
70009       }
70010       break;
70011     }
70012 #endif
70013   }
70014   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70015 }
70016
70017 /*
70018 ** pEList is a list of expressions which are really the result set of the
70019 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
70020 ** This routine checks to see if pE is a simple identifier which corresponds
70021 ** to the AS-name of one of the terms of the expression list.  If it is,
70022 ** this routine return an integer between 1 and N where N is the number of
70023 ** elements in pEList, corresponding to the matching entry.  If there is
70024 ** no match, or if pE is not a simple identifier, then this routine
70025 ** return 0.
70026 **
70027 ** pEList has been resolved.  pE has not.
70028 */
70029 static int resolveAsName(
70030   Parse *pParse,     /* Parsing context for error messages */
70031   ExprList *pEList,  /* List of expressions to scan */
70032   Expr *pE           /* Expression we are trying to match */
70033 ){
70034   int i;             /* Loop counter */
70035
70036   UNUSED_PARAMETER(pParse);
70037
70038   if( pE->op==TK_ID ){
70039     char *zCol = pE->u.zToken;
70040     for(i=0; i<pEList->nExpr; i++){
70041       char *zAs = pEList->a[i].zName;
70042       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70043         return i+1;
70044       }
70045     }
70046   }
70047   return 0;
70048 }
70049
70050 /*
70051 ** pE is a pointer to an expression which is a single term in the
70052 ** ORDER BY of a compound SELECT.  The expression has not been
70053 ** name resolved.
70054 **
70055 ** At the point this routine is called, we already know that the
70056 ** ORDER BY term is not an integer index into the result set.  That
70057 ** case is handled by the calling routine.
70058 **
70059 ** Attempt to match pE against result set columns in the left-most
70060 ** SELECT statement.  Return the index i of the matching column,
70061 ** as an indication to the caller that it should sort by the i-th column.
70062 ** The left-most column is 1.  In other words, the value returned is the
70063 ** same integer value that would be used in the SQL statement to indicate
70064 ** the column.
70065 **
70066 ** If there is no match, return 0.  Return -1 if an error occurs.
70067 */
70068 static int resolveOrderByTermToExprList(
70069   Parse *pParse,     /* Parsing context for error messages */
70070   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
70071   Expr *pE           /* The specific ORDER BY term */
70072 ){
70073   int i;             /* Loop counter */
70074   ExprList *pEList;  /* The columns of the result set */
70075   NameContext nc;    /* Name context for resolving pE */
70076   sqlite3 *db;       /* Database connection */
70077   int rc;            /* Return code from subprocedures */
70078   u8 savedSuppErr;   /* Saved value of db->suppressErr */
70079
70080   assert( sqlite3ExprIsInteger(pE, &i)==0 );
70081   pEList = pSelect->pEList;
70082
70083   /* Resolve all names in the ORDER BY term expression
70084   */
70085   memset(&nc, 0, sizeof(nc));
70086   nc.pParse = pParse;
70087   nc.pSrcList = pSelect->pSrc;
70088   nc.pEList = pEList;
70089   nc.allowAgg = 1;
70090   nc.nErr = 0;
70091   db = pParse->db;
70092   savedSuppErr = db->suppressErr;
70093   db->suppressErr = 1;
70094   rc = sqlite3ResolveExprNames(&nc, pE);
70095   db->suppressErr = savedSuppErr;
70096   if( rc ) return 0;
70097
70098   /* Try to match the ORDER BY expression against an expression
70099   ** in the result set.  Return an 1-based index of the matching
70100   ** result-set entry.
70101   */
70102   for(i=0; i<pEList->nExpr; i++){
70103     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70104       return i+1;
70105     }
70106   }
70107
70108   /* If no match, return 0. */
70109   return 0;
70110 }
70111
70112 /*
70113 ** Generate an ORDER BY or GROUP BY term out-of-range error.
70114 */
70115 static void resolveOutOfRangeError(
70116   Parse *pParse,         /* The error context into which to write the error */
70117   const char *zType,     /* "ORDER" or "GROUP" */
70118   int i,                 /* The index (1-based) of the term out of range */
70119   int mx                 /* Largest permissible value of i */
70120 ){
70121   sqlite3ErrorMsg(pParse, 
70122     "%r %s BY term out of range - should be "
70123     "between 1 and %d", i, zType, mx);
70124 }
70125
70126 /*
70127 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
70128 ** each term of the ORDER BY clause is a constant integer between 1
70129 ** and N where N is the number of columns in the compound SELECT.
70130 **
70131 ** ORDER BY terms that are already an integer between 1 and N are
70132 ** unmodified.  ORDER BY terms that are integers outside the range of
70133 ** 1 through N generate an error.  ORDER BY terms that are expressions
70134 ** are matched against result set expressions of compound SELECT
70135 ** beginning with the left-most SELECT and working toward the right.
70136 ** At the first match, the ORDER BY expression is transformed into
70137 ** the integer column number.
70138 **
70139 ** Return the number of errors seen.
70140 */
70141 static int resolveCompoundOrderBy(
70142   Parse *pParse,        /* Parsing context.  Leave error messages here */
70143   Select *pSelect       /* The SELECT statement containing the ORDER BY */
70144 ){
70145   int i;
70146   ExprList *pOrderBy;
70147   ExprList *pEList;
70148   sqlite3 *db;
70149   int moreToDo = 1;
70150
70151   pOrderBy = pSelect->pOrderBy;
70152   if( pOrderBy==0 ) return 0;
70153   db = pParse->db;
70154 #if SQLITE_MAX_COLUMN
70155   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70156     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70157     return 1;
70158   }
70159 #endif
70160   for(i=0; i<pOrderBy->nExpr; i++){
70161     pOrderBy->a[i].done = 0;
70162   }
70163   pSelect->pNext = 0;
70164   while( pSelect->pPrior ){
70165     pSelect->pPrior->pNext = pSelect;
70166     pSelect = pSelect->pPrior;
70167   }
70168   while( pSelect && moreToDo ){
70169     struct ExprList_item *pItem;
70170     moreToDo = 0;
70171     pEList = pSelect->pEList;
70172     assert( pEList!=0 );
70173     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70174       int iCol = -1;
70175       Expr *pE, *pDup;
70176       if( pItem->done ) continue;
70177       pE = pItem->pExpr;
70178       if( sqlite3ExprIsInteger(pE, &iCol) ){
70179         if( iCol<=0 || iCol>pEList->nExpr ){
70180           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70181           return 1;
70182         }
70183       }else{
70184         iCol = resolveAsName(pParse, pEList, pE);
70185         if( iCol==0 ){
70186           pDup = sqlite3ExprDup(db, pE, 0);
70187           if( !db->mallocFailed ){
70188             assert(pDup);
70189             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70190           }
70191           sqlite3ExprDelete(db, pDup);
70192         }
70193       }
70194       if( iCol>0 ){
70195         CollSeq *pColl = pE->pColl;
70196         int flags = pE->flags & EP_ExpCollate;
70197         sqlite3ExprDelete(db, pE);
70198         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70199         if( pE==0 ) return 1;
70200         pE->pColl = pColl;
70201         pE->flags |= EP_IntValue | flags;
70202         pE->u.iValue = iCol;
70203         pItem->iCol = (u16)iCol;
70204         pItem->done = 1;
70205       }else{
70206         moreToDo = 1;
70207       }
70208     }
70209     pSelect = pSelect->pNext;
70210   }
70211   for(i=0; i<pOrderBy->nExpr; i++){
70212     if( pOrderBy->a[i].done==0 ){
70213       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70214             "column in the result set", i+1);
70215       return 1;
70216     }
70217   }
70218   return 0;
70219 }
70220
70221 /*
70222 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70223 ** the SELECT statement pSelect.  If any term is reference to a
70224 ** result set expression (as determined by the ExprList.a.iCol field)
70225 ** then convert that term into a copy of the corresponding result set
70226 ** column.
70227 **
70228 ** If any errors are detected, add an error message to pParse and
70229 ** return non-zero.  Return zero if no errors are seen.
70230 */
70231 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70232   Parse *pParse,        /* Parsing context.  Leave error messages here */
70233   Select *pSelect,      /* The SELECT statement containing the clause */
70234   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
70235   const char *zType     /* "ORDER" or "GROUP" */
70236 ){
70237   int i;
70238   sqlite3 *db = pParse->db;
70239   ExprList *pEList;
70240   struct ExprList_item *pItem;
70241
70242   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70243 #if SQLITE_MAX_COLUMN
70244   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70245     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70246     return 1;
70247   }
70248 #endif
70249   pEList = pSelect->pEList;
70250   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
70251   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70252     if( pItem->iCol ){
70253       if( pItem->iCol>pEList->nExpr ){
70254         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70255         return 1;
70256       }
70257       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70258     }
70259   }
70260   return 0;
70261 }
70262
70263 /*
70264 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70265 ** The Name context of the SELECT statement is pNC.  zType is either
70266 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70267 **
70268 ** This routine resolves each term of the clause into an expression.
70269 ** If the order-by term is an integer I between 1 and N (where N is the
70270 ** number of columns in the result set of the SELECT) then the expression
70271 ** in the resolution is a copy of the I-th result-set expression.  If
70272 ** the order-by term is an identify that corresponds to the AS-name of
70273 ** a result-set expression, then the term resolves to a copy of the
70274 ** result-set expression.  Otherwise, the expression is resolved in
70275 ** the usual way - using sqlite3ResolveExprNames().
70276 **
70277 ** This routine returns the number of errors.  If errors occur, then
70278 ** an appropriate error message might be left in pParse.  (OOM errors
70279 ** excepted.)
70280 */
70281 static int resolveOrderGroupBy(
70282   NameContext *pNC,     /* The name context of the SELECT statement */
70283   Select *pSelect,      /* The SELECT statement holding pOrderBy */
70284   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
70285   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
70286 ){
70287   int i;                         /* Loop counter */
70288   int iCol;                      /* Column number */
70289   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
70290   Parse *pParse;                 /* Parsing context */
70291   int nResult;                   /* Number of terms in the result set */
70292
70293   if( pOrderBy==0 ) return 0;
70294   nResult = pSelect->pEList->nExpr;
70295   pParse = pNC->pParse;
70296   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70297     Expr *pE = pItem->pExpr;
70298     iCol = resolveAsName(pParse, pSelect->pEList, pE);
70299     if( iCol>0 ){
70300       /* If an AS-name match is found, mark this ORDER BY column as being
70301       ** a copy of the iCol-th result-set column.  The subsequent call to
70302       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70303       ** copy of the iCol-th result-set expression. */
70304       pItem->iCol = (u16)iCol;
70305       continue;
70306     }
70307     if( sqlite3ExprIsInteger(pE, &iCol) ){
70308       /* The ORDER BY term is an integer constant.  Again, set the column
70309       ** number so that sqlite3ResolveOrderGroupBy() will convert the
70310       ** order-by term to a copy of the result-set expression */
70311       if( iCol<1 ){
70312         resolveOutOfRangeError(pParse, zType, i+1, nResult);
70313         return 1;
70314       }
70315       pItem->iCol = (u16)iCol;
70316       continue;
70317     }
70318
70319     /* Otherwise, treat the ORDER BY term as an ordinary expression */
70320     pItem->iCol = 0;
70321     if( sqlite3ResolveExprNames(pNC, pE) ){
70322       return 1;
70323     }
70324   }
70325   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70326 }
70327
70328 /*
70329 ** Resolve names in the SELECT statement p and all of its descendents.
70330 */
70331 static int resolveSelectStep(Walker *pWalker, Select *p){
70332   NameContext *pOuterNC;  /* Context that contains this SELECT */
70333   NameContext sNC;        /* Name context of this SELECT */
70334   int isCompound;         /* True if p is a compound select */
70335   int nCompound;          /* Number of compound terms processed so far */
70336   Parse *pParse;          /* Parsing context */
70337   ExprList *pEList;       /* Result set expression list */
70338   int i;                  /* Loop counter */
70339   ExprList *pGroupBy;     /* The GROUP BY clause */
70340   Select *pLeftmost;      /* Left-most of SELECT of a compound */
70341   sqlite3 *db;            /* Database connection */
70342   
70343
70344   assert( p!=0 );
70345   if( p->selFlags & SF_Resolved ){
70346     return WRC_Prune;
70347   }
70348   pOuterNC = pWalker->u.pNC;
70349   pParse = pWalker->pParse;
70350   db = pParse->db;
70351
70352   /* Normally sqlite3SelectExpand() will be called first and will have
70353   ** already expanded this SELECT.  However, if this is a subquery within
70354   ** an expression, sqlite3ResolveExprNames() will be called without a
70355   ** prior call to sqlite3SelectExpand().  When that happens, let
70356   ** sqlite3SelectPrep() do all of the processing for this SELECT.
70357   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70358   ** this routine in the correct order.
70359   */
70360   if( (p->selFlags & SF_Expanded)==0 ){
70361     sqlite3SelectPrep(pParse, p, pOuterNC);
70362     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70363   }
70364
70365   isCompound = p->pPrior!=0;
70366   nCompound = 0;
70367   pLeftmost = p;
70368   while( p ){
70369     assert( (p->selFlags & SF_Expanded)!=0 );
70370     assert( (p->selFlags & SF_Resolved)==0 );
70371     p->selFlags |= SF_Resolved;
70372
70373     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70374     ** are not allowed to refer to any names, so pass an empty NameContext.
70375     */
70376     memset(&sNC, 0, sizeof(sNC));
70377     sNC.pParse = pParse;
70378     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70379         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70380       return WRC_Abort;
70381     }
70382   
70383     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70384     ** resolve the result-set expression list.
70385     */
70386     sNC.allowAgg = 1;
70387     sNC.pSrcList = p->pSrc;
70388     sNC.pNext = pOuterNC;
70389   
70390     /* Resolve names in the result set. */
70391     pEList = p->pEList;
70392     assert( pEList!=0 );
70393     for(i=0; i<pEList->nExpr; i++){
70394       Expr *pX = pEList->a[i].pExpr;
70395       if( sqlite3ResolveExprNames(&sNC, pX) ){
70396         return WRC_Abort;
70397       }
70398     }
70399   
70400     /* Recursively resolve names in all subqueries
70401     */
70402     for(i=0; i<p->pSrc->nSrc; i++){
70403       struct SrcList_item *pItem = &p->pSrc->a[i];
70404       if( pItem->pSelect ){
70405         const char *zSavedContext = pParse->zAuthContext;
70406         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
70407         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
70408         pParse->zAuthContext = zSavedContext;
70409         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
70410       }
70411     }
70412   
70413     /* If there are no aggregate functions in the result-set, and no GROUP BY 
70414     ** expression, do not allow aggregates in any of the other expressions.
70415     */
70416     assert( (p->selFlags & SF_Aggregate)==0 );
70417     pGroupBy = p->pGroupBy;
70418     if( pGroupBy || sNC.hasAgg ){
70419       p->selFlags |= SF_Aggregate;
70420     }else{
70421       sNC.allowAgg = 0;
70422     }
70423   
70424     /* If a HAVING clause is present, then there must be a GROUP BY clause.
70425     */
70426     if( p->pHaving && !pGroupBy ){
70427       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70428       return WRC_Abort;
70429     }
70430   
70431     /* Add the expression list to the name-context before parsing the
70432     ** other expressions in the SELECT statement. This is so that
70433     ** expressions in the WHERE clause (etc.) can refer to expressions by
70434     ** aliases in the result set.
70435     **
70436     ** Minor point: If this is the case, then the expression will be
70437     ** re-evaluated for each reference to it.
70438     */
70439     sNC.pEList = p->pEList;
70440     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
70441        sqlite3ResolveExprNames(&sNC, p->pHaving)
70442     ){
70443       return WRC_Abort;
70444     }
70445
70446     /* The ORDER BY and GROUP BY clauses may not refer to terms in
70447     ** outer queries 
70448     */
70449     sNC.pNext = 0;
70450     sNC.allowAgg = 1;
70451
70452     /* Process the ORDER BY clause for singleton SELECT statements.
70453     ** The ORDER BY clause for compounds SELECT statements is handled
70454     ** below, after all of the result-sets for all of the elements of
70455     ** the compound have been resolved.
70456     */
70457     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
70458       return WRC_Abort;
70459     }
70460     if( db->mallocFailed ){
70461       return WRC_Abort;
70462     }
70463   
70464     /* Resolve the GROUP BY clause.  At the same time, make sure 
70465     ** the GROUP BY clause does not contain aggregate functions.
70466     */
70467     if( pGroupBy ){
70468       struct ExprList_item *pItem;
70469     
70470       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
70471         return WRC_Abort;
70472       }
70473       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70474         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70475           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70476               "the GROUP BY clause");
70477           return WRC_Abort;
70478         }
70479       }
70480     }
70481
70482     /* Advance to the next term of the compound
70483     */
70484     p = p->pPrior;
70485     nCompound++;
70486   }
70487
70488   /* Resolve the ORDER BY on a compound SELECT after all terms of
70489   ** the compound have been resolved.
70490   */
70491   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
70492     return WRC_Abort;
70493   }
70494
70495   return WRC_Prune;
70496 }
70497
70498 /*
70499 ** This routine walks an expression tree and resolves references to
70500 ** table columns and result-set columns.  At the same time, do error
70501 ** checking on function usage and set a flag if any aggregate functions
70502 ** are seen.
70503 **
70504 ** To resolve table columns references we look for nodes (or subtrees) of the 
70505 ** form X.Y.Z or Y.Z or just Z where
70506 **
70507 **      X:   The name of a database.  Ex:  "main" or "temp" or
70508 **           the symbolic name assigned to an ATTACH-ed database.
70509 **
70510 **      Y:   The name of a table in a FROM clause.  Or in a trigger
70511 **           one of the special names "old" or "new".
70512 **
70513 **      Z:   The name of a column in table Y.
70514 **
70515 ** The node at the root of the subtree is modified as follows:
70516 **
70517 **    Expr.op        Changed to TK_COLUMN
70518 **    Expr.pTab      Points to the Table object for X.Y
70519 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
70520 **    Expr.iTable    The VDBE cursor number for X.Y
70521 **
70522 **
70523 ** To resolve result-set references, look for expression nodes of the
70524 ** form Z (with no X and Y prefix) where the Z matches the right-hand
70525 ** size of an AS clause in the result-set of a SELECT.  The Z expression
70526 ** is replaced by a copy of the left-hand side of the result-set expression.
70527 ** Table-name and function resolution occurs on the substituted expression
70528 ** tree.  For example, in:
70529 **
70530 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
70531 **
70532 ** The "x" term of the order by is replaced by "a+b" to render:
70533 **
70534 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
70535 **
70536 ** Function calls are checked to make sure that the function is 
70537 ** defined and that the correct number of arguments are specified.
70538 ** If the function is an aggregate function, then the pNC->hasAgg is
70539 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
70540 ** If an expression contains aggregate functions then the EP_Agg
70541 ** property on the expression is set.
70542 **
70543 ** An error message is left in pParse if anything is amiss.  The number
70544 ** if errors is returned.
70545 */
70546 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
70547   NameContext *pNC,       /* Namespace to resolve expressions in. */
70548   Expr *pExpr             /* The expression to be analyzed. */
70549 ){
70550   int savedHasAgg;
70551   Walker w;
70552
70553   if( pExpr==0 ) return 0;
70554 #if SQLITE_MAX_EXPR_DEPTH>0
70555   {
70556     Parse *pParse = pNC->pParse;
70557     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
70558       return 1;
70559     }
70560     pParse->nHeight += pExpr->nHeight;
70561   }
70562 #endif
70563   savedHasAgg = pNC->hasAgg;
70564   pNC->hasAgg = 0;
70565   w.xExprCallback = resolveExprStep;
70566   w.xSelectCallback = resolveSelectStep;
70567   w.pParse = pNC->pParse;
70568   w.u.pNC = pNC;
70569   sqlite3WalkExpr(&w, pExpr);
70570 #if SQLITE_MAX_EXPR_DEPTH>0
70571   pNC->pParse->nHeight -= pExpr->nHeight;
70572 #endif
70573   if( pNC->nErr>0 || w.pParse->nErr>0 ){
70574     ExprSetProperty(pExpr, EP_Error);
70575   }
70576   if( pNC->hasAgg ){
70577     ExprSetProperty(pExpr, EP_Agg);
70578   }else if( savedHasAgg ){
70579     pNC->hasAgg = 1;
70580   }
70581   return ExprHasProperty(pExpr, EP_Error);
70582 }
70583
70584
70585 /*
70586 ** Resolve all names in all expressions of a SELECT and in all
70587 ** decendents of the SELECT, including compounds off of p->pPrior,
70588 ** subqueries in expressions, and subqueries used as FROM clause
70589 ** terms.
70590 **
70591 ** See sqlite3ResolveExprNames() for a description of the kinds of
70592 ** transformations that occur.
70593 **
70594 ** All SELECT statements should have been expanded using
70595 ** sqlite3SelectExpand() prior to invoking this routine.
70596 */
70597 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
70598   Parse *pParse,         /* The parser context */
70599   Select *p,             /* The SELECT statement being coded. */
70600   NameContext *pOuterNC  /* Name context for parent SELECT statement */
70601 ){
70602   Walker w;
70603
70604   assert( p!=0 );
70605   w.xExprCallback = resolveExprStep;
70606   w.xSelectCallback = resolveSelectStep;
70607   w.pParse = pParse;
70608   w.u.pNC = pOuterNC;
70609   sqlite3WalkSelect(&w, p);
70610 }
70611
70612 /************** End of resolve.c *********************************************/
70613 /************** Begin file expr.c ********************************************/
70614 /*
70615 ** 2001 September 15
70616 **
70617 ** The author disclaims copyright to this source code.  In place of
70618 ** a legal notice, here is a blessing:
70619 **
70620 **    May you do good and not evil.
70621 **    May you find forgiveness for yourself and forgive others.
70622 **    May you share freely, never taking more than you give.
70623 **
70624 *************************************************************************
70625 ** This file contains routines used for analyzing expressions and
70626 ** for generating VDBE code that evaluates expressions in SQLite.
70627 */
70628
70629 /*
70630 ** Return the 'affinity' of the expression pExpr if any.
70631 **
70632 ** If pExpr is a column, a reference to a column via an 'AS' alias,
70633 ** or a sub-select with a column as the return value, then the 
70634 ** affinity of that column is returned. Otherwise, 0x00 is returned,
70635 ** indicating no affinity for the expression.
70636 **
70637 ** i.e. the WHERE clause expresssions in the following statements all
70638 ** have an affinity:
70639 **
70640 ** CREATE TABLE t1(a);
70641 ** SELECT * FROM t1 WHERE a;
70642 ** SELECT a AS b FROM t1 WHERE b;
70643 ** SELECT * FROM t1 WHERE (select a from t1);
70644 */
70645 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
70646   int op = pExpr->op;
70647   if( op==TK_SELECT ){
70648     assert( pExpr->flags&EP_xIsSelect );
70649     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
70650   }
70651 #ifndef SQLITE_OMIT_CAST
70652   if( op==TK_CAST ){
70653     assert( !ExprHasProperty(pExpr, EP_IntValue) );
70654     return sqlite3AffinityType(pExpr->u.zToken);
70655   }
70656 #endif
70657   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
70658    && pExpr->pTab!=0
70659   ){
70660     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
70661     ** a TK_COLUMN but was previously evaluated and cached in a register */
70662     int j = pExpr->iColumn;
70663     if( j<0 ) return SQLITE_AFF_INTEGER;
70664     assert( pExpr->pTab && j<pExpr->pTab->nCol );
70665     return pExpr->pTab->aCol[j].affinity;
70666   }
70667   return pExpr->affinity;
70668 }
70669
70670 /*
70671 ** Set the explicit collating sequence for an expression to the
70672 ** collating sequence supplied in the second argument.
70673 */
70674 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
70675   if( pExpr && pColl ){
70676     pExpr->pColl = pColl;
70677     pExpr->flags |= EP_ExpCollate;
70678   }
70679   return pExpr;
70680 }
70681
70682 /*
70683 ** Set the collating sequence for expression pExpr to be the collating
70684 ** sequence named by pToken.   Return a pointer to the revised expression.
70685 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
70686 ** flag.  An explicit collating sequence will override implicit
70687 ** collating sequences.
70688 */
70689 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
70690   char *zColl = 0;            /* Dequoted name of collation sequence */
70691   CollSeq *pColl;
70692   sqlite3 *db = pParse->db;
70693   zColl = sqlite3NameFromToken(db, pCollName);
70694   pColl = sqlite3LocateCollSeq(pParse, zColl);
70695   sqlite3ExprSetColl(pExpr, pColl);
70696   sqlite3DbFree(db, zColl);
70697   return pExpr;
70698 }
70699
70700 /*
70701 ** Return the default collation sequence for the expression pExpr. If
70702 ** there is no default collation type, return 0.
70703 */
70704 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
70705   CollSeq *pColl = 0;
70706   Expr *p = pExpr;
70707   while( p ){
70708     int op;
70709     pColl = p->pColl;
70710     if( pColl ) break;
70711     op = p->op;
70712     if( p->pTab!=0 && (
70713         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
70714     )){
70715       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
70716       ** a TK_COLUMN but was previously evaluated and cached in a register */
70717       const char *zColl;
70718       int j = p->iColumn;
70719       if( j>=0 ){
70720         sqlite3 *db = pParse->db;
70721         zColl = p->pTab->aCol[j].zColl;
70722         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70723         pExpr->pColl = pColl;
70724       }
70725       break;
70726     }
70727     if( op!=TK_CAST && op!=TK_UPLUS ){
70728       break;
70729     }
70730     p = p->pLeft;
70731   }
70732   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
70733     pColl = 0;
70734   }
70735   return pColl;
70736 }
70737
70738 /*
70739 ** pExpr is an operand of a comparison operator.  aff2 is the
70740 ** type affinity of the other operand.  This routine returns the
70741 ** type affinity that should be used for the comparison operator.
70742 */
70743 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
70744   char aff1 = sqlite3ExprAffinity(pExpr);
70745   if( aff1 && aff2 ){
70746     /* Both sides of the comparison are columns. If one has numeric
70747     ** affinity, use that. Otherwise use no affinity.
70748     */
70749     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
70750       return SQLITE_AFF_NUMERIC;
70751     }else{
70752       return SQLITE_AFF_NONE;
70753     }
70754   }else if( !aff1 && !aff2 ){
70755     /* Neither side of the comparison is a column.  Compare the
70756     ** results directly.
70757     */
70758     return SQLITE_AFF_NONE;
70759   }else{
70760     /* One side is a column, the other is not. Use the columns affinity. */
70761     assert( aff1==0 || aff2==0 );
70762     return (aff1 + aff2);
70763   }
70764 }
70765
70766 /*
70767 ** pExpr is a comparison operator.  Return the type affinity that should
70768 ** be applied to both operands prior to doing the comparison.
70769 */
70770 static char comparisonAffinity(Expr *pExpr){
70771   char aff;
70772   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
70773           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
70774           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
70775   assert( pExpr->pLeft );
70776   aff = sqlite3ExprAffinity(pExpr->pLeft);
70777   if( pExpr->pRight ){
70778     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
70779   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70780     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
70781   }else if( !aff ){
70782     aff = SQLITE_AFF_NONE;
70783   }
70784   return aff;
70785 }
70786
70787 /*
70788 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
70789 ** idx_affinity is the affinity of an indexed column. Return true
70790 ** if the index with affinity idx_affinity may be used to implement
70791 ** the comparison in pExpr.
70792 */
70793 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
70794   char aff = comparisonAffinity(pExpr);
70795   switch( aff ){
70796     case SQLITE_AFF_NONE:
70797       return 1;
70798     case SQLITE_AFF_TEXT:
70799       return idx_affinity==SQLITE_AFF_TEXT;
70800     default:
70801       return sqlite3IsNumericAffinity(idx_affinity);
70802   }
70803 }
70804
70805 /*
70806 ** Return the P5 value that should be used for a binary comparison
70807 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
70808 */
70809 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
70810   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
70811   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
70812   return aff;
70813 }
70814
70815 /*
70816 ** Return a pointer to the collation sequence that should be used by
70817 ** a binary comparison operator comparing pLeft and pRight.
70818 **
70819 ** If the left hand expression has a collating sequence type, then it is
70820 ** used. Otherwise the collation sequence for the right hand expression
70821 ** is used, or the default (BINARY) if neither expression has a collating
70822 ** type.
70823 **
70824 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
70825 ** it is not considered.
70826 */
70827 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
70828   Parse *pParse, 
70829   Expr *pLeft, 
70830   Expr *pRight
70831 ){
70832   CollSeq *pColl;
70833   assert( pLeft );
70834   if( pLeft->flags & EP_ExpCollate ){
70835     assert( pLeft->pColl );
70836     pColl = pLeft->pColl;
70837   }else if( pRight && pRight->flags & EP_ExpCollate ){
70838     assert( pRight->pColl );
70839     pColl = pRight->pColl;
70840   }else{
70841     pColl = sqlite3ExprCollSeq(pParse, pLeft);
70842     if( !pColl ){
70843       pColl = sqlite3ExprCollSeq(pParse, pRight);
70844     }
70845   }
70846   return pColl;
70847 }
70848
70849 /*
70850 ** Generate code for a comparison operator.
70851 */
70852 static int codeCompare(
70853   Parse *pParse,    /* The parsing (and code generating) context */
70854   Expr *pLeft,      /* The left operand */
70855   Expr *pRight,     /* The right operand */
70856   int opcode,       /* The comparison opcode */
70857   int in1, int in2, /* Register holding operands */
70858   int dest,         /* Jump here if true.  */
70859   int jumpIfNull    /* If true, jump if either operand is NULL */
70860 ){
70861   int p5;
70862   int addr;
70863   CollSeq *p4;
70864
70865   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
70866   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
70867   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
70868                            (void*)p4, P4_COLLSEQ);
70869   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
70870   return addr;
70871 }
70872
70873 #if SQLITE_MAX_EXPR_DEPTH>0
70874 /*
70875 ** Check that argument nHeight is less than or equal to the maximum
70876 ** expression depth allowed. If it is not, leave an error message in
70877 ** pParse.
70878 */
70879 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
70880   int rc = SQLITE_OK;
70881   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
70882   if( nHeight>mxHeight ){
70883     sqlite3ErrorMsg(pParse, 
70884        "Expression tree is too large (maximum depth %d)", mxHeight
70885     );
70886     rc = SQLITE_ERROR;
70887   }
70888   return rc;
70889 }
70890
70891 /* The following three functions, heightOfExpr(), heightOfExprList()
70892 ** and heightOfSelect(), are used to determine the maximum height
70893 ** of any expression tree referenced by the structure passed as the
70894 ** first argument.
70895 **
70896 ** If this maximum height is greater than the current value pointed
70897 ** to by pnHeight, the second parameter, then set *pnHeight to that
70898 ** value.
70899 */
70900 static void heightOfExpr(Expr *p, int *pnHeight){
70901   if( p ){
70902     if( p->nHeight>*pnHeight ){
70903       *pnHeight = p->nHeight;
70904     }
70905   }
70906 }
70907 static void heightOfExprList(ExprList *p, int *pnHeight){
70908   if( p ){
70909     int i;
70910     for(i=0; i<p->nExpr; i++){
70911       heightOfExpr(p->a[i].pExpr, pnHeight);
70912     }
70913   }
70914 }
70915 static void heightOfSelect(Select *p, int *pnHeight){
70916   if( p ){
70917     heightOfExpr(p->pWhere, pnHeight);
70918     heightOfExpr(p->pHaving, pnHeight);
70919     heightOfExpr(p->pLimit, pnHeight);
70920     heightOfExpr(p->pOffset, pnHeight);
70921     heightOfExprList(p->pEList, pnHeight);
70922     heightOfExprList(p->pGroupBy, pnHeight);
70923     heightOfExprList(p->pOrderBy, pnHeight);
70924     heightOfSelect(p->pPrior, pnHeight);
70925   }
70926 }
70927
70928 /*
70929 ** Set the Expr.nHeight variable in the structure passed as an 
70930 ** argument. An expression with no children, Expr.pList or 
70931 ** Expr.pSelect member has a height of 1. Any other expression
70932 ** has a height equal to the maximum height of any other 
70933 ** referenced Expr plus one.
70934 */
70935 static void exprSetHeight(Expr *p){
70936   int nHeight = 0;
70937   heightOfExpr(p->pLeft, &nHeight);
70938   heightOfExpr(p->pRight, &nHeight);
70939   if( ExprHasProperty(p, EP_xIsSelect) ){
70940     heightOfSelect(p->x.pSelect, &nHeight);
70941   }else{
70942     heightOfExprList(p->x.pList, &nHeight);
70943   }
70944   p->nHeight = nHeight + 1;
70945 }
70946
70947 /*
70948 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
70949 ** the height is greater than the maximum allowed expression depth,
70950 ** leave an error in pParse.
70951 */
70952 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
70953   exprSetHeight(p);
70954   sqlite3ExprCheckHeight(pParse, p->nHeight);
70955 }
70956
70957 /*
70958 ** Return the maximum height of any expression tree referenced
70959 ** by the select statement passed as an argument.
70960 */
70961 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
70962   int nHeight = 0;
70963   heightOfSelect(p, &nHeight);
70964   return nHeight;
70965 }
70966 #else
70967   #define exprSetHeight(y)
70968 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
70969
70970 /*
70971 ** This routine is the core allocator for Expr nodes.
70972 **
70973 ** Construct a new expression node and return a pointer to it.  Memory
70974 ** for this node and for the pToken argument is a single allocation
70975 ** obtained from sqlite3DbMalloc().  The calling function
70976 ** is responsible for making sure the node eventually gets freed.
70977 **
70978 ** If dequote is true, then the token (if it exists) is dequoted.
70979 ** If dequote is false, no dequoting is performance.  The deQuote
70980 ** parameter is ignored if pToken is NULL or if the token does not
70981 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
70982 ** then the EP_DblQuoted flag is set on the expression node.
70983 **
70984 ** Special case:  If op==TK_INTEGER and pToken points to a string that
70985 ** can be translated into a 32-bit integer, then the token is not
70986 ** stored in u.zToken.  Instead, the integer values is written
70987 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
70988 ** is allocated to hold the integer text and the dequote flag is ignored.
70989 */
70990 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
70991   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
70992   int op,                 /* Expression opcode */
70993   const Token *pToken,    /* Token argument.  Might be NULL */
70994   int dequote             /* True to dequote */
70995 ){
70996   Expr *pNew;
70997   int nExtra = 0;
70998   int iValue = 0;
70999
71000   if( pToken ){
71001     if( op!=TK_INTEGER || pToken->z==0
71002           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
71003       nExtra = pToken->n+1;
71004       assert( iValue>=0 );
71005     }
71006   }
71007   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
71008   if( pNew ){
71009     pNew->op = (u8)op;
71010     pNew->iAgg = -1;
71011     if( pToken ){
71012       if( nExtra==0 ){
71013         pNew->flags |= EP_IntValue;
71014         pNew->u.iValue = iValue;
71015       }else{
71016         int c;
71017         pNew->u.zToken = (char*)&pNew[1];
71018         memcpy(pNew->u.zToken, pToken->z, pToken->n);
71019         pNew->u.zToken[pToken->n] = 0;
71020         if( dequote && nExtra>=3 
71021              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71022           sqlite3Dequote(pNew->u.zToken);
71023           if( c=='"' ) pNew->flags |= EP_DblQuoted;
71024         }
71025       }
71026     }
71027 #if SQLITE_MAX_EXPR_DEPTH>0
71028     pNew->nHeight = 1;
71029 #endif  
71030   }
71031   return pNew;
71032 }
71033
71034 /*
71035 ** Allocate a new expression node from a zero-terminated token that has
71036 ** already been dequoted.
71037 */
71038 SQLITE_PRIVATE Expr *sqlite3Expr(
71039   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71040   int op,                 /* Expression opcode */
71041   const char *zToken      /* Token argument.  Might be NULL */
71042 ){
71043   Token x;
71044   x.z = zToken;
71045   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71046   return sqlite3ExprAlloc(db, op, &x, 0);
71047 }
71048
71049 /*
71050 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
71051 **
71052 ** If pRoot==NULL that means that a memory allocation error has occurred.
71053 ** In that case, delete the subtrees pLeft and pRight.
71054 */
71055 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71056   sqlite3 *db,
71057   Expr *pRoot,
71058   Expr *pLeft,
71059   Expr *pRight
71060 ){
71061   if( pRoot==0 ){
71062     assert( db->mallocFailed );
71063     sqlite3ExprDelete(db, pLeft);
71064     sqlite3ExprDelete(db, pRight);
71065   }else{
71066     if( pRight ){
71067       pRoot->pRight = pRight;
71068       if( pRight->flags & EP_ExpCollate ){
71069         pRoot->flags |= EP_ExpCollate;
71070         pRoot->pColl = pRight->pColl;
71071       }
71072     }
71073     if( pLeft ){
71074       pRoot->pLeft = pLeft;
71075       if( pLeft->flags & EP_ExpCollate ){
71076         pRoot->flags |= EP_ExpCollate;
71077         pRoot->pColl = pLeft->pColl;
71078       }
71079     }
71080     exprSetHeight(pRoot);
71081   }
71082 }
71083
71084 /*
71085 ** Allocate a Expr node which joins as many as two subtrees.
71086 **
71087 ** One or both of the subtrees can be NULL.  Return a pointer to the new
71088 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
71089 ** free the subtrees and return NULL.
71090 */
71091 SQLITE_PRIVATE Expr *sqlite3PExpr(
71092   Parse *pParse,          /* Parsing context */
71093   int op,                 /* Expression opcode */
71094   Expr *pLeft,            /* Left operand */
71095   Expr *pRight,           /* Right operand */
71096   const Token *pToken     /* Argument token */
71097 ){
71098   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71099   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71100   if( p ) {
71101     sqlite3ExprCheckHeight(pParse, p->nHeight);
71102   }
71103   return p;
71104 }
71105
71106 /*
71107 ** Join two expressions using an AND operator.  If either expression is
71108 ** NULL, then just return the other expression.
71109 */
71110 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71111   if( pLeft==0 ){
71112     return pRight;
71113   }else if( pRight==0 ){
71114     return pLeft;
71115   }else{
71116     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71117     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71118     return pNew;
71119   }
71120 }
71121
71122 /*
71123 ** Construct a new expression node for a function with multiple
71124 ** arguments.
71125 */
71126 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71127   Expr *pNew;
71128   sqlite3 *db = pParse->db;
71129   assert( pToken );
71130   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71131   if( pNew==0 ){
71132     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71133     return 0;
71134   }
71135   pNew->x.pList = pList;
71136   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71137   sqlite3ExprSetHeight(pParse, pNew);
71138   return pNew;
71139 }
71140
71141 /*
71142 ** Assign a variable number to an expression that encodes a wildcard
71143 ** in the original SQL statement.  
71144 **
71145 ** Wildcards consisting of a single "?" are assigned the next sequential
71146 ** variable number.
71147 **
71148 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
71149 ** sure "nnn" is not too be to avoid a denial of service attack when
71150 ** the SQL statement comes from an external source.
71151 **
71152 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71153 ** as the previous instance of the same wildcard.  Or if this is the first
71154 ** instance of the wildcard, the next sequenial variable number is
71155 ** assigned.
71156 */
71157 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71158   sqlite3 *db = pParse->db;
71159   const char *z;
71160
71161   if( pExpr==0 ) return;
71162   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71163   z = pExpr->u.zToken;
71164   assert( z!=0 );
71165   assert( z[0]!=0 );
71166   if( z[1]==0 ){
71167     /* Wildcard of the form "?".  Assign the next variable number */
71168     assert( z[0]=='?' );
71169     pExpr->iColumn = (ynVar)(++pParse->nVar);
71170   }else if( z[0]=='?' ){
71171     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
71172     ** use it as the variable number */
71173     i64 i;
71174     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
71175     pExpr->iColumn = (ynVar)i;
71176     testcase( i==0 );
71177     testcase( i==1 );
71178     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71179     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71180     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71181       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71182           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71183     }
71184     if( i>pParse->nVar ){
71185       pParse->nVar = (int)i;
71186     }
71187   }else{
71188     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
71189     ** number as the prior appearance of the same name, or if the name
71190     ** has never appeared before, reuse the same variable number
71191     */
71192     int i;
71193     u32 n;
71194     n = sqlite3Strlen30(z);
71195     for(i=0; i<pParse->nVarExpr; i++){
71196       Expr *pE = pParse->apVarExpr[i];
71197       assert( pE!=0 );
71198       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
71199         pExpr->iColumn = pE->iColumn;
71200         break;
71201       }
71202     }
71203     if( i>=pParse->nVarExpr ){
71204       pExpr->iColumn = (ynVar)(++pParse->nVar);
71205       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
71206         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
71207         pParse->apVarExpr =
71208             sqlite3DbReallocOrFree(
71209               db,
71210               pParse->apVarExpr,
71211               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
71212             );
71213       }
71214       if( !db->mallocFailed ){
71215         assert( pParse->apVarExpr!=0 );
71216         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
71217       }
71218     }
71219   } 
71220   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71221     sqlite3ErrorMsg(pParse, "too many SQL variables");
71222   }
71223 }
71224
71225 /*
71226 ** Recursively delete an expression tree.
71227 */
71228 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71229   if( p==0 ) return;
71230   /* Sanity check: Assert that the IntValue is non-negative if it exists */
71231   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71232   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71233     sqlite3ExprDelete(db, p->pLeft);
71234     sqlite3ExprDelete(db, p->pRight);
71235     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71236       sqlite3DbFree(db, p->u.zToken);
71237     }
71238     if( ExprHasProperty(p, EP_xIsSelect) ){
71239       sqlite3SelectDelete(db, p->x.pSelect);
71240     }else{
71241       sqlite3ExprListDelete(db, p->x.pList);
71242     }
71243   }
71244   if( !ExprHasProperty(p, EP_Static) ){
71245     sqlite3DbFree(db, p);
71246   }
71247 }
71248
71249 /*
71250 ** Return the number of bytes allocated for the expression structure 
71251 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
71252 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71253 */
71254 static int exprStructSize(Expr *p){
71255   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71256   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71257   return EXPR_FULLSIZE;
71258 }
71259
71260 /*
71261 ** The dupedExpr*Size() routines each return the number of bytes required
71262 ** to store a copy of an expression or expression tree.  They differ in
71263 ** how much of the tree is measured.
71264 **
71265 **     dupedExprStructSize()     Size of only the Expr structure 
71266 **     dupedExprNodeSize()       Size of Expr + space for token
71267 **     dupedExprSize()           Expr + token + subtree components
71268 **
71269 ***************************************************************************
71270 **
71271 ** The dupedExprStructSize() function returns two values OR-ed together:  
71272 ** (1) the space required for a copy of the Expr structure only and 
71273 ** (2) the EP_xxx flags that indicate what the structure size should be.
71274 ** The return values is always one of:
71275 **
71276 **      EXPR_FULLSIZE
71277 **      EXPR_REDUCEDSIZE   | EP_Reduced
71278 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
71279 **
71280 ** The size of the structure can be found by masking the return value
71281 ** of this routine with 0xfff.  The flags can be found by masking the
71282 ** return value with EP_Reduced|EP_TokenOnly.
71283 **
71284 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71285 ** (unreduced) Expr objects as they or originally constructed by the parser.
71286 ** During expression analysis, extra information is computed and moved into
71287 ** later parts of teh Expr object and that extra information might get chopped
71288 ** off if the expression is reduced.  Note also that it does not work to
71289 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
71290 ** to reduce a pristine expression tree from the parser.  The implementation
71291 ** of dupedExprStructSize() contain multiple assert() statements that attempt
71292 ** to enforce this constraint.
71293 */
71294 static int dupedExprStructSize(Expr *p, int flags){
71295   int nSize;
71296   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71297   if( 0==(flags&EXPRDUP_REDUCE) ){
71298     nSize = EXPR_FULLSIZE;
71299   }else{
71300     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71301     assert( !ExprHasProperty(p, EP_FromJoin) ); 
71302     assert( (p->flags2 & EP2_MallocedToken)==0 );
71303     assert( (p->flags2 & EP2_Irreducible)==0 );
71304     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71305       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71306     }else{
71307       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71308     }
71309   }
71310   return nSize;
71311 }
71312
71313 /*
71314 ** This function returns the space in bytes required to store the copy 
71315 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
71316 ** string is defined.)
71317 */
71318 static int dupedExprNodeSize(Expr *p, int flags){
71319   int nByte = dupedExprStructSize(p, flags) & 0xfff;
71320   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71321     nByte += sqlite3Strlen30(p->u.zToken)+1;
71322   }
71323   return ROUND8(nByte);
71324 }
71325
71326 /*
71327 ** Return the number of bytes required to create a duplicate of the 
71328 ** expression passed as the first argument. The second argument is a
71329 ** mask containing EXPRDUP_XXX flags.
71330 **
71331 ** The value returned includes space to create a copy of the Expr struct
71332 ** itself and the buffer referred to by Expr.u.zToken, if any.
71333 **
71334 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
71335 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
71336 ** and Expr.pRight variables (but not for any structures pointed to or 
71337 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
71338 */
71339 static int dupedExprSize(Expr *p, int flags){
71340   int nByte = 0;
71341   if( p ){
71342     nByte = dupedExprNodeSize(p, flags);
71343     if( flags&EXPRDUP_REDUCE ){
71344       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71345     }
71346   }
71347   return nByte;
71348 }
71349
71350 /*
71351 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
71352 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
71353 ** to store the copy of expression p, the copies of p->u.zToken
71354 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71355 ** if any. Before returning, *pzBuffer is set to the first byte passed the
71356 ** portion of the buffer copied into by this function.
71357 */
71358 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71359   Expr *pNew = 0;                      /* Value to return */
71360   if( p ){
71361     const int isReduced = (flags&EXPRDUP_REDUCE);
71362     u8 *zAlloc;
71363     u32 staticFlag = 0;
71364
71365     assert( pzBuffer==0 || isReduced );
71366
71367     /* Figure out where to write the new Expr structure. */
71368     if( pzBuffer ){
71369       zAlloc = *pzBuffer;
71370       staticFlag = EP_Static;
71371     }else{
71372       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71373     }
71374     pNew = (Expr *)zAlloc;
71375
71376     if( pNew ){
71377       /* Set nNewSize to the size allocated for the structure pointed to
71378       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71379       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71380       ** by the copy of the p->u.zToken string (if any).
71381       */
71382       const unsigned nStructSize = dupedExprStructSize(p, flags);
71383       const int nNewSize = nStructSize & 0xfff;
71384       int nToken;
71385       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71386         nToken = sqlite3Strlen30(p->u.zToken) + 1;
71387       }else{
71388         nToken = 0;
71389       }
71390       if( isReduced ){
71391         assert( ExprHasProperty(p, EP_Reduced)==0 );
71392         memcpy(zAlloc, p, nNewSize);
71393       }else{
71394         int nSize = exprStructSize(p);
71395         memcpy(zAlloc, p, nSize);
71396         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
71397       }
71398
71399       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
71400       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
71401       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
71402       pNew->flags |= staticFlag;
71403
71404       /* Copy the p->u.zToken string, if any. */
71405       if( nToken ){
71406         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
71407         memcpy(zToken, p->u.zToken, nToken);
71408       }
71409
71410       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
71411         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
71412         if( ExprHasProperty(p, EP_xIsSelect) ){
71413           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
71414         }else{
71415           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
71416         }
71417       }
71418
71419       /* Fill in pNew->pLeft and pNew->pRight. */
71420       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
71421         zAlloc += dupedExprNodeSize(p, flags);
71422         if( ExprHasProperty(pNew, EP_Reduced) ){
71423           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
71424           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
71425         }
71426         if( pzBuffer ){
71427           *pzBuffer = zAlloc;
71428         }
71429       }else{
71430         pNew->flags2 = 0;
71431         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71432           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
71433           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
71434         }
71435       }
71436
71437     }
71438   }
71439   return pNew;
71440 }
71441
71442 /*
71443 ** The following group of routines make deep copies of expressions,
71444 ** expression lists, ID lists, and select statements.  The copies can
71445 ** be deleted (by being passed to their respective ...Delete() routines)
71446 ** without effecting the originals.
71447 **
71448 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
71449 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
71450 ** by subsequent calls to sqlite*ListAppend() routines.
71451 **
71452 ** Any tables that the SrcList might point to are not duplicated.
71453 **
71454 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
71455 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
71456 ** truncated version of the usual Expr structure that will be stored as
71457 ** part of the in-memory representation of the database schema.
71458 */
71459 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
71460   return exprDup(db, p, flags, 0);
71461 }
71462 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
71463   ExprList *pNew;
71464   struct ExprList_item *pItem, *pOldItem;
71465   int i;
71466   if( p==0 ) return 0;
71467   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71468   if( pNew==0 ) return 0;
71469   pNew->iECursor = 0;
71470   pNew->nExpr = pNew->nAlloc = p->nExpr;
71471   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
71472   if( pItem==0 ){
71473     sqlite3DbFree(db, pNew);
71474     return 0;
71475   } 
71476   pOldItem = p->a;
71477   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
71478     Expr *pOldExpr = pOldItem->pExpr;
71479     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
71480     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71481     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
71482     pItem->sortOrder = pOldItem->sortOrder;
71483     pItem->done = 0;
71484     pItem->iCol = pOldItem->iCol;
71485     pItem->iAlias = pOldItem->iAlias;
71486   }
71487   return pNew;
71488 }
71489
71490 /*
71491 ** If cursors, triggers, views and subqueries are all omitted from
71492 ** the build, then none of the following routines, except for 
71493 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
71494 ** called with a NULL argument.
71495 */
71496 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
71497  || !defined(SQLITE_OMIT_SUBQUERY)
71498 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
71499   SrcList *pNew;
71500   int i;
71501   int nByte;
71502   if( p==0 ) return 0;
71503   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
71504   pNew = sqlite3DbMallocRaw(db, nByte );
71505   if( pNew==0 ) return 0;
71506   pNew->nSrc = pNew->nAlloc = p->nSrc;
71507   for(i=0; i<p->nSrc; i++){
71508     struct SrcList_item *pNewItem = &pNew->a[i];
71509     struct SrcList_item *pOldItem = &p->a[i];
71510     Table *pTab;
71511     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
71512     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71513     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
71514     pNewItem->jointype = pOldItem->jointype;
71515     pNewItem->iCursor = pOldItem->iCursor;
71516     pNewItem->isPopulated = pOldItem->isPopulated;
71517     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
71518     pNewItem->notIndexed = pOldItem->notIndexed;
71519     pNewItem->pIndex = pOldItem->pIndex;
71520     pTab = pNewItem->pTab = pOldItem->pTab;
71521     if( pTab ){
71522       pTab->nRef++;
71523     }
71524     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
71525     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
71526     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
71527     pNewItem->colUsed = pOldItem->colUsed;
71528   }
71529   return pNew;
71530 }
71531 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
71532   IdList *pNew;
71533   int i;
71534   if( p==0 ) return 0;
71535   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71536   if( pNew==0 ) return 0;
71537   pNew->nId = pNew->nAlloc = p->nId;
71538   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
71539   if( pNew->a==0 ){
71540     sqlite3DbFree(db, pNew);
71541     return 0;
71542   }
71543   for(i=0; i<p->nId; i++){
71544     struct IdList_item *pNewItem = &pNew->a[i];
71545     struct IdList_item *pOldItem = &p->a[i];
71546     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71547     pNewItem->idx = pOldItem->idx;
71548   }
71549   return pNew;
71550 }
71551 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71552   Select *pNew;
71553   if( p==0 ) return 0;
71554   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
71555   if( pNew==0 ) return 0;
71556   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
71557   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
71558   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
71559   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
71560   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
71561   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
71562   pNew->op = p->op;
71563   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
71564   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
71565   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
71566   pNew->iLimit = 0;
71567   pNew->iOffset = 0;
71568   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
71569   pNew->pRightmost = 0;
71570   pNew->addrOpenEphm[0] = -1;
71571   pNew->addrOpenEphm[1] = -1;
71572   pNew->addrOpenEphm[2] = -1;
71573   return pNew;
71574 }
71575 #else
71576 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71577   assert( p==0 );
71578   return 0;
71579 }
71580 #endif
71581
71582
71583 /*
71584 ** Add a new element to the end of an expression list.  If pList is
71585 ** initially NULL, then create a new expression list.
71586 **
71587 ** If a memory allocation error occurs, the entire list is freed and
71588 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
71589 ** that the new entry was successfully appended.
71590 */
71591 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
71592   Parse *pParse,          /* Parsing context */
71593   ExprList *pList,        /* List to which to append. Might be NULL */
71594   Expr *pExpr             /* Expression to be appended. Might be NULL */
71595 ){
71596   sqlite3 *db = pParse->db;
71597   if( pList==0 ){
71598     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
71599     if( pList==0 ){
71600       goto no_mem;
71601     }
71602     assert( pList->nAlloc==0 );
71603   }
71604   if( pList->nAlloc<=pList->nExpr ){
71605     struct ExprList_item *a;
71606     int n = pList->nAlloc*2 + 4;
71607     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
71608     if( a==0 ){
71609       goto no_mem;
71610     }
71611     pList->a = a;
71612     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
71613   }
71614   assert( pList->a!=0 );
71615   if( 1 ){
71616     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
71617     memset(pItem, 0, sizeof(*pItem));
71618     pItem->pExpr = pExpr;
71619   }
71620   return pList;
71621
71622 no_mem:     
71623   /* Avoid leaking memory if malloc has failed. */
71624   sqlite3ExprDelete(db, pExpr);
71625   sqlite3ExprListDelete(db, pList);
71626   return 0;
71627 }
71628
71629 /*
71630 ** Set the ExprList.a[].zName element of the most recently added item
71631 ** on the expression list.
71632 **
71633 ** pList might be NULL following an OOM error.  But pName should never be
71634 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71635 ** is set.
71636 */
71637 SQLITE_PRIVATE void sqlite3ExprListSetName(
71638   Parse *pParse,          /* Parsing context */
71639   ExprList *pList,        /* List to which to add the span. */
71640   Token *pName,           /* Name to be added */
71641   int dequote             /* True to cause the name to be dequoted */
71642 ){
71643   assert( pList!=0 || pParse->db->mallocFailed!=0 );
71644   if( pList ){
71645     struct ExprList_item *pItem;
71646     assert( pList->nExpr>0 );
71647     pItem = &pList->a[pList->nExpr-1];
71648     assert( pItem->zName==0 );
71649     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
71650     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
71651   }
71652 }
71653
71654 /*
71655 ** Set the ExprList.a[].zSpan element of the most recently added item
71656 ** on the expression list.
71657 **
71658 ** pList might be NULL following an OOM error.  But pSpan should never be
71659 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
71660 ** is set.
71661 */
71662 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
71663   Parse *pParse,          /* Parsing context */
71664   ExprList *pList,        /* List to which to add the span. */
71665   ExprSpan *pSpan         /* The span to be added */
71666 ){
71667   sqlite3 *db = pParse->db;
71668   assert( pList!=0 || db->mallocFailed!=0 );
71669   if( pList ){
71670     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
71671     assert( pList->nExpr>0 );
71672     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
71673     sqlite3DbFree(db, pItem->zSpan);
71674     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
71675                                     (int)(pSpan->zEnd - pSpan->zStart));
71676   }
71677 }
71678
71679 /*
71680 ** If the expression list pEList contains more than iLimit elements,
71681 ** leave an error message in pParse.
71682 */
71683 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
71684   Parse *pParse,
71685   ExprList *pEList,
71686   const char *zObject
71687 ){
71688   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
71689   testcase( pEList && pEList->nExpr==mx );
71690   testcase( pEList && pEList->nExpr==mx+1 );
71691   if( pEList && pEList->nExpr>mx ){
71692     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
71693   }
71694 }
71695
71696 /*
71697 ** Delete an entire expression list.
71698 */
71699 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
71700   int i;
71701   struct ExprList_item *pItem;
71702   if( pList==0 ) return;
71703   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
71704   assert( pList->nExpr<=pList->nAlloc );
71705   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71706     sqlite3ExprDelete(db, pItem->pExpr);
71707     sqlite3DbFree(db, pItem->zName);
71708     sqlite3DbFree(db, pItem->zSpan);
71709   }
71710   sqlite3DbFree(db, pList->a);
71711   sqlite3DbFree(db, pList);
71712 }
71713
71714 /*
71715 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
71716 ** to an integer.  These routines are checking an expression to see
71717 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
71718 ** not constant.
71719 **
71720 ** These callback routines are used to implement the following:
71721 **
71722 **     sqlite3ExprIsConstant()
71723 **     sqlite3ExprIsConstantNotJoin()
71724 **     sqlite3ExprIsConstantOrFunction()
71725 **
71726 */
71727 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
71728
71729   /* If pWalker->u.i is 3 then any term of the expression that comes from
71730   ** the ON or USING clauses of a join disqualifies the expression
71731   ** from being considered constant. */
71732   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
71733     pWalker->u.i = 0;
71734     return WRC_Abort;
71735   }
71736
71737   switch( pExpr->op ){
71738     /* Consider functions to be constant if all their arguments are constant
71739     ** and pWalker->u.i==2 */
71740     case TK_FUNCTION:
71741       if( pWalker->u.i==2 ) return 0;
71742       /* Fall through */
71743     case TK_ID:
71744     case TK_COLUMN:
71745     case TK_AGG_FUNCTION:
71746     case TK_AGG_COLUMN:
71747       testcase( pExpr->op==TK_ID );
71748       testcase( pExpr->op==TK_COLUMN );
71749       testcase( pExpr->op==TK_AGG_FUNCTION );
71750       testcase( pExpr->op==TK_AGG_COLUMN );
71751       pWalker->u.i = 0;
71752       return WRC_Abort;
71753     default:
71754       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
71755       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
71756       return WRC_Continue;
71757   }
71758 }
71759 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
71760   UNUSED_PARAMETER(NotUsed);
71761   pWalker->u.i = 0;
71762   return WRC_Abort;
71763 }
71764 static int exprIsConst(Expr *p, int initFlag){
71765   Walker w;
71766   w.u.i = initFlag;
71767   w.xExprCallback = exprNodeIsConstant;
71768   w.xSelectCallback = selectNodeIsConstant;
71769   sqlite3WalkExpr(&w, p);
71770   return w.u.i;
71771 }
71772
71773 /*
71774 ** Walk an expression tree.  Return 1 if the expression is constant
71775 ** and 0 if it involves variables or function calls.
71776 **
71777 ** For the purposes of this function, a double-quoted string (ex: "abc")
71778 ** is considered a variable but a single-quoted string (ex: 'abc') is
71779 ** a constant.
71780 */
71781 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
71782   return exprIsConst(p, 1);
71783 }
71784
71785 /*
71786 ** Walk an expression tree.  Return 1 if the expression is constant
71787 ** that does no originate from the ON or USING clauses of a join.
71788 ** Return 0 if it involves variables or function calls or terms from
71789 ** an ON or USING clause.
71790 */
71791 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
71792   return exprIsConst(p, 3);
71793 }
71794
71795 /*
71796 ** Walk an expression tree.  Return 1 if the expression is constant
71797 ** or a function call with constant arguments.  Return and 0 if there
71798 ** are any variables.
71799 **
71800 ** For the purposes of this function, a double-quoted string (ex: "abc")
71801 ** is considered a variable but a single-quoted string (ex: 'abc') is
71802 ** a constant.
71803 */
71804 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
71805   return exprIsConst(p, 2);
71806 }
71807
71808 /*
71809 ** If the expression p codes a constant integer that is small enough
71810 ** to fit in a 32-bit integer, return 1 and put the value of the integer
71811 ** in *pValue.  If the expression is not an integer or if it is too big
71812 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
71813 */
71814 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
71815   int rc = 0;
71816
71817   /* If an expression is an integer literal that fits in a signed 32-bit
71818   ** integer, then the EP_IntValue flag will have already been set */
71819   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
71820            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
71821
71822   if( p->flags & EP_IntValue ){
71823     *pValue = p->u.iValue;
71824     return 1;
71825   }
71826   switch( p->op ){
71827     case TK_UPLUS: {
71828       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
71829       break;
71830     }
71831     case TK_UMINUS: {
71832       int v;
71833       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
71834         *pValue = -v;
71835         rc = 1;
71836       }
71837       break;
71838     }
71839     default: break;
71840   }
71841   return rc;
71842 }
71843
71844 /*
71845 ** Return FALSE if there is no chance that the expression can be NULL.
71846 **
71847 ** If the expression might be NULL or if the expression is too complex
71848 ** to tell return TRUE.  
71849 **
71850 ** This routine is used as an optimization, to skip OP_IsNull opcodes
71851 ** when we know that a value cannot be NULL.  Hence, a false positive
71852 ** (returning TRUE when in fact the expression can never be NULL) might
71853 ** be a small performance hit but is otherwise harmless.  On the other
71854 ** hand, a false negative (returning FALSE when the result could be NULL)
71855 ** will likely result in an incorrect answer.  So when in doubt, return
71856 ** TRUE.
71857 */
71858 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
71859   u8 op;
71860   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
71861   op = p->op;
71862   if( op==TK_REGISTER ) op = p->op2;
71863   switch( op ){
71864     case TK_INTEGER:
71865     case TK_STRING:
71866     case TK_FLOAT:
71867     case TK_BLOB:
71868       return 0;
71869     default:
71870       return 1;
71871   }
71872 }
71873
71874 /*
71875 ** Generate an OP_IsNull instruction that tests register iReg and jumps
71876 ** to location iDest if the value in iReg is NULL.  The value in iReg 
71877 ** was computed by pExpr.  If we can look at pExpr at compile-time and
71878 ** determine that it can never generate a NULL, then the OP_IsNull operation
71879 ** can be omitted.
71880 */
71881 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
71882   Vdbe *v,            /* The VDBE under construction */
71883   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
71884   int iReg,           /* Test the value in this register for NULL */
71885   int iDest           /* Jump here if the value is null */
71886 ){
71887   if( sqlite3ExprCanBeNull(pExpr) ){
71888     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
71889   }
71890 }
71891
71892 /*
71893 ** Return TRUE if the given expression is a constant which would be
71894 ** unchanged by OP_Affinity with the affinity given in the second
71895 ** argument.
71896 **
71897 ** This routine is used to determine if the OP_Affinity operation
71898 ** can be omitted.  When in doubt return FALSE.  A false negative
71899 ** is harmless.  A false positive, however, can result in the wrong
71900 ** answer.
71901 */
71902 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
71903   u8 op;
71904   if( aff==SQLITE_AFF_NONE ) return 1;
71905   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
71906   op = p->op;
71907   if( op==TK_REGISTER ) op = p->op2;
71908   switch( op ){
71909     case TK_INTEGER: {
71910       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
71911     }
71912     case TK_FLOAT: {
71913       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
71914     }
71915     case TK_STRING: {
71916       return aff==SQLITE_AFF_TEXT;
71917     }
71918     case TK_BLOB: {
71919       return 1;
71920     }
71921     case TK_COLUMN: {
71922       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
71923       return p->iColumn<0
71924           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
71925     }
71926     default: {
71927       return 0;
71928     }
71929   }
71930 }
71931
71932 /*
71933 ** Return TRUE if the given string is a row-id column name.
71934 */
71935 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
71936   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
71937   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
71938   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
71939   return 0;
71940 }
71941
71942 /*
71943 ** Return true if we are able to the IN operator optimization on a
71944 ** query of the form
71945 **
71946 **       x IN (SELECT ...)
71947 **
71948 ** Where the SELECT... clause is as specified by the parameter to this
71949 ** routine.
71950 **
71951 ** The Select object passed in has already been preprocessed and no
71952 ** errors have been found.
71953 */
71954 #ifndef SQLITE_OMIT_SUBQUERY
71955 static int isCandidateForInOpt(Select *p){
71956   SrcList *pSrc;
71957   ExprList *pEList;
71958   Table *pTab;
71959   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
71960   if( p->pPrior ) return 0;              /* Not a compound SELECT */
71961   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
71962     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
71963     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
71964     return 0; /* No DISTINCT keyword and no aggregate functions */
71965   }
71966   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
71967   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
71968   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
71969   if( p->pWhere ) return 0;              /* Has no WHERE clause */
71970   pSrc = p->pSrc;
71971   assert( pSrc!=0 );
71972   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
71973   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
71974   pTab = pSrc->a[0].pTab;
71975   if( NEVER(pTab==0) ) return 0;
71976   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
71977   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
71978   pEList = p->pEList;
71979   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
71980   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
71981   return 1;
71982 }
71983 #endif /* SQLITE_OMIT_SUBQUERY */
71984
71985 /*
71986 ** This function is used by the implementation of the IN (...) operator.
71987 ** It's job is to find or create a b-tree structure that may be used
71988 ** either to test for membership of the (...) set or to iterate through
71989 ** its members, skipping duplicates.
71990 **
71991 ** The index of the cursor opened on the b-tree (database table, database index 
71992 ** or ephermal table) is stored in pX->iTable before this function returns.
71993 ** The returned value of this function indicates the b-tree type, as follows:
71994 **
71995 **   IN_INDEX_ROWID - The cursor was opened on a database table.
71996 **   IN_INDEX_INDEX - The cursor was opened on a database index.
71997 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
71998 **                    populated epheremal table.
71999 **
72000 ** An existing b-tree may only be used if the SELECT is of the simple
72001 ** form:
72002 **
72003 **     SELECT <column> FROM <table>
72004 **
72005 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
72006 ** through the set members, skipping any duplicates. In this case an
72007 ** epheremal table must be used unless the selected <column> is guaranteed
72008 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
72009 ** has a UNIQUE constraint or UNIQUE index.
72010 **
72011 ** If the prNotFound parameter is not 0, then the b-tree will be used 
72012 ** for fast set membership tests. In this case an epheremal table must 
72013 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
72014 ** be found with <column> as its left-most column.
72015 **
72016 ** When the b-tree is being used for membership tests, the calling function
72017 ** needs to know whether or not the structure contains an SQL NULL 
72018 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72019 ** If there is any chance that the (...) might contain a NULL value at
72020 ** runtime, then a register is allocated and the register number written
72021 ** to *prNotFound. If there is no chance that the (...) contains a
72022 ** NULL value, then *prNotFound is left unchanged.
72023 **
72024 ** If a register is allocated and its location stored in *prNotFound, then
72025 ** its initial value is NULL.  If the (...) does not remain constant
72026 ** for the duration of the query (i.e. the SELECT within the (...)
72027 ** is a correlated subquery) then the value of the allocated register is
72028 ** reset to NULL each time the subquery is rerun. This allows the
72029 ** caller to use vdbe code equivalent to the following:
72030 **
72031 **   if( register==NULL ){
72032 **     has_null = <test if data structure contains null>
72033 **     register = 1
72034 **   }
72035 **
72036 ** in order to avoid running the <test if data structure contains null>
72037 ** test more often than is necessary.
72038 */
72039 #ifndef SQLITE_OMIT_SUBQUERY
72040 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72041   Select *p;                            /* SELECT to the right of IN operator */
72042   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
72043   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
72044   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
72045
72046   assert( pX->op==TK_IN );
72047
72048   /* Check to see if an existing table or index can be used to
72049   ** satisfy the query.  This is preferable to generating a new 
72050   ** ephemeral table.
72051   */
72052   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72053   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72054     sqlite3 *db = pParse->db;              /* Database connection */
72055     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
72056     int iCol = pExpr->iColumn;             /* Index of column <column> */
72057     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
72058     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
72059     int iDb;                               /* Database idx for pTab */
72060    
72061     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72062     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72063     sqlite3CodeVerifySchema(pParse, iDb);
72064     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72065
72066     /* This function is only called from two places. In both cases the vdbe
72067     ** has already been allocated. So assume sqlite3GetVdbe() is always
72068     ** successful here.
72069     */
72070     assert(v);
72071     if( iCol<0 ){
72072       int iMem = ++pParse->nMem;
72073       int iAddr;
72074
72075       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72076       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72077
72078       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72079       eType = IN_INDEX_ROWID;
72080
72081       sqlite3VdbeJumpHere(v, iAddr);
72082     }else{
72083       Index *pIdx;                         /* Iterator variable */
72084
72085       /* The collation sequence used by the comparison. If an index is to
72086       ** be used in place of a temp-table, it must be ordered according
72087       ** to this collation sequence.  */
72088       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72089
72090       /* Check that the affinity that will be used to perform the 
72091       ** comparison is the same as the affinity of the column. If
72092       ** it is not, it is not possible to use any index.
72093       */
72094       char aff = comparisonAffinity(pX);
72095       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72096
72097       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72098         if( (pIdx->aiColumn[0]==iCol)
72099          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72100          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72101         ){
72102           int iMem = ++pParse->nMem;
72103           int iAddr;
72104           char *pKey;
72105   
72106           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72107           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72108           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72109   
72110           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72111                                pKey,P4_KEYINFO_HANDOFF);
72112           VdbeComment((v, "%s", pIdx->zName));
72113           eType = IN_INDEX_INDEX;
72114
72115           sqlite3VdbeJumpHere(v, iAddr);
72116           if( prNotFound && !pTab->aCol[iCol].notNull ){
72117             *prNotFound = ++pParse->nMem;
72118           }
72119         }
72120       }
72121     }
72122   }
72123
72124   if( eType==0 ){
72125     /* Could not found an existing table or index to use as the RHS b-tree.
72126     ** We will have to generate an ephemeral table to do the job.
72127     */
72128     double savedNQueryLoop = pParse->nQueryLoop;
72129     int rMayHaveNull = 0;
72130     eType = IN_INDEX_EPH;
72131     if( prNotFound ){
72132       *prNotFound = rMayHaveNull = ++pParse->nMem;
72133     }else{
72134       testcase( pParse->nQueryLoop>(double)1 );
72135       pParse->nQueryLoop = (double)1;
72136       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72137         eType = IN_INDEX_ROWID;
72138       }
72139     }
72140     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72141     pParse->nQueryLoop = savedNQueryLoop;
72142   }else{
72143     pX->iTable = iTab;
72144   }
72145   return eType;
72146 }
72147 #endif
72148
72149 /*
72150 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72151 ** or IN operators.  Examples:
72152 **
72153 **     (SELECT a FROM b)          -- subquery
72154 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
72155 **     x IN (4,5,11)              -- IN operator with list on right-hand side
72156 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
72157 **
72158 ** The pExpr parameter describes the expression that contains the IN
72159 ** operator or subquery.
72160 **
72161 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72162 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72163 ** to some integer key column of a table B-Tree. In this case, use an
72164 ** intkey B-Tree to store the set of IN(...) values instead of the usual
72165 ** (slower) variable length keys B-Tree.
72166 **
72167 ** If rMayHaveNull is non-zero, that means that the operation is an IN
72168 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72169 ** Furthermore, the IN is in a WHERE clause and that we really want
72170 ** to iterate over the RHS of the IN operator in order to quickly locate
72171 ** all corresponding LHS elements.  All this routine does is initialize
72172 ** the register given by rMayHaveNull to NULL.  Calling routines will take
72173 ** care of changing this register value to non-NULL if the RHS is NULL-free.
72174 **
72175 ** If rMayHaveNull is zero, that means that the subquery is being used
72176 ** for membership testing only.  There is no need to initialize any
72177 ** registers to indicate the presense or absence of NULLs on the RHS.
72178 **
72179 ** For a SELECT or EXISTS operator, return the register that holds the
72180 ** result.  For IN operators or if an error occurs, the return value is 0.
72181 */
72182 #ifndef SQLITE_OMIT_SUBQUERY
72183 SQLITE_PRIVATE int sqlite3CodeSubselect(
72184   Parse *pParse,          /* Parsing context */
72185   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
72186   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
72187   int isRowid             /* If true, LHS of IN operator is a rowid */
72188 ){
72189   int testAddr = 0;                       /* One-time test address */
72190   int rReg = 0;                           /* Register storing resulting */
72191   Vdbe *v = sqlite3GetVdbe(pParse);
72192   if( NEVER(v==0) ) return 0;
72193   sqlite3ExprCachePush(pParse);
72194
72195   /* This code must be run in its entirety every time it is encountered
72196   ** if any of the following is true:
72197   **
72198   **    *  The right-hand side is a correlated subquery
72199   **    *  The right-hand side is an expression list containing variables
72200   **    *  We are inside a trigger
72201   **
72202   ** If all of the above are false, then we can run this code just once
72203   ** save the results, and reuse the same result on subsequent invocations.
72204   */
72205   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72206     int mem = ++pParse->nMem;
72207     sqlite3VdbeAddOp1(v, OP_If, mem);
72208     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72209     assert( testAddr>0 || pParse->db->mallocFailed );
72210   }
72211
72212 #ifndef SQLITE_OMIT_EXPLAIN
72213   if( pParse->explain==2 ){
72214     char *zMsg = sqlite3MPrintf(
72215         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72216         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72217     );
72218     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72219   }
72220 #endif
72221
72222   switch( pExpr->op ){
72223     case TK_IN: {
72224       char affinity;              /* Affinity of the LHS of the IN */
72225       KeyInfo keyInfo;            /* Keyinfo for the generated table */
72226       int addr;                   /* Address of OP_OpenEphemeral instruction */
72227       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72228
72229       if( rMayHaveNull ){
72230         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72231       }
72232
72233       affinity = sqlite3ExprAffinity(pLeft);
72234
72235       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72236       ** expression it is handled the same way.  An ephemeral table is 
72237       ** filled with single-field index keys representing the results
72238       ** from the SELECT or the <exprlist>.
72239       **
72240       ** If the 'x' expression is a column value, or the SELECT...
72241       ** statement returns a column value, then the affinity of that
72242       ** column is used to build the index keys. If both 'x' and the
72243       ** SELECT... statement are columns, then numeric affinity is used
72244       ** if either column has NUMERIC or INTEGER affinity. If neither
72245       ** 'x' nor the SELECT... statement are columns, then numeric affinity
72246       ** is used.
72247       */
72248       pExpr->iTable = pParse->nTab++;
72249       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72250       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72251       memset(&keyInfo, 0, sizeof(keyInfo));
72252       keyInfo.nField = 1;
72253
72254       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72255         /* Case 1:     expr IN (SELECT ...)
72256         **
72257         ** Generate code to write the results of the select into the temporary
72258         ** table allocated and opened above.
72259         */
72260         SelectDest dest;
72261         ExprList *pEList;
72262
72263         assert( !isRowid );
72264         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72265         dest.affinity = (u8)affinity;
72266         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72267         pExpr->x.pSelect->iLimit = 0;
72268         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72269           return 0;
72270         }
72271         pEList = pExpr->x.pSelect->pEList;
72272         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
72273           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72274               pEList->a[0].pExpr);
72275         }
72276       }else if( ALWAYS(pExpr->x.pList!=0) ){
72277         /* Case 2:     expr IN (exprlist)
72278         **
72279         ** For each expression, build an index key from the evaluation and
72280         ** store it in the temporary table. If <expr> is a column, then use
72281         ** that columns affinity when building index keys. If <expr> is not
72282         ** a column, use numeric affinity.
72283         */
72284         int i;
72285         ExprList *pList = pExpr->x.pList;
72286         struct ExprList_item *pItem;
72287         int r1, r2, r3;
72288
72289         if( !affinity ){
72290           affinity = SQLITE_AFF_NONE;
72291         }
72292         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72293
72294         /* Loop through each expression in <exprlist>. */
72295         r1 = sqlite3GetTempReg(pParse);
72296         r2 = sqlite3GetTempReg(pParse);
72297         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72298         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72299           Expr *pE2 = pItem->pExpr;
72300           int iValToIns;
72301
72302           /* If the expression is not constant then we will need to
72303           ** disable the test that was generated above that makes sure
72304           ** this code only executes once.  Because for a non-constant
72305           ** expression we need to rerun this code each time.
72306           */
72307           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72308             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72309             testAddr = 0;
72310           }
72311
72312           /* Evaluate the expression and insert it into the temp table */
72313           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72314             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72315           }else{
72316             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72317             if( isRowid ){
72318               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72319                                 sqlite3VdbeCurrentAddr(v)+2);
72320               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72321             }else{
72322               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72323               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72324               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72325             }
72326           }
72327         }
72328         sqlite3ReleaseTempReg(pParse, r1);
72329         sqlite3ReleaseTempReg(pParse, r2);
72330       }
72331       if( !isRowid ){
72332         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72333       }
72334       break;
72335     }
72336
72337     case TK_EXISTS:
72338     case TK_SELECT:
72339     default: {
72340       /* If this has to be a scalar SELECT.  Generate code to put the
72341       ** value of this select in a memory cell and record the number
72342       ** of the memory cell in iColumn.  If this is an EXISTS, write
72343       ** an integer 0 (not exists) or 1 (exists) into a memory cell
72344       ** and record that memory cell in iColumn.
72345       */
72346       Select *pSel;                         /* SELECT statement to encode */
72347       SelectDest dest;                      /* How to deal with SELECt result */
72348
72349       testcase( pExpr->op==TK_EXISTS );
72350       testcase( pExpr->op==TK_SELECT );
72351       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72352
72353       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72354       pSel = pExpr->x.pSelect;
72355       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72356       if( pExpr->op==TK_SELECT ){
72357         dest.eDest = SRT_Mem;
72358         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72359         VdbeComment((v, "Init subquery result"));
72360       }else{
72361         dest.eDest = SRT_Exists;
72362         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72363         VdbeComment((v, "Init EXISTS result"));
72364       }
72365       sqlite3ExprDelete(pParse->db, pSel->pLimit);
72366       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72367                                   &sqlite3IntTokens[1]);
72368       pSel->iLimit = 0;
72369       if( sqlite3Select(pParse, pSel, &dest) ){
72370         return 0;
72371       }
72372       rReg = dest.iParm;
72373       ExprSetIrreducible(pExpr);
72374       break;
72375     }
72376   }
72377
72378   if( testAddr ){
72379     sqlite3VdbeJumpHere(v, testAddr-1);
72380   }
72381   sqlite3ExprCachePop(pParse, 1);
72382
72383   return rReg;
72384 }
72385 #endif /* SQLITE_OMIT_SUBQUERY */
72386
72387 #ifndef SQLITE_OMIT_SUBQUERY
72388 /*
72389 ** Generate code for an IN expression.
72390 **
72391 **      x IN (SELECT ...)
72392 **      x IN (value, value, ...)
72393 **
72394 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
72395 ** is an array of zero or more values.  The expression is true if the LHS is
72396 ** contained within the RHS.  The value of the expression is unknown (NULL)
72397 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
72398 ** RHS contains one or more NULL values.
72399 **
72400 ** This routine generates code will jump to destIfFalse if the LHS is not 
72401 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
72402 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
72403 ** within the RHS then fall through.
72404 */
72405 static void sqlite3ExprCodeIN(
72406   Parse *pParse,        /* Parsing and code generating context */
72407   Expr *pExpr,          /* The IN expression */
72408   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
72409   int destIfNull        /* Jump here if the results are unknown due to NULLs */
72410 ){
72411   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
72412   char affinity;        /* Comparison affinity to use */
72413   int eType;            /* Type of the RHS */
72414   int r1;               /* Temporary use register */
72415   Vdbe *v;              /* Statement under construction */
72416
72417   /* Compute the RHS.   After this step, the table with cursor
72418   ** pExpr->iTable will contains the values that make up the RHS.
72419   */
72420   v = pParse->pVdbe;
72421   assert( v!=0 );       /* OOM detected prior to this routine */
72422   VdbeNoopComment((v, "begin IN expr"));
72423   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
72424
72425   /* Figure out the affinity to use to create a key from the results
72426   ** of the expression. affinityStr stores a static string suitable for
72427   ** P4 of OP_MakeRecord.
72428   */
72429   affinity = comparisonAffinity(pExpr);
72430
72431   /* Code the LHS, the <expr> from "<expr> IN (...)".
72432   */
72433   sqlite3ExprCachePush(pParse);
72434   r1 = sqlite3GetTempReg(pParse);
72435   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
72436
72437   /* If the LHS is NULL, then the result is either false or NULL depending
72438   ** on whether the RHS is empty or not, respectively.
72439   */
72440   if( destIfNull==destIfFalse ){
72441     /* Shortcut for the common case where the false and NULL outcomes are
72442     ** the same. */
72443     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
72444   }else{
72445     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
72446     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
72447     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
72448     sqlite3VdbeJumpHere(v, addr1);
72449   }
72450
72451   if( eType==IN_INDEX_ROWID ){
72452     /* In this case, the RHS is the ROWID of table b-tree
72453     */
72454     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
72455     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
72456   }else{
72457     /* In this case, the RHS is an index b-tree.
72458     */
72459     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
72460
72461     /* If the set membership test fails, then the result of the 
72462     ** "x IN (...)" expression must be either 0 or NULL. If the set
72463     ** contains no NULL values, then the result is 0. If the set 
72464     ** contains one or more NULL values, then the result of the
72465     ** expression is also NULL.
72466     */
72467     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
72468       /* This branch runs if it is known at compile time that the RHS
72469       ** cannot contain NULL values. This happens as the result
72470       ** of a "NOT NULL" constraint in the database schema.
72471       **
72472       ** Also run this branch if NULL is equivalent to FALSE
72473       ** for this particular IN operator.
72474       */
72475       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
72476
72477     }else{
72478       /* In this branch, the RHS of the IN might contain a NULL and
72479       ** the presence of a NULL on the RHS makes a difference in the
72480       ** outcome.
72481       */
72482       int j1, j2, j3;
72483
72484       /* First check to see if the LHS is contained in the RHS.  If so,
72485       ** then the presence of NULLs in the RHS does not matter, so jump
72486       ** over all of the code that follows.
72487       */
72488       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
72489
72490       /* Here we begin generating code that runs if the LHS is not
72491       ** contained within the RHS.  Generate additional code that
72492       ** tests the RHS for NULLs.  If the RHS contains a NULL then
72493       ** jump to destIfNull.  If there are no NULLs in the RHS then
72494       ** jump to destIfFalse.
72495       */
72496       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
72497       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
72498       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
72499       sqlite3VdbeJumpHere(v, j3);
72500       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
72501       sqlite3VdbeJumpHere(v, j2);
72502
72503       /* Jump to the appropriate target depending on whether or not
72504       ** the RHS contains a NULL
72505       */
72506       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
72507       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
72508
72509       /* The OP_Found at the top of this branch jumps here when true, 
72510       ** causing the overall IN expression evaluation to fall through.
72511       */
72512       sqlite3VdbeJumpHere(v, j1);
72513     }
72514   }
72515   sqlite3ReleaseTempReg(pParse, r1);
72516   sqlite3ExprCachePop(pParse, 1);
72517   VdbeComment((v, "end IN expr"));
72518 }
72519 #endif /* SQLITE_OMIT_SUBQUERY */
72520
72521 /*
72522 ** Duplicate an 8-byte value
72523 */
72524 static char *dup8bytes(Vdbe *v, const char *in){
72525   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
72526   if( out ){
72527     memcpy(out, in, 8);
72528   }
72529   return out;
72530 }
72531
72532 #ifndef SQLITE_OMIT_FLOATING_POINT
72533 /*
72534 ** Generate an instruction that will put the floating point
72535 ** value described by z[0..n-1] into register iMem.
72536 **
72537 ** The z[] string will probably not be zero-terminated.  But the 
72538 ** z[n] character is guaranteed to be something that does not look
72539 ** like the continuation of the number.
72540 */
72541 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
72542   if( ALWAYS(z!=0) ){
72543     double value;
72544     char *zV;
72545     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72546     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
72547     if( negateFlag ) value = -value;
72548     zV = dup8bytes(v, (char*)&value);
72549     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
72550   }
72551 }
72552 #endif
72553
72554
72555 /*
72556 ** Generate an instruction that will put the integer describe by
72557 ** text z[0..n-1] into register iMem.
72558 **
72559 ** Expr.u.zToken is always UTF8 and zero-terminated.
72560 */
72561 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
72562   Vdbe *v = pParse->pVdbe;
72563   if( pExpr->flags & EP_IntValue ){
72564     int i = pExpr->u.iValue;
72565     assert( i>=0 );
72566     if( negFlag ) i = -i;
72567     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
72568   }else{
72569     int c;
72570     i64 value;
72571     const char *z = pExpr->u.zToken;
72572     assert( z!=0 );
72573     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72574     if( c==0 || (c==2 && negFlag) ){
72575       char *zV;
72576       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
72577       zV = dup8bytes(v, (char*)&value);
72578       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
72579     }else{
72580 #ifdef SQLITE_OMIT_FLOATING_POINT
72581       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
72582 #else
72583       codeReal(v, z, negFlag, iMem);
72584 #endif
72585     }
72586   }
72587 }
72588
72589 /*
72590 ** Clear a cache entry.
72591 */
72592 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
72593   if( p->tempReg ){
72594     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72595       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
72596     }
72597     p->tempReg = 0;
72598   }
72599 }
72600
72601
72602 /*
72603 ** Record in the column cache that a particular column from a
72604 ** particular table is stored in a particular register.
72605 */
72606 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
72607   int i;
72608   int minLru;
72609   int idxLru;
72610   struct yColCache *p;
72611
72612   assert( iReg>0 );  /* Register numbers are always positive */
72613   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
72614
72615   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
72616   ** for testing only - to verify that SQLite always gets the same answer
72617   ** with and without the column cache.
72618   */
72619   if( pParse->db->flags & SQLITE_ColumnCache ) return;
72620
72621   /* First replace any existing entry.
72622   **
72623   ** Actually, the way the column cache is currently used, we are guaranteed
72624   ** that the object will never already be in cache.  Verify this guarantee.
72625   */
72626 #ifndef NDEBUG
72627   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72628 #if 0 /* This code wold remove the entry from the cache if it existed */
72629     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
72630       cacheEntryClear(pParse, p);
72631       p->iLevel = pParse->iCacheLevel;
72632       p->iReg = iReg;
72633       p->lru = pParse->iCacheCnt++;
72634       return;
72635     }
72636 #endif
72637     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
72638   }
72639 #endif
72640
72641   /* Find an empty slot and replace it */
72642   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72643     if( p->iReg==0 ){
72644       p->iLevel = pParse->iCacheLevel;
72645       p->iTable = iTab;
72646       p->iColumn = iCol;
72647       p->iReg = iReg;
72648       p->tempReg = 0;
72649       p->lru = pParse->iCacheCnt++;
72650       return;
72651     }
72652   }
72653
72654   /* Replace the last recently used */
72655   minLru = 0x7fffffff;
72656   idxLru = -1;
72657   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72658     if( p->lru<minLru ){
72659       idxLru = i;
72660       minLru = p->lru;
72661     }
72662   }
72663   if( ALWAYS(idxLru>=0) ){
72664     p = &pParse->aColCache[idxLru];
72665     p->iLevel = pParse->iCacheLevel;
72666     p->iTable = iTab;
72667     p->iColumn = iCol;
72668     p->iReg = iReg;
72669     p->tempReg = 0;
72670     p->lru = pParse->iCacheCnt++;
72671     return;
72672   }
72673 }
72674
72675 /*
72676 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
72677 ** Purge the range of registers from the column cache.
72678 */
72679 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
72680   int i;
72681   int iLast = iReg + nReg - 1;
72682   struct yColCache *p;
72683   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72684     int r = p->iReg;
72685     if( r>=iReg && r<=iLast ){
72686       cacheEntryClear(pParse, p);
72687       p->iReg = 0;
72688     }
72689   }
72690 }
72691
72692 /*
72693 ** Remember the current column cache context.  Any new entries added
72694 ** added to the column cache after this call are removed when the
72695 ** corresponding pop occurs.
72696 */
72697 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
72698   pParse->iCacheLevel++;
72699 }
72700
72701 /*
72702 ** Remove from the column cache any entries that were added since the
72703 ** the previous N Push operations.  In other words, restore the cache
72704 ** to the state it was in N Pushes ago.
72705 */
72706 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
72707   int i;
72708   struct yColCache *p;
72709   assert( N>0 );
72710   assert( pParse->iCacheLevel>=N );
72711   pParse->iCacheLevel -= N;
72712   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72713     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
72714       cacheEntryClear(pParse, p);
72715       p->iReg = 0;
72716     }
72717   }
72718 }
72719
72720 /*
72721 ** When a cached column is reused, make sure that its register is
72722 ** no longer available as a temp register.  ticket #3879:  that same
72723 ** register might be in the cache in multiple places, so be sure to
72724 ** get them all.
72725 */
72726 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
72727   int i;
72728   struct yColCache *p;
72729   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72730     if( p->iReg==iReg ){
72731       p->tempReg = 0;
72732     }
72733   }
72734 }
72735
72736 /*
72737 ** Generate code to extract the value of the iCol-th column of a table.
72738 */
72739 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
72740   Vdbe *v,        /* The VDBE under construction */
72741   Table *pTab,    /* The table containing the value */
72742   int iTabCur,    /* The cursor for this table */
72743   int iCol,       /* Index of the column to extract */
72744   int regOut      /* Extract the valud into this register */
72745 ){
72746   if( iCol<0 || iCol==pTab->iPKey ){
72747     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
72748   }else{
72749     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
72750     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
72751   }
72752   if( iCol>=0 ){
72753     sqlite3ColumnDefault(v, pTab, iCol, regOut);
72754   }
72755 }
72756
72757 /*
72758 ** Generate code that will extract the iColumn-th column from
72759 ** table pTab and store the column value in a register.  An effort
72760 ** is made to store the column value in register iReg, but this is
72761 ** not guaranteed.  The location of the column value is returned.
72762 **
72763 ** There must be an open cursor to pTab in iTable when this routine
72764 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
72765 */
72766 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
72767   Parse *pParse,   /* Parsing and code generating context */
72768   Table *pTab,     /* Description of the table we are reading from */
72769   int iColumn,     /* Index of the table column */
72770   int iTable,      /* The cursor pointing to the table */
72771   int iReg         /* Store results here */
72772 ){
72773   Vdbe *v = pParse->pVdbe;
72774   int i;
72775   struct yColCache *p;
72776
72777   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72778     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
72779       p->lru = pParse->iCacheCnt++;
72780       sqlite3ExprCachePinRegister(pParse, p->iReg);
72781       return p->iReg;
72782     }
72783   }  
72784   assert( v!=0 );
72785   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
72786   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
72787   return iReg;
72788 }
72789
72790 /*
72791 ** Clear all column cache entries.
72792 */
72793 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
72794   int i;
72795   struct yColCache *p;
72796
72797   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72798     if( p->iReg ){
72799       cacheEntryClear(pParse, p);
72800       p->iReg = 0;
72801     }
72802   }
72803 }
72804
72805 /*
72806 ** Record the fact that an affinity change has occurred on iCount
72807 ** registers starting with iStart.
72808 */
72809 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
72810   sqlite3ExprCacheRemove(pParse, iStart, iCount);
72811 }
72812
72813 /*
72814 ** Generate code to move content from registers iFrom...iFrom+nReg-1
72815 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
72816 */
72817 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
72818   int i;
72819   struct yColCache *p;
72820   if( NEVER(iFrom==iTo) ) return;
72821   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
72822   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72823     int x = p->iReg;
72824     if( x>=iFrom && x<iFrom+nReg ){
72825       p->iReg += iTo-iFrom;
72826     }
72827   }
72828 }
72829
72830 /*
72831 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
72832 ** over to iTo..iTo+nReg-1.
72833 */
72834 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
72835   int i;
72836   if( NEVER(iFrom==iTo) ) return;
72837   for(i=0; i<nReg; i++){
72838     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
72839   }
72840 }
72841
72842 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
72843 /*
72844 ** Return true if any register in the range iFrom..iTo (inclusive)
72845 ** is used as part of the column cache.
72846 **
72847 ** This routine is used within assert() and testcase() macros only
72848 ** and does not appear in a normal build.
72849 */
72850 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
72851   int i;
72852   struct yColCache *p;
72853   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72854     int r = p->iReg;
72855     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
72856   }
72857   return 0;
72858 }
72859 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
72860
72861 /*
72862 ** Generate code into the current Vdbe to evaluate the given
72863 ** expression.  Attempt to store the results in register "target".
72864 ** Return the register where results are stored.
72865 **
72866 ** With this routine, there is no guarantee that results will
72867 ** be stored in target.  The result might be stored in some other
72868 ** register if it is convenient to do so.  The calling function
72869 ** must check the return code and move the results to the desired
72870 ** register.
72871 */
72872 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
72873   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
72874   int op;                   /* The opcode being coded */
72875   int inReg = target;       /* Results stored in register inReg */
72876   int regFree1 = 0;         /* If non-zero free this temporary register */
72877   int regFree2 = 0;         /* If non-zero free this temporary register */
72878   int r1, r2, r3, r4;       /* Various register numbers */
72879   sqlite3 *db = pParse->db; /* The database connection */
72880
72881   assert( target>0 && target<=pParse->nMem );
72882   if( v==0 ){
72883     assert( pParse->db->mallocFailed );
72884     return 0;
72885   }
72886
72887   if( pExpr==0 ){
72888     op = TK_NULL;
72889   }else{
72890     op = pExpr->op;
72891   }
72892   switch( op ){
72893     case TK_AGG_COLUMN: {
72894       AggInfo *pAggInfo = pExpr->pAggInfo;
72895       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
72896       if( !pAggInfo->directMode ){
72897         assert( pCol->iMem>0 );
72898         inReg = pCol->iMem;
72899         break;
72900       }else if( pAggInfo->useSortingIdx ){
72901         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
72902                               pCol->iSorterColumn, target);
72903         break;
72904       }
72905       /* Otherwise, fall thru into the TK_COLUMN case */
72906     }
72907     case TK_COLUMN: {
72908       if( pExpr->iTable<0 ){
72909         /* This only happens when coding check constraints */
72910         assert( pParse->ckBase>0 );
72911         inReg = pExpr->iColumn + pParse->ckBase;
72912       }else{
72913         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
72914                                  pExpr->iColumn, pExpr->iTable, target);
72915       }
72916       break;
72917     }
72918     case TK_INTEGER: {
72919       codeInteger(pParse, pExpr, 0, target);
72920       break;
72921     }
72922 #ifndef SQLITE_OMIT_FLOATING_POINT
72923     case TK_FLOAT: {
72924       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72925       codeReal(v, pExpr->u.zToken, 0, target);
72926       break;
72927     }
72928 #endif
72929     case TK_STRING: {
72930       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72931       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
72932       break;
72933     }
72934     case TK_NULL: {
72935       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
72936       break;
72937     }
72938 #ifndef SQLITE_OMIT_BLOB_LITERAL
72939     case TK_BLOB: {
72940       int n;
72941       const char *z;
72942       char *zBlob;
72943       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72944       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
72945       assert( pExpr->u.zToken[1]=='\'' );
72946       z = &pExpr->u.zToken[2];
72947       n = sqlite3Strlen30(z) - 1;
72948       assert( z[n]=='\'' );
72949       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
72950       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
72951       break;
72952     }
72953 #endif
72954     case TK_VARIABLE: {
72955       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72956       assert( pExpr->u.zToken!=0 );
72957       assert( pExpr->u.zToken[0]!=0 );
72958       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
72959       if( pExpr->u.zToken[1]!=0 ){
72960         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
72961       }
72962       break;
72963     }
72964     case TK_REGISTER: {
72965       inReg = pExpr->iTable;
72966       break;
72967     }
72968     case TK_AS: {
72969       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
72970       break;
72971     }
72972 #ifndef SQLITE_OMIT_CAST
72973     case TK_CAST: {
72974       /* Expressions of the form:   CAST(pLeft AS token) */
72975       int aff, to_op;
72976       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
72977       assert( !ExprHasProperty(pExpr, EP_IntValue) );
72978       aff = sqlite3AffinityType(pExpr->u.zToken);
72979       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
72980       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
72981       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
72982       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
72983       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
72984       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
72985       testcase( to_op==OP_ToText );
72986       testcase( to_op==OP_ToBlob );
72987       testcase( to_op==OP_ToNumeric );
72988       testcase( to_op==OP_ToInt );
72989       testcase( to_op==OP_ToReal );
72990       if( inReg!=target ){
72991         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
72992         inReg = target;
72993       }
72994       sqlite3VdbeAddOp1(v, to_op, inReg);
72995       testcase( usedAsColumnCache(pParse, inReg, inReg) );
72996       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
72997       break;
72998     }
72999 #endif /* SQLITE_OMIT_CAST */
73000     case TK_LT:
73001     case TK_LE:
73002     case TK_GT:
73003     case TK_GE:
73004     case TK_NE:
73005     case TK_EQ: {
73006       assert( TK_LT==OP_Lt );
73007       assert( TK_LE==OP_Le );
73008       assert( TK_GT==OP_Gt );
73009       assert( TK_GE==OP_Ge );
73010       assert( TK_EQ==OP_Eq );
73011       assert( TK_NE==OP_Ne );
73012       testcase( op==TK_LT );
73013       testcase( op==TK_LE );
73014       testcase( op==TK_GT );
73015       testcase( op==TK_GE );
73016       testcase( op==TK_EQ );
73017       testcase( op==TK_NE );
73018       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73019       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73020       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73021                   r1, r2, inReg, SQLITE_STOREP2);
73022       testcase( regFree1==0 );
73023       testcase( regFree2==0 );
73024       break;
73025     }
73026     case TK_IS:
73027     case TK_ISNOT: {
73028       testcase( op==TK_IS );
73029       testcase( op==TK_ISNOT );
73030       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73031       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73032       op = (op==TK_IS) ? TK_EQ : TK_NE;
73033       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73034                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73035       testcase( regFree1==0 );
73036       testcase( regFree2==0 );
73037       break;
73038     }
73039     case TK_AND:
73040     case TK_OR:
73041     case TK_PLUS:
73042     case TK_STAR:
73043     case TK_MINUS:
73044     case TK_REM:
73045     case TK_BITAND:
73046     case TK_BITOR:
73047     case TK_SLASH:
73048     case TK_LSHIFT:
73049     case TK_RSHIFT: 
73050     case TK_CONCAT: {
73051       assert( TK_AND==OP_And );
73052       assert( TK_OR==OP_Or );
73053       assert( TK_PLUS==OP_Add );
73054       assert( TK_MINUS==OP_Subtract );
73055       assert( TK_REM==OP_Remainder );
73056       assert( TK_BITAND==OP_BitAnd );
73057       assert( TK_BITOR==OP_BitOr );
73058       assert( TK_SLASH==OP_Divide );
73059       assert( TK_LSHIFT==OP_ShiftLeft );
73060       assert( TK_RSHIFT==OP_ShiftRight );
73061       assert( TK_CONCAT==OP_Concat );
73062       testcase( op==TK_AND );
73063       testcase( op==TK_OR );
73064       testcase( op==TK_PLUS );
73065       testcase( op==TK_MINUS );
73066       testcase( op==TK_REM );
73067       testcase( op==TK_BITAND );
73068       testcase( op==TK_BITOR );
73069       testcase( op==TK_SLASH );
73070       testcase( op==TK_LSHIFT );
73071       testcase( op==TK_RSHIFT );
73072       testcase( op==TK_CONCAT );
73073       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73074       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73075       sqlite3VdbeAddOp3(v, op, r2, r1, target);
73076       testcase( regFree1==0 );
73077       testcase( regFree2==0 );
73078       break;
73079     }
73080     case TK_UMINUS: {
73081       Expr *pLeft = pExpr->pLeft;
73082       assert( pLeft );
73083       if( pLeft->op==TK_INTEGER ){
73084         codeInteger(pParse, pLeft, 1, target);
73085 #ifndef SQLITE_OMIT_FLOATING_POINT
73086       }else if( pLeft->op==TK_FLOAT ){
73087         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73088         codeReal(v, pLeft->u.zToken, 1, target);
73089 #endif
73090       }else{
73091         regFree1 = r1 = sqlite3GetTempReg(pParse);
73092         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73093         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73094         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73095         testcase( regFree2==0 );
73096       }
73097       inReg = target;
73098       break;
73099     }
73100     case TK_BITNOT:
73101     case TK_NOT: {
73102       assert( TK_BITNOT==OP_BitNot );
73103       assert( TK_NOT==OP_Not );
73104       testcase( op==TK_BITNOT );
73105       testcase( op==TK_NOT );
73106       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73107       testcase( regFree1==0 );
73108       inReg = target;
73109       sqlite3VdbeAddOp2(v, op, r1, inReg);
73110       break;
73111     }
73112     case TK_ISNULL:
73113     case TK_NOTNULL: {
73114       int addr;
73115       assert( TK_ISNULL==OP_IsNull );
73116       assert( TK_NOTNULL==OP_NotNull );
73117       testcase( op==TK_ISNULL );
73118       testcase( op==TK_NOTNULL );
73119       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73120       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73121       testcase( regFree1==0 );
73122       addr = sqlite3VdbeAddOp1(v, op, r1);
73123       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73124       sqlite3VdbeJumpHere(v, addr);
73125       break;
73126     }
73127     case TK_AGG_FUNCTION: {
73128       AggInfo *pInfo = pExpr->pAggInfo;
73129       if( pInfo==0 ){
73130         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73131         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73132       }else{
73133         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73134       }
73135       break;
73136     }
73137     case TK_CONST_FUNC:
73138     case TK_FUNCTION: {
73139       ExprList *pFarg;       /* List of function arguments */
73140       int nFarg;             /* Number of function arguments */
73141       FuncDef *pDef;         /* The function definition object */
73142       int nId;               /* Length of the function name in bytes */
73143       const char *zId;       /* The function name */
73144       int constMask = 0;     /* Mask of function arguments that are constant */
73145       int i;                 /* Loop counter */
73146       u8 enc = ENC(db);      /* The text encoding used by this database */
73147       CollSeq *pColl = 0;    /* A collating sequence */
73148
73149       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73150       testcase( op==TK_CONST_FUNC );
73151       testcase( op==TK_FUNCTION );
73152       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73153         pFarg = 0;
73154       }else{
73155         pFarg = pExpr->x.pList;
73156       }
73157       nFarg = pFarg ? pFarg->nExpr : 0;
73158       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73159       zId = pExpr->u.zToken;
73160       nId = sqlite3Strlen30(zId);
73161       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73162       if( pDef==0 ){
73163         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73164         break;
73165       }
73166
73167       /* Attempt a direct implementation of the built-in COALESCE() and
73168       ** IFNULL() functions.  This avoids unnecessary evalation of
73169       ** arguments past the first non-NULL argument.
73170       */
73171       if( pDef->flags & SQLITE_FUNC_COALESCE ){
73172         int endCoalesce = sqlite3VdbeMakeLabel(v);
73173         assert( nFarg>=2 );
73174         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73175         for(i=1; i<nFarg; i++){
73176           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73177           sqlite3ExprCacheRemove(pParse, target, 1);
73178           sqlite3ExprCachePush(pParse);
73179           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73180           sqlite3ExprCachePop(pParse, 1);
73181         }
73182         sqlite3VdbeResolveLabel(v, endCoalesce);
73183         break;
73184       }
73185
73186
73187       if( pFarg ){
73188         r1 = sqlite3GetTempRange(pParse, nFarg);
73189         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
73190         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73191         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
73192       }else{
73193         r1 = 0;
73194       }
73195 #ifndef SQLITE_OMIT_VIRTUALTABLE
73196       /* Possibly overload the function if the first argument is
73197       ** a virtual table column.
73198       **
73199       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73200       ** second argument, not the first, as the argument to test to
73201       ** see if it is a column in a virtual table.  This is done because
73202       ** the left operand of infix functions (the operand we want to
73203       ** control overloading) ends up as the second argument to the
73204       ** function.  The expression "A glob B" is equivalent to 
73205       ** "glob(B,A).  We want to use the A in "A glob B" to test
73206       ** for function overloading.  But we use the B term in "glob(B,A)".
73207       */
73208       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73209         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73210       }else if( nFarg>0 ){
73211         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73212       }
73213 #endif
73214       for(i=0; i<nFarg; i++){
73215         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73216           constMask |= (1<<i);
73217         }
73218         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73219           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73220         }
73221       }
73222       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73223         if( !pColl ) pColl = db->pDfltColl; 
73224         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73225       }
73226       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73227                         (char*)pDef, P4_FUNCDEF);
73228       sqlite3VdbeChangeP5(v, (u8)nFarg);
73229       if( nFarg ){
73230         sqlite3ReleaseTempRange(pParse, r1, nFarg);
73231       }
73232       break;
73233     }
73234 #ifndef SQLITE_OMIT_SUBQUERY
73235     case TK_EXISTS:
73236     case TK_SELECT: {
73237       testcase( op==TK_EXISTS );
73238       testcase( op==TK_SELECT );
73239       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73240       break;
73241     }
73242     case TK_IN: {
73243       int destIfFalse = sqlite3VdbeMakeLabel(v);
73244       int destIfNull = sqlite3VdbeMakeLabel(v);
73245       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73246       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73247       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73248       sqlite3VdbeResolveLabel(v, destIfFalse);
73249       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73250       sqlite3VdbeResolveLabel(v, destIfNull);
73251       break;
73252     }
73253 #endif /* SQLITE_OMIT_SUBQUERY */
73254
73255
73256     /*
73257     **    x BETWEEN y AND z
73258     **
73259     ** This is equivalent to
73260     **
73261     **    x>=y AND x<=z
73262     **
73263     ** X is stored in pExpr->pLeft.
73264     ** Y is stored in pExpr->pList->a[0].pExpr.
73265     ** Z is stored in pExpr->pList->a[1].pExpr.
73266     */
73267     case TK_BETWEEN: {
73268       Expr *pLeft = pExpr->pLeft;
73269       struct ExprList_item *pLItem = pExpr->x.pList->a;
73270       Expr *pRight = pLItem->pExpr;
73271
73272       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73273       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73274       testcase( regFree1==0 );
73275       testcase( regFree2==0 );
73276       r3 = sqlite3GetTempReg(pParse);
73277       r4 = sqlite3GetTempReg(pParse);
73278       codeCompare(pParse, pLeft, pRight, OP_Ge,
73279                   r1, r2, r3, SQLITE_STOREP2);
73280       pLItem++;
73281       pRight = pLItem->pExpr;
73282       sqlite3ReleaseTempReg(pParse, regFree2);
73283       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73284       testcase( regFree2==0 );
73285       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73286       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73287       sqlite3ReleaseTempReg(pParse, r3);
73288       sqlite3ReleaseTempReg(pParse, r4);
73289       break;
73290     }
73291     case TK_UPLUS: {
73292       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73293       break;
73294     }
73295
73296     case TK_TRIGGER: {
73297       /* If the opcode is TK_TRIGGER, then the expression is a reference
73298       ** to a column in the new.* or old.* pseudo-tables available to
73299       ** trigger programs. In this case Expr.iTable is set to 1 for the
73300       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73301       ** is set to the column of the pseudo-table to read, or to -1 to
73302       ** read the rowid field.
73303       **
73304       ** The expression is implemented using an OP_Param opcode. The p1
73305       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73306       ** to reference another column of the old.* pseudo-table, where 
73307       ** i is the index of the column. For a new.rowid reference, p1 is
73308       ** set to (n+1), where n is the number of columns in each pseudo-table.
73309       ** For a reference to any other column in the new.* pseudo-table, p1
73310       ** is set to (n+2+i), where n and i are as defined previously. For
73311       ** example, if the table on which triggers are being fired is
73312       ** declared as:
73313       **
73314       **   CREATE TABLE t1(a, b);
73315       **
73316       ** Then p1 is interpreted as follows:
73317       **
73318       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
73319       **   p1==1   ->    old.a         p1==4   ->    new.a
73320       **   p1==2   ->    old.b         p1==5   ->    new.b       
73321       */
73322       Table *pTab = pExpr->pTab;
73323       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73324
73325       assert( pExpr->iTable==0 || pExpr->iTable==1 );
73326       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73327       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73328       assert( p1>=0 && p1<(pTab->nCol*2+2) );
73329
73330       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73331       VdbeComment((v, "%s.%s -> $%d",
73332         (pExpr->iTable ? "new" : "old"),
73333         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73334         target
73335       ));
73336
73337 #ifndef SQLITE_OMIT_FLOATING_POINT
73338       /* If the column has REAL affinity, it may currently be stored as an
73339       ** integer. Use OP_RealAffinity to make sure it is really real.  */
73340       if( pExpr->iColumn>=0 
73341        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73342       ){
73343         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73344       }
73345 #endif
73346       break;
73347     }
73348
73349
73350     /*
73351     ** Form A:
73352     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73353     **
73354     ** Form B:
73355     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73356     **
73357     ** Form A is can be transformed into the equivalent form B as follows:
73358     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73359     **        WHEN x=eN THEN rN ELSE y END
73360     **
73361     ** X (if it exists) is in pExpr->pLeft.
73362     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
73363     ** ELSE clause and no other term matches, then the result of the
73364     ** exprssion is NULL.
73365     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73366     **
73367     ** The result of the expression is the Ri for the first matching Ei,
73368     ** or if there is no matching Ei, the ELSE term Y, or if there is
73369     ** no ELSE term, NULL.
73370     */
73371     default: assert( op==TK_CASE ); {
73372       int endLabel;                     /* GOTO label for end of CASE stmt */
73373       int nextCase;                     /* GOTO label for next WHEN clause */
73374       int nExpr;                        /* 2x number of WHEN terms */
73375       int i;                            /* Loop counter */
73376       ExprList *pEList;                 /* List of WHEN terms */
73377       struct ExprList_item *aListelem;  /* Array of WHEN terms */
73378       Expr opCompare;                   /* The X==Ei expression */
73379       Expr cacheX;                      /* Cached expression X */
73380       Expr *pX;                         /* The X expression */
73381       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
73382       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73383
73384       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73385       assert((pExpr->x.pList->nExpr % 2) == 0);
73386       assert(pExpr->x.pList->nExpr > 0);
73387       pEList = pExpr->x.pList;
73388       aListelem = pEList->a;
73389       nExpr = pEList->nExpr;
73390       endLabel = sqlite3VdbeMakeLabel(v);
73391       if( (pX = pExpr->pLeft)!=0 ){
73392         cacheX = *pX;
73393         testcase( pX->op==TK_COLUMN );
73394         testcase( pX->op==TK_REGISTER );
73395         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
73396         testcase( regFree1==0 );
73397         cacheX.op = TK_REGISTER;
73398         opCompare.op = TK_EQ;
73399         opCompare.pLeft = &cacheX;
73400         pTest = &opCompare;
73401         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
73402         ** The value in regFree1 might get SCopy-ed into the file result.
73403         ** So make sure that the regFree1 register is not reused for other
73404         ** purposes and possibly overwritten.  */
73405         regFree1 = 0;
73406       }
73407       for(i=0; i<nExpr; i=i+2){
73408         sqlite3ExprCachePush(pParse);
73409         if( pX ){
73410           assert( pTest!=0 );
73411           opCompare.pRight = aListelem[i].pExpr;
73412         }else{
73413           pTest = aListelem[i].pExpr;
73414         }
73415         nextCase = sqlite3VdbeMakeLabel(v);
73416         testcase( pTest->op==TK_COLUMN );
73417         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
73418         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
73419         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
73420         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
73421         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
73422         sqlite3ExprCachePop(pParse, 1);
73423         sqlite3VdbeResolveLabel(v, nextCase);
73424       }
73425       if( pExpr->pRight ){
73426         sqlite3ExprCachePush(pParse);
73427         sqlite3ExprCode(pParse, pExpr->pRight, target);
73428         sqlite3ExprCachePop(pParse, 1);
73429       }else{
73430         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73431       }
73432       assert( db->mallocFailed || pParse->nErr>0 
73433            || pParse->iCacheLevel==iCacheLevel );
73434       sqlite3VdbeResolveLabel(v, endLabel);
73435       break;
73436     }
73437 #ifndef SQLITE_OMIT_TRIGGER
73438     case TK_RAISE: {
73439       assert( pExpr->affinity==OE_Rollback 
73440            || pExpr->affinity==OE_Abort
73441            || pExpr->affinity==OE_Fail
73442            || pExpr->affinity==OE_Ignore
73443       );
73444       if( !pParse->pTriggerTab ){
73445         sqlite3ErrorMsg(pParse,
73446                        "RAISE() may only be used within a trigger-program");
73447         return 0;
73448       }
73449       if( pExpr->affinity==OE_Abort ){
73450         sqlite3MayAbort(pParse);
73451       }
73452       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73453       if( pExpr->affinity==OE_Ignore ){
73454         sqlite3VdbeAddOp4(
73455             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
73456       }else{
73457         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
73458       }
73459
73460       break;
73461     }
73462 #endif
73463   }
73464   sqlite3ReleaseTempReg(pParse, regFree1);
73465   sqlite3ReleaseTempReg(pParse, regFree2);
73466   return inReg;
73467 }
73468
73469 /*
73470 ** Generate code to evaluate an expression and store the results
73471 ** into a register.  Return the register number where the results
73472 ** are stored.
73473 **
73474 ** If the register is a temporary register that can be deallocated,
73475 ** then write its number into *pReg.  If the result register is not
73476 ** a temporary, then set *pReg to zero.
73477 */
73478 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
73479   int r1 = sqlite3GetTempReg(pParse);
73480   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73481   if( r2==r1 ){
73482     *pReg = r1;
73483   }else{
73484     sqlite3ReleaseTempReg(pParse, r1);
73485     *pReg = 0;
73486   }
73487   return r2;
73488 }
73489
73490 /*
73491 ** Generate code that will evaluate expression pExpr and store the
73492 ** results in register target.  The results are guaranteed to appear
73493 ** in register target.
73494 */
73495 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
73496   int inReg;
73497
73498   assert( target>0 && target<=pParse->nMem );
73499   if( pExpr && pExpr->op==TK_REGISTER ){
73500     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
73501   }else{
73502     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
73503     assert( pParse->pVdbe || pParse->db->mallocFailed );
73504     if( inReg!=target && pParse->pVdbe ){
73505       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
73506     }
73507   }
73508   return target;
73509 }
73510
73511 /*
73512 ** Generate code that evalutes the given expression and puts the result
73513 ** in register target.
73514 **
73515 ** Also make a copy of the expression results into another "cache" register
73516 ** and modify the expression so that the next time it is evaluated,
73517 ** the result is a copy of the cache register.
73518 **
73519 ** This routine is used for expressions that are used multiple 
73520 ** times.  They are evaluated once and the results of the expression
73521 ** are reused.
73522 */
73523 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
73524   Vdbe *v = pParse->pVdbe;
73525   int inReg;
73526   inReg = sqlite3ExprCode(pParse, pExpr, target);
73527   assert( target>0 );
73528   /* This routine is called for terms to INSERT or UPDATE.  And the only
73529   ** other place where expressions can be converted into TK_REGISTER is
73530   ** in WHERE clause processing.  So as currently implemented, there is
73531   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
73532   ** keep the ALWAYS() in case the conditions above change with future
73533   ** modifications or enhancements. */
73534   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
73535     int iMem;
73536     iMem = ++pParse->nMem;
73537     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
73538     pExpr->iTable = iMem;
73539     pExpr->op2 = pExpr->op;
73540     pExpr->op = TK_REGISTER;
73541   }
73542   return inReg;
73543 }
73544
73545 /*
73546 ** Return TRUE if pExpr is an constant expression that is appropriate
73547 ** for factoring out of a loop.  Appropriate expressions are:
73548 **
73549 **    *  Any expression that evaluates to two or more opcodes.
73550 **
73551 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
73552 **       or OP_Variable that does not need to be placed in a 
73553 **       specific register.
73554 **
73555 ** There is no point in factoring out single-instruction constant
73556 ** expressions that need to be placed in a particular register.  
73557 ** We could factor them out, but then we would end up adding an
73558 ** OP_SCopy instruction to move the value into the correct register
73559 ** later.  We might as well just use the original instruction and
73560 ** avoid the OP_SCopy.
73561 */
73562 static int isAppropriateForFactoring(Expr *p){
73563   if( !sqlite3ExprIsConstantNotJoin(p) ){
73564     return 0;  /* Only constant expressions are appropriate for factoring */
73565   }
73566   if( (p->flags & EP_FixedDest)==0 ){
73567     return 1;  /* Any constant without a fixed destination is appropriate */
73568   }
73569   while( p->op==TK_UPLUS ) p = p->pLeft;
73570   switch( p->op ){
73571 #ifndef SQLITE_OMIT_BLOB_LITERAL
73572     case TK_BLOB:
73573 #endif
73574     case TK_VARIABLE:
73575     case TK_INTEGER:
73576     case TK_FLOAT:
73577     case TK_NULL:
73578     case TK_STRING: {
73579       testcase( p->op==TK_BLOB );
73580       testcase( p->op==TK_VARIABLE );
73581       testcase( p->op==TK_INTEGER );
73582       testcase( p->op==TK_FLOAT );
73583       testcase( p->op==TK_NULL );
73584       testcase( p->op==TK_STRING );
73585       /* Single-instruction constants with a fixed destination are
73586       ** better done in-line.  If we factor them, they will just end
73587       ** up generating an OP_SCopy to move the value to the destination
73588       ** register. */
73589       return 0;
73590     }
73591     case TK_UMINUS: {
73592       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
73593         return 0;
73594       }
73595       break;
73596     }
73597     default: {
73598       break;
73599     }
73600   }
73601   return 1;
73602 }
73603
73604 /*
73605 ** If pExpr is a constant expression that is appropriate for
73606 ** factoring out of a loop, then evaluate the expression
73607 ** into a register and convert the expression into a TK_REGISTER
73608 ** expression.
73609 */
73610 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
73611   Parse *pParse = pWalker->pParse;
73612   switch( pExpr->op ){
73613     case TK_IN:
73614     case TK_REGISTER: {
73615       return WRC_Prune;
73616     }
73617     case TK_FUNCTION:
73618     case TK_AGG_FUNCTION:
73619     case TK_CONST_FUNC: {
73620       /* The arguments to a function have a fixed destination.
73621       ** Mark them this way to avoid generated unneeded OP_SCopy
73622       ** instructions. 
73623       */
73624       ExprList *pList = pExpr->x.pList;
73625       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73626       if( pList ){
73627         int i = pList->nExpr;
73628         struct ExprList_item *pItem = pList->a;
73629         for(; i>0; i--, pItem++){
73630           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
73631         }
73632       }
73633       break;
73634     }
73635   }
73636   if( isAppropriateForFactoring(pExpr) ){
73637     int r1 = ++pParse->nMem;
73638     int r2;
73639     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73640     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
73641     pExpr->op2 = pExpr->op;
73642     pExpr->op = TK_REGISTER;
73643     pExpr->iTable = r2;
73644     return WRC_Prune;
73645   }
73646   return WRC_Continue;
73647 }
73648
73649 /*
73650 ** Preevaluate constant subexpressions within pExpr and store the
73651 ** results in registers.  Modify pExpr so that the constant subexpresions
73652 ** are TK_REGISTER opcodes that refer to the precomputed values.
73653 **
73654 ** This routine is a no-op if the jump to the cookie-check code has
73655 ** already occur.  Since the cookie-check jump is generated prior to
73656 ** any other serious processing, this check ensures that there is no
73657 ** way to accidently bypass the constant initializations.
73658 **
73659 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
73660 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
73661 ** interface.  This allows test logic to verify that the same answer is
73662 ** obtained for queries regardless of whether or not constants are
73663 ** precomputed into registers or if they are inserted in-line.
73664 */
73665 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
73666   Walker w;
73667   if( pParse->cookieGoto ) return;
73668   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
73669   w.xExprCallback = evalConstExpr;
73670   w.xSelectCallback = 0;
73671   w.pParse = pParse;
73672   sqlite3WalkExpr(&w, pExpr);
73673 }
73674
73675
73676 /*
73677 ** Generate code that pushes the value of every element of the given
73678 ** expression list into a sequence of registers beginning at target.
73679 **
73680 ** Return the number of elements evaluated.
73681 */
73682 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
73683   Parse *pParse,     /* Parsing context */
73684   ExprList *pList,   /* The expression list to be coded */
73685   int target,        /* Where to write results */
73686   int doHardCopy     /* Make a hard copy of every element */
73687 ){
73688   struct ExprList_item *pItem;
73689   int i, n;
73690   assert( pList!=0 );
73691   assert( target>0 );
73692   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
73693   n = pList->nExpr;
73694   for(pItem=pList->a, i=0; i<n; i++, pItem++){
73695     Expr *pExpr = pItem->pExpr;
73696     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
73697     if( inReg!=target+i ){
73698       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
73699                         inReg, target+i);
73700     }
73701   }
73702   return n;
73703 }
73704
73705 /*
73706 ** Generate code for a BETWEEN operator.
73707 **
73708 **    x BETWEEN y AND z
73709 **
73710 ** The above is equivalent to 
73711 **
73712 **    x>=y AND x<=z
73713 **
73714 ** Code it as such, taking care to do the common subexpression
73715 ** elementation of x.
73716 */
73717 static void exprCodeBetween(
73718   Parse *pParse,    /* Parsing and code generating context */
73719   Expr *pExpr,      /* The BETWEEN expression */
73720   int dest,         /* Jump here if the jump is taken */
73721   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
73722   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
73723 ){
73724   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
73725   Expr compLeft;    /* The  x>=y  term */
73726   Expr compRight;   /* The  x<=z  term */
73727   Expr exprX;       /* The  x  subexpression */
73728   int regFree1 = 0; /* Temporary use register */
73729
73730   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73731   exprX = *pExpr->pLeft;
73732   exprAnd.op = TK_AND;
73733   exprAnd.pLeft = &compLeft;
73734   exprAnd.pRight = &compRight;
73735   compLeft.op = TK_GE;
73736   compLeft.pLeft = &exprX;
73737   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
73738   compRight.op = TK_LE;
73739   compRight.pLeft = &exprX;
73740   compRight.pRight = pExpr->x.pList->a[1].pExpr;
73741   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
73742   exprX.op = TK_REGISTER;
73743   if( jumpIfTrue ){
73744     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
73745   }else{
73746     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
73747   }
73748   sqlite3ReleaseTempReg(pParse, regFree1);
73749
73750   /* Ensure adequate test coverage */
73751   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
73752   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
73753   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
73754   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
73755   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
73756   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
73757   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
73758   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
73759 }
73760
73761 /*
73762 ** Generate code for a boolean expression such that a jump is made
73763 ** to the label "dest" if the expression is true but execution
73764 ** continues straight thru if the expression is false.
73765 **
73766 ** If the expression evaluates to NULL (neither true nor false), then
73767 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
73768 **
73769 ** This code depends on the fact that certain token values (ex: TK_EQ)
73770 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
73771 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
73772 ** the make process cause these values to align.  Assert()s in the code
73773 ** below verify that the numbers are aligned correctly.
73774 */
73775 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
73776   Vdbe *v = pParse->pVdbe;
73777   int op = 0;
73778   int regFree1 = 0;
73779   int regFree2 = 0;
73780   int r1, r2;
73781
73782   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
73783   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
73784   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
73785   op = pExpr->op;
73786   switch( op ){
73787     case TK_AND: {
73788       int d2 = sqlite3VdbeMakeLabel(v);
73789       testcase( jumpIfNull==0 );
73790       sqlite3ExprCachePush(pParse);
73791       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
73792       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73793       sqlite3VdbeResolveLabel(v, d2);
73794       sqlite3ExprCachePop(pParse, 1);
73795       break;
73796     }
73797     case TK_OR: {
73798       testcase( jumpIfNull==0 );
73799       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
73800       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
73801       break;
73802     }
73803     case TK_NOT: {
73804       testcase( jumpIfNull==0 );
73805       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
73806       break;
73807     }
73808     case TK_LT:
73809     case TK_LE:
73810     case TK_GT:
73811     case TK_GE:
73812     case TK_NE:
73813     case TK_EQ: {
73814       assert( TK_LT==OP_Lt );
73815       assert( TK_LE==OP_Le );
73816       assert( TK_GT==OP_Gt );
73817       assert( TK_GE==OP_Ge );
73818       assert( TK_EQ==OP_Eq );
73819       assert( TK_NE==OP_Ne );
73820       testcase( op==TK_LT );
73821       testcase( op==TK_LE );
73822       testcase( op==TK_GT );
73823       testcase( op==TK_GE );
73824       testcase( op==TK_EQ );
73825       testcase( op==TK_NE );
73826       testcase( jumpIfNull==0 );
73827       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73828       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73829       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73830                   r1, r2, dest, jumpIfNull);
73831       testcase( regFree1==0 );
73832       testcase( regFree2==0 );
73833       break;
73834     }
73835     case TK_IS:
73836     case TK_ISNOT: {
73837       testcase( op==TK_IS );
73838       testcase( op==TK_ISNOT );
73839       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73840       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73841       op = (op==TK_IS) ? TK_EQ : TK_NE;
73842       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73843                   r1, r2, dest, SQLITE_NULLEQ);
73844       testcase( regFree1==0 );
73845       testcase( regFree2==0 );
73846       break;
73847     }
73848     case TK_ISNULL:
73849     case TK_NOTNULL: {
73850       assert( TK_ISNULL==OP_IsNull );
73851       assert( TK_NOTNULL==OP_NotNull );
73852       testcase( op==TK_ISNULL );
73853       testcase( op==TK_NOTNULL );
73854       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73855       sqlite3VdbeAddOp2(v, op, r1, dest);
73856       testcase( regFree1==0 );
73857       break;
73858     }
73859     case TK_BETWEEN: {
73860       testcase( jumpIfNull==0 );
73861       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
73862       break;
73863     }
73864 #ifndef SQLITE_OMIT_SUBQUERY
73865     case TK_IN: {
73866       int destIfFalse = sqlite3VdbeMakeLabel(v);
73867       int destIfNull = jumpIfNull ? dest : destIfFalse;
73868       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73869       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
73870       sqlite3VdbeResolveLabel(v, destIfFalse);
73871       break;
73872     }
73873 #endif
73874     default: {
73875       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
73876       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
73877       testcase( regFree1==0 );
73878       testcase( jumpIfNull==0 );
73879       break;
73880     }
73881   }
73882   sqlite3ReleaseTempReg(pParse, regFree1);
73883   sqlite3ReleaseTempReg(pParse, regFree2);  
73884 }
73885
73886 /*
73887 ** Generate code for a boolean expression such that a jump is made
73888 ** to the label "dest" if the expression is false but execution
73889 ** continues straight thru if the expression is true.
73890 **
73891 ** If the expression evaluates to NULL (neither true nor false) then
73892 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
73893 ** is 0.
73894 */
73895 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
73896   Vdbe *v = pParse->pVdbe;
73897   int op = 0;
73898   int regFree1 = 0;
73899   int regFree2 = 0;
73900   int r1, r2;
73901
73902   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
73903   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
73904   if( pExpr==0 )    return;
73905
73906   /* The value of pExpr->op and op are related as follows:
73907   **
73908   **       pExpr->op            op
73909   **       ---------          ----------
73910   **       TK_ISNULL          OP_NotNull
73911   **       TK_NOTNULL         OP_IsNull
73912   **       TK_NE              OP_Eq
73913   **       TK_EQ              OP_Ne
73914   **       TK_GT              OP_Le
73915   **       TK_LE              OP_Gt
73916   **       TK_GE              OP_Lt
73917   **       TK_LT              OP_Ge
73918   **
73919   ** For other values of pExpr->op, op is undefined and unused.
73920   ** The value of TK_ and OP_ constants are arranged such that we
73921   ** can compute the mapping above using the following expression.
73922   ** Assert()s verify that the computation is correct.
73923   */
73924   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
73925
73926   /* Verify correct alignment of TK_ and OP_ constants
73927   */
73928   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
73929   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
73930   assert( pExpr->op!=TK_NE || op==OP_Eq );
73931   assert( pExpr->op!=TK_EQ || op==OP_Ne );
73932   assert( pExpr->op!=TK_LT || op==OP_Ge );
73933   assert( pExpr->op!=TK_LE || op==OP_Gt );
73934   assert( pExpr->op!=TK_GT || op==OP_Le );
73935   assert( pExpr->op!=TK_GE || op==OP_Lt );
73936
73937   switch( pExpr->op ){
73938     case TK_AND: {
73939       testcase( jumpIfNull==0 );
73940       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
73941       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
73942       break;
73943     }
73944     case TK_OR: {
73945       int d2 = sqlite3VdbeMakeLabel(v);
73946       testcase( jumpIfNull==0 );
73947       sqlite3ExprCachePush(pParse);
73948       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
73949       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
73950       sqlite3VdbeResolveLabel(v, d2);
73951       sqlite3ExprCachePop(pParse, 1);
73952       break;
73953     }
73954     case TK_NOT: {
73955       testcase( jumpIfNull==0 );
73956       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
73957       break;
73958     }
73959     case TK_LT:
73960     case TK_LE:
73961     case TK_GT:
73962     case TK_GE:
73963     case TK_NE:
73964     case TK_EQ: {
73965       testcase( op==TK_LT );
73966       testcase( op==TK_LE );
73967       testcase( op==TK_GT );
73968       testcase( op==TK_GE );
73969       testcase( op==TK_EQ );
73970       testcase( op==TK_NE );
73971       testcase( jumpIfNull==0 );
73972       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73973       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73974       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73975                   r1, r2, dest, jumpIfNull);
73976       testcase( regFree1==0 );
73977       testcase( regFree2==0 );
73978       break;
73979     }
73980     case TK_IS:
73981     case TK_ISNOT: {
73982       testcase( pExpr->op==TK_IS );
73983       testcase( pExpr->op==TK_ISNOT );
73984       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73985       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73986       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
73987       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73988                   r1, r2, dest, SQLITE_NULLEQ);
73989       testcase( regFree1==0 );
73990       testcase( regFree2==0 );
73991       break;
73992     }
73993     case TK_ISNULL:
73994     case TK_NOTNULL: {
73995       testcase( op==TK_ISNULL );
73996       testcase( op==TK_NOTNULL );
73997       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73998       sqlite3VdbeAddOp2(v, op, r1, dest);
73999       testcase( regFree1==0 );
74000       break;
74001     }
74002     case TK_BETWEEN: {
74003       testcase( jumpIfNull==0 );
74004       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
74005       break;
74006     }
74007 #ifndef SQLITE_OMIT_SUBQUERY
74008     case TK_IN: {
74009       if( jumpIfNull ){
74010         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74011       }else{
74012         int destIfNull = sqlite3VdbeMakeLabel(v);
74013         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74014         sqlite3VdbeResolveLabel(v, destIfNull);
74015       }
74016       break;
74017     }
74018 #endif
74019     default: {
74020       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74021       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74022       testcase( regFree1==0 );
74023       testcase( jumpIfNull==0 );
74024       break;
74025     }
74026   }
74027   sqlite3ReleaseTempReg(pParse, regFree1);
74028   sqlite3ReleaseTempReg(pParse, regFree2);
74029 }
74030
74031 /*
74032 ** Do a deep comparison of two expression trees.  Return 0 if the two
74033 ** expressions are completely identical.  Return 1 if they differ only
74034 ** by a COLLATE operator at the top level.  Return 2 if there are differences
74035 ** other than the top-level COLLATE operator.
74036 **
74037 ** Sometimes this routine will return 2 even if the two expressions
74038 ** really are equivalent.  If we cannot prove that the expressions are
74039 ** identical, we return 2 just to be safe.  So if this routine
74040 ** returns 2, then you do not really know for certain if the two
74041 ** expressions are the same.  But if you get a 0 or 1 return, then you
74042 ** can be sure the expressions are the same.  In the places where
74043 ** this routine is used, it does not hurt to get an extra 2 - that
74044 ** just might result in some slightly slower code.  But returning
74045 ** an incorrect 0 or 1 could lead to a malfunction.
74046 */
74047 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74048   if( pA==0||pB==0 ){
74049     return pB==pA ? 0 : 2;
74050   }
74051   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74052   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74053   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74054     return 2;
74055   }
74056   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74057   if( pA->op!=pB->op ) return 2;
74058   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74059   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74060   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74061   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74062   if( ExprHasProperty(pA, EP_IntValue) ){
74063     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74064       return 2;
74065     }
74066   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74067     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74068     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74069       return 2;
74070     }
74071   }
74072   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74073   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74074   return 0;
74075 }
74076
74077 /*
74078 ** Compare two ExprList objects.  Return 0 if they are identical and 
74079 ** non-zero if they differ in any way.
74080 **
74081 ** This routine might return non-zero for equivalent ExprLists.  The
74082 ** only consequence will be disabled optimizations.  But this routine
74083 ** must never return 0 if the two ExprList objects are different, or
74084 ** a malfunction will result.
74085 **
74086 ** Two NULL pointers are considered to be the same.  But a NULL pointer
74087 ** always differs from a non-NULL pointer.
74088 */
74089 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74090   int i;
74091   if( pA==0 && pB==0 ) return 0;
74092   if( pA==0 || pB==0 ) return 1;
74093   if( pA->nExpr!=pB->nExpr ) return 1;
74094   for(i=0; i<pA->nExpr; i++){
74095     Expr *pExprA = pA->a[i].pExpr;
74096     Expr *pExprB = pB->a[i].pExpr;
74097     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74098     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74099   }
74100   return 0;
74101 }
74102
74103 /*
74104 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
74105 ** the new element.  Return a negative number if malloc fails.
74106 */
74107 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74108   int i;
74109   pInfo->aCol = sqlite3ArrayAllocate(
74110        db,
74111        pInfo->aCol,
74112        sizeof(pInfo->aCol[0]),
74113        3,
74114        &pInfo->nColumn,
74115        &pInfo->nColumnAlloc,
74116        &i
74117   );
74118   return i;
74119 }    
74120
74121 /*
74122 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
74123 ** the new element.  Return a negative number if malloc fails.
74124 */
74125 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74126   int i;
74127   pInfo->aFunc = sqlite3ArrayAllocate(
74128        db, 
74129        pInfo->aFunc,
74130        sizeof(pInfo->aFunc[0]),
74131        3,
74132        &pInfo->nFunc,
74133        &pInfo->nFuncAlloc,
74134        &i
74135   );
74136   return i;
74137 }    
74138
74139 /*
74140 ** This is the xExprCallback for a tree walker.  It is used to
74141 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
74142 ** for additional information.
74143 */
74144 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74145   int i;
74146   NameContext *pNC = pWalker->u.pNC;
74147   Parse *pParse = pNC->pParse;
74148   SrcList *pSrcList = pNC->pSrcList;
74149   AggInfo *pAggInfo = pNC->pAggInfo;
74150
74151   switch( pExpr->op ){
74152     case TK_AGG_COLUMN:
74153     case TK_COLUMN: {
74154       testcase( pExpr->op==TK_AGG_COLUMN );
74155       testcase( pExpr->op==TK_COLUMN );
74156       /* Check to see if the column is in one of the tables in the FROM
74157       ** clause of the aggregate query */
74158       if( ALWAYS(pSrcList!=0) ){
74159         struct SrcList_item *pItem = pSrcList->a;
74160         for(i=0; i<pSrcList->nSrc; i++, pItem++){
74161           struct AggInfo_col *pCol;
74162           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74163           if( pExpr->iTable==pItem->iCursor ){
74164             /* If we reach this point, it means that pExpr refers to a table
74165             ** that is in the FROM clause of the aggregate query.  
74166             **
74167             ** Make an entry for the column in pAggInfo->aCol[] if there
74168             ** is not an entry there already.
74169             */
74170             int k;
74171             pCol = pAggInfo->aCol;
74172             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74173               if( pCol->iTable==pExpr->iTable &&
74174                   pCol->iColumn==pExpr->iColumn ){
74175                 break;
74176               }
74177             }
74178             if( (k>=pAggInfo->nColumn)
74179              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
74180             ){
74181               pCol = &pAggInfo->aCol[k];
74182               pCol->pTab = pExpr->pTab;
74183               pCol->iTable = pExpr->iTable;
74184               pCol->iColumn = pExpr->iColumn;
74185               pCol->iMem = ++pParse->nMem;
74186               pCol->iSorterColumn = -1;
74187               pCol->pExpr = pExpr;
74188               if( pAggInfo->pGroupBy ){
74189                 int j, n;
74190                 ExprList *pGB = pAggInfo->pGroupBy;
74191                 struct ExprList_item *pTerm = pGB->a;
74192                 n = pGB->nExpr;
74193                 for(j=0; j<n; j++, pTerm++){
74194                   Expr *pE = pTerm->pExpr;
74195                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74196                       pE->iColumn==pExpr->iColumn ){
74197                     pCol->iSorterColumn = j;
74198                     break;
74199                   }
74200                 }
74201               }
74202               if( pCol->iSorterColumn<0 ){
74203                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74204               }
74205             }
74206             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74207             ** because it was there before or because we just created it).
74208             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74209             ** pAggInfo->aCol[] entry.
74210             */
74211             ExprSetIrreducible(pExpr);
74212             pExpr->pAggInfo = pAggInfo;
74213             pExpr->op = TK_AGG_COLUMN;
74214             pExpr->iAgg = (i16)k;
74215             break;
74216           } /* endif pExpr->iTable==pItem->iCursor */
74217         } /* end loop over pSrcList */
74218       }
74219       return WRC_Prune;
74220     }
74221     case TK_AGG_FUNCTION: {
74222       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74223       ** to be ignored */
74224       if( pNC->nDepth==0 ){
74225         /* Check to see if pExpr is a duplicate of another aggregate 
74226         ** function that is already in the pAggInfo structure
74227         */
74228         struct AggInfo_func *pItem = pAggInfo->aFunc;
74229         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74230           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74231             break;
74232           }
74233         }
74234         if( i>=pAggInfo->nFunc ){
74235           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
74236           */
74237           u8 enc = ENC(pParse->db);
74238           i = addAggInfoFunc(pParse->db, pAggInfo);
74239           if( i>=0 ){
74240             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74241             pItem = &pAggInfo->aFunc[i];
74242             pItem->pExpr = pExpr;
74243             pItem->iMem = ++pParse->nMem;
74244             assert( !ExprHasProperty(pExpr, EP_IntValue) );
74245             pItem->pFunc = sqlite3FindFunction(pParse->db,
74246                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74247                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74248             if( pExpr->flags & EP_Distinct ){
74249               pItem->iDistinct = pParse->nTab++;
74250             }else{
74251               pItem->iDistinct = -1;
74252             }
74253           }
74254         }
74255         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74256         */
74257         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74258         ExprSetIrreducible(pExpr);
74259         pExpr->iAgg = (i16)i;
74260         pExpr->pAggInfo = pAggInfo;
74261         return WRC_Prune;
74262       }
74263     }
74264   }
74265   return WRC_Continue;
74266 }
74267 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74268   NameContext *pNC = pWalker->u.pNC;
74269   if( pNC->nDepth==0 ){
74270     pNC->nDepth++;
74271     sqlite3WalkSelect(pWalker, pSelect);
74272     pNC->nDepth--;
74273     return WRC_Prune;
74274   }else{
74275     return WRC_Continue;
74276   }
74277 }
74278
74279 /*
74280 ** Analyze the given expression looking for aggregate functions and
74281 ** for variables that need to be added to the pParse->aAgg[] array.
74282 ** Make additional entries to the pParse->aAgg[] array as necessary.
74283 **
74284 ** This routine should only be called after the expression has been
74285 ** analyzed by sqlite3ResolveExprNames().
74286 */
74287 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74288   Walker w;
74289   w.xExprCallback = analyzeAggregate;
74290   w.xSelectCallback = analyzeAggregatesInSelect;
74291   w.u.pNC = pNC;
74292   assert( pNC->pSrcList!=0 );
74293   sqlite3WalkExpr(&w, pExpr);
74294 }
74295
74296 /*
74297 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74298 ** expression list.  Return the number of errors.
74299 **
74300 ** If an error is found, the analysis is cut short.
74301 */
74302 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74303   struct ExprList_item *pItem;
74304   int i;
74305   if( pList ){
74306     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74307       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74308     }
74309   }
74310 }
74311
74312 /*
74313 ** Allocate a single new register for use to hold some intermediate result.
74314 */
74315 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74316   if( pParse->nTempReg==0 ){
74317     return ++pParse->nMem;
74318   }
74319   return pParse->aTempReg[--pParse->nTempReg];
74320 }
74321
74322 /*
74323 ** Deallocate a register, making available for reuse for some other
74324 ** purpose.
74325 **
74326 ** If a register is currently being used by the column cache, then
74327 ** the dallocation is deferred until the column cache line that uses
74328 ** the register becomes stale.
74329 */
74330 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74331   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74332     int i;
74333     struct yColCache *p;
74334     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74335       if( p->iReg==iReg ){
74336         p->tempReg = 1;
74337         return;
74338       }
74339     }
74340     pParse->aTempReg[pParse->nTempReg++] = iReg;
74341   }
74342 }
74343
74344 /*
74345 ** Allocate or deallocate a block of nReg consecutive registers
74346 */
74347 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74348   int i, n;
74349   i = pParse->iRangeReg;
74350   n = pParse->nRangeReg;
74351   if( nReg<=n ){
74352     assert( !usedAsColumnCache(pParse, i, i+n-1) );
74353     pParse->iRangeReg += nReg;
74354     pParse->nRangeReg -= nReg;
74355   }else{
74356     i = pParse->nMem+1;
74357     pParse->nMem += nReg;
74358   }
74359   return i;
74360 }
74361 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74362   sqlite3ExprCacheRemove(pParse, iReg, nReg);
74363   if( nReg>pParse->nRangeReg ){
74364     pParse->nRangeReg = nReg;
74365     pParse->iRangeReg = iReg;
74366   }
74367 }
74368
74369 /************** End of expr.c ************************************************/
74370 /************** Begin file alter.c *******************************************/
74371 /*
74372 ** 2005 February 15
74373 **
74374 ** The author disclaims copyright to this source code.  In place of
74375 ** a legal notice, here is a blessing:
74376 **
74377 **    May you do good and not evil.
74378 **    May you find forgiveness for yourself and forgive others.
74379 **    May you share freely, never taking more than you give.
74380 **
74381 *************************************************************************
74382 ** This file contains C code routines that used to generate VDBE code
74383 ** that implements the ALTER TABLE command.
74384 */
74385
74386 /*
74387 ** The code in this file only exists if we are not omitting the
74388 ** ALTER TABLE logic from the build.
74389 */
74390 #ifndef SQLITE_OMIT_ALTERTABLE
74391
74392
74393 /*
74394 ** This function is used by SQL generated to implement the 
74395 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
74396 ** CREATE INDEX command. The second is a table name. The table name in 
74397 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
74398 ** argument and the result returned. Examples:
74399 **
74400 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
74401 **     -> 'CREATE TABLE def(a, b, c)'
74402 **
74403 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
74404 **     -> 'CREATE INDEX i ON def(a, b, c)'
74405 */
74406 static void renameTableFunc(
74407   sqlite3_context *context,
74408   int NotUsed,
74409   sqlite3_value **argv
74410 ){
74411   unsigned char const *zSql = sqlite3_value_text(argv[0]);
74412   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74413
74414   int token;
74415   Token tname;
74416   unsigned char const *zCsr = zSql;
74417   int len = 0;
74418   char *zRet;
74419
74420   sqlite3 *db = sqlite3_context_db_handle(context);
74421
74422   UNUSED_PARAMETER(NotUsed);
74423
74424   /* The principle used to locate the table name in the CREATE TABLE 
74425   ** statement is that the table name is the first non-space token that
74426   ** is immediately followed by a TK_LP or TK_USING token.
74427   */
74428   if( zSql ){
74429     do {
74430       if( !*zCsr ){
74431         /* Ran out of input before finding an opening bracket. Return NULL. */
74432         return;
74433       }
74434
74435       /* Store the token that zCsr points to in tname. */
74436       tname.z = (char*)zCsr;
74437       tname.n = len;
74438
74439       /* Advance zCsr to the next token. Store that token type in 'token',
74440       ** and its length in 'len' (to be used next iteration of this loop).
74441       */
74442       do {
74443         zCsr += len;
74444         len = sqlite3GetToken(zCsr, &token);
74445       } while( token==TK_SPACE );
74446       assert( len>0 );
74447     } while( token!=TK_LP && token!=TK_USING );
74448
74449     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
74450        zTableName, tname.z+tname.n);
74451     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74452   }
74453 }
74454
74455 /*
74456 ** This C function implements an SQL user function that is used by SQL code
74457 ** generated by the ALTER TABLE ... RENAME command to modify the definition
74458 ** of any foreign key constraints that use the table being renamed as the 
74459 ** parent table. It is passed three arguments:
74460 **
74461 **   1) The complete text of the CREATE TABLE statement being modified,
74462 **   2) The old name of the table being renamed, and
74463 **   3) The new name of the table being renamed.
74464 **
74465 ** It returns the new CREATE TABLE statement. For example:
74466 **
74467 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
74468 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
74469 */
74470 #ifndef SQLITE_OMIT_FOREIGN_KEY
74471 static void renameParentFunc(
74472   sqlite3_context *context,
74473   int NotUsed,
74474   sqlite3_value **argv
74475 ){
74476   sqlite3 *db = sqlite3_context_db_handle(context);
74477   char *zOutput = 0;
74478   char *zResult;
74479   unsigned char const *zInput = sqlite3_value_text(argv[0]);
74480   unsigned char const *zOld = sqlite3_value_text(argv[1]);
74481   unsigned char const *zNew = sqlite3_value_text(argv[2]);
74482
74483   unsigned const char *z;         /* Pointer to token */
74484   int n;                          /* Length of token z */
74485   int token;                      /* Type of token */
74486
74487   UNUSED_PARAMETER(NotUsed);
74488   for(z=zInput; *z; z=z+n){
74489     n = sqlite3GetToken(z, &token);
74490     if( token==TK_REFERENCES ){
74491       char *zParent;
74492       do {
74493         z += n;
74494         n = sqlite3GetToken(z, &token);
74495       }while( token==TK_SPACE );
74496
74497       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
74498       if( zParent==0 ) break;
74499       sqlite3Dequote(zParent);
74500       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
74501         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
74502             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
74503         );
74504         sqlite3DbFree(db, zOutput);
74505         zOutput = zOut;
74506         zInput = &z[n];
74507       }
74508       sqlite3DbFree(db, zParent);
74509     }
74510   }
74511
74512   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
74513   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
74514   sqlite3DbFree(db, zOutput);
74515 }
74516 #endif
74517
74518 #ifndef SQLITE_OMIT_TRIGGER
74519 /* This function is used by SQL generated to implement the
74520 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
74521 ** statement. The second is a table name. The table name in the CREATE 
74522 ** TRIGGER statement is replaced with the third argument and the result 
74523 ** returned. This is analagous to renameTableFunc() above, except for CREATE
74524 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
74525 */
74526 static void renameTriggerFunc(
74527   sqlite3_context *context,
74528   int NotUsed,
74529   sqlite3_value **argv
74530 ){
74531   unsigned char const *zSql = sqlite3_value_text(argv[0]);
74532   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74533
74534   int token;
74535   Token tname;
74536   int dist = 3;
74537   unsigned char const *zCsr = zSql;
74538   int len = 0;
74539   char *zRet;
74540   sqlite3 *db = sqlite3_context_db_handle(context);
74541
74542   UNUSED_PARAMETER(NotUsed);
74543
74544   /* The principle used to locate the table name in the CREATE TRIGGER 
74545   ** statement is that the table name is the first token that is immediatedly
74546   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
74547   ** of TK_WHEN, TK_BEGIN or TK_FOR.
74548   */
74549   if( zSql ){
74550     do {
74551
74552       if( !*zCsr ){
74553         /* Ran out of input before finding the table name. Return NULL. */
74554         return;
74555       }
74556
74557       /* Store the token that zCsr points to in tname. */
74558       tname.z = (char*)zCsr;
74559       tname.n = len;
74560
74561       /* Advance zCsr to the next token. Store that token type in 'token',
74562       ** and its length in 'len' (to be used next iteration of this loop).
74563       */
74564       do {
74565         zCsr += len;
74566         len = sqlite3GetToken(zCsr, &token);
74567       }while( token==TK_SPACE );
74568       assert( len>0 );
74569
74570       /* Variable 'dist' stores the number of tokens read since the most
74571       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
74572       ** token is read and 'dist' equals 2, the condition stated above
74573       ** to be met.
74574       **
74575       ** Note that ON cannot be a database, table or column name, so
74576       ** there is no need to worry about syntax like 
74577       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
74578       */
74579       dist++;
74580       if( token==TK_DOT || token==TK_ON ){
74581         dist = 0;
74582       }
74583     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
74584
74585     /* Variable tname now contains the token that is the old table-name
74586     ** in the CREATE TRIGGER statement.
74587     */
74588     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
74589        zTableName, tname.z+tname.n);
74590     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74591   }
74592 }
74593 #endif   /* !SQLITE_OMIT_TRIGGER */
74594
74595 /*
74596 ** Register built-in functions used to help implement ALTER TABLE
74597 */
74598 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
74599   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
74600     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
74601 #ifndef SQLITE_OMIT_TRIGGER
74602     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
74603 #endif
74604 #ifndef SQLITE_OMIT_FOREIGN_KEY
74605     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
74606 #endif
74607   };
74608   int i;
74609   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
74610   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
74611
74612   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
74613     sqlite3FuncDefInsert(pHash, &aFunc[i]);
74614   }
74615 }
74616
74617 /*
74618 ** This function is used to create the text of expressions of the form:
74619 **
74620 **   name=<constant1> OR name=<constant2> OR ...
74621 **
74622 ** If argument zWhere is NULL, then a pointer string containing the text 
74623 ** "name=<constant>" is returned, where <constant> is the quoted version
74624 ** of the string passed as argument zConstant. The returned buffer is
74625 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
74626 ** caller to ensure that it is eventually freed.
74627 **
74628 ** If argument zWhere is not NULL, then the string returned is 
74629 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
74630 ** In this case zWhere is passed to sqlite3DbFree() before returning.
74631 ** 
74632 */
74633 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
74634   char *zNew;
74635   if( !zWhere ){
74636     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
74637   }else{
74638     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
74639     sqlite3DbFree(db, zWhere);
74640   }
74641   return zNew;
74642 }
74643
74644 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74645 /*
74646 ** Generate the text of a WHERE expression which can be used to select all
74647 ** tables that have foreign key constraints that refer to table pTab (i.e.
74648 ** constraints for which pTab is the parent table) from the sqlite_master
74649 ** table.
74650 */
74651 static char *whereForeignKeys(Parse *pParse, Table *pTab){
74652   FKey *p;
74653   char *zWhere = 0;
74654   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74655     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
74656   }
74657   return zWhere;
74658 }
74659 #endif
74660
74661 /*
74662 ** Generate the text of a WHERE expression which can be used to select all
74663 ** temporary triggers on table pTab from the sqlite_temp_master table. If
74664 ** table pTab has no temporary triggers, or is itself stored in the 
74665 ** temporary database, NULL is returned.
74666 */
74667 static char *whereTempTriggers(Parse *pParse, Table *pTab){
74668   Trigger *pTrig;
74669   char *zWhere = 0;
74670   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
74671
74672   /* If the table is not located in the temp-db (in which case NULL is 
74673   ** returned, loop through the tables list of triggers. For each trigger
74674   ** that is not part of the temp-db schema, add a clause to the WHERE 
74675   ** expression being built up in zWhere.
74676   */
74677   if( pTab->pSchema!=pTempSchema ){
74678     sqlite3 *db = pParse->db;
74679     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74680       if( pTrig->pSchema==pTempSchema ){
74681         zWhere = whereOrName(db, zWhere, pTrig->zName);
74682       }
74683     }
74684   }
74685   if( zWhere ){
74686     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
74687     sqlite3DbFree(pParse->db, zWhere);
74688     zWhere = zNew;
74689   }
74690   return zWhere;
74691 }
74692
74693 /*
74694 ** Generate code to drop and reload the internal representation of table
74695 ** pTab from the database, including triggers and temporary triggers.
74696 ** Argument zName is the name of the table in the database schema at
74697 ** the time the generated code is executed. This can be different from
74698 ** pTab->zName if this function is being called to code part of an 
74699 ** "ALTER TABLE RENAME TO" statement.
74700 */
74701 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
74702   Vdbe *v;
74703   char *zWhere;
74704   int iDb;                   /* Index of database containing pTab */
74705 #ifndef SQLITE_OMIT_TRIGGER
74706   Trigger *pTrig;
74707 #endif
74708
74709   v = sqlite3GetVdbe(pParse);
74710   if( NEVER(v==0) ) return;
74711   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74712   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74713   assert( iDb>=0 );
74714
74715 #ifndef SQLITE_OMIT_TRIGGER
74716   /* Drop any table triggers from the internal schema. */
74717   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74718     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
74719     assert( iTrigDb==iDb || iTrigDb==1 );
74720     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
74721   }
74722 #endif
74723
74724   /* Drop the table and index from the internal schema.  */
74725   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74726
74727   /* Reload the table, index and permanent trigger schemas. */
74728   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
74729   if( !zWhere ) return;
74730   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
74731
74732 #ifndef SQLITE_OMIT_TRIGGER
74733   /* Now, if the table is not stored in the temp database, reload any temp 
74734   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
74735   */
74736   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74737     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
74738   }
74739 #endif
74740 }
74741
74742 /*
74743 ** Parameter zName is the name of a table that is about to be altered
74744 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
74745 ** If the table is a system table, this function leaves an error message
74746 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
74747 **
74748 ** Or, if zName is not a system table, zero is returned.
74749 */
74750 static int isSystemTable(Parse *pParse, const char *zName){
74751   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74752     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
74753     return 1;
74754   }
74755   return 0;
74756 }
74757
74758 /*
74759 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
74760 ** command. 
74761 */
74762 SQLITE_PRIVATE void sqlite3AlterRenameTable(
74763   Parse *pParse,            /* Parser context. */
74764   SrcList *pSrc,            /* The table to rename. */
74765   Token *pName              /* The new table name. */
74766 ){
74767   int iDb;                  /* Database that contains the table */
74768   char *zDb;                /* Name of database iDb */
74769   Table *pTab;              /* Table being renamed */
74770   char *zName = 0;          /* NULL-terminated version of pName */ 
74771   sqlite3 *db = pParse->db; /* Database connection */
74772   int nTabName;             /* Number of UTF-8 characters in zTabName */
74773   const char *zTabName;     /* Original name of the table */
74774   Vdbe *v;
74775 #ifndef SQLITE_OMIT_TRIGGER
74776   char *zWhere = 0;         /* Where clause to locate temp triggers */
74777 #endif
74778   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
74779   int savedDbFlags;         /* Saved value of db->flags */
74780
74781   savedDbFlags = db->flags;  
74782   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
74783   assert( pSrc->nSrc==1 );
74784   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
74785
74786   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
74787   if( !pTab ) goto exit_rename_table;
74788   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74789   zDb = db->aDb[iDb].zName;
74790   db->flags |= SQLITE_PreferBuiltin;
74791
74792   /* Get a NULL terminated version of the new table name. */
74793   zName = sqlite3NameFromToken(db, pName);
74794   if( !zName ) goto exit_rename_table;
74795
74796   /* Check that a table or index named 'zName' does not already exist
74797   ** in database iDb. If so, this is an error.
74798   */
74799   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
74800     sqlite3ErrorMsg(pParse, 
74801         "there is already another table or index with this name: %s", zName);
74802     goto exit_rename_table;
74803   }
74804
74805   /* Make sure it is not a system table being altered, or a reserved name
74806   ** that the table is being renamed to.
74807   */
74808   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
74809     goto exit_rename_table;
74810   }
74811   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
74812     exit_rename_table;
74813   }
74814
74815 #ifndef SQLITE_OMIT_VIEW
74816   if( pTab->pSelect ){
74817     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
74818     goto exit_rename_table;
74819   }
74820 #endif
74821
74822 #ifndef SQLITE_OMIT_AUTHORIZATION
74823   /* Invoke the authorization callback. */
74824   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
74825     goto exit_rename_table;
74826   }
74827 #endif
74828
74829 #ifndef SQLITE_OMIT_VIRTUALTABLE
74830   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74831     goto exit_rename_table;
74832   }
74833   if( IsVirtual(pTab) ){
74834     pVTab = sqlite3GetVTable(db, pTab);
74835     if( pVTab->pVtab->pModule->xRename==0 ){
74836       pVTab = 0;
74837     }
74838   }
74839 #endif
74840
74841   /* Begin a transaction and code the VerifyCookie for database iDb. 
74842   ** Then modify the schema cookie (since the ALTER TABLE modifies the
74843   ** schema). Open a statement transaction if the table is a virtual
74844   ** table.
74845   */
74846   v = sqlite3GetVdbe(pParse);
74847   if( v==0 ){
74848     goto exit_rename_table;
74849   }
74850   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
74851   sqlite3ChangeCookie(pParse, iDb);
74852
74853   /* If this is a virtual table, invoke the xRename() function if
74854   ** one is defined. The xRename() callback will modify the names
74855   ** of any resources used by the v-table implementation (including other
74856   ** SQLite tables) that are identified by the name of the virtual table.
74857   */
74858 #ifndef SQLITE_OMIT_VIRTUALTABLE
74859   if( pVTab ){
74860     int i = ++pParse->nMem;
74861     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
74862     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
74863     sqlite3MayAbort(pParse);
74864   }
74865 #endif
74866
74867   /* figure out how many UTF-8 characters are in zName */
74868   zTabName = pTab->zName;
74869   nTabName = sqlite3Utf8CharLen(zTabName, -1);
74870
74871 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74872   if( db->flags&SQLITE_ForeignKeys ){
74873     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
74874     ** statements corresponding to all child tables of foreign key constraints
74875     ** for which the renamed table is the parent table.  */
74876     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
74877       sqlite3NestedParse(pParse, 
74878           "UPDATE \"%w\".%s SET "
74879               "sql = sqlite_rename_parent(sql, %Q, %Q) "
74880               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
74881       sqlite3DbFree(db, zWhere);
74882     }
74883   }
74884 #endif
74885
74886   /* Modify the sqlite_master table to use the new table name. */
74887   sqlite3NestedParse(pParse,
74888       "UPDATE %Q.%s SET "
74889 #ifdef SQLITE_OMIT_TRIGGER
74890           "sql = sqlite_rename_table(sql, %Q), "
74891 #else
74892           "sql = CASE "
74893             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
74894             "ELSE sqlite_rename_table(sql, %Q) END, "
74895 #endif
74896           "tbl_name = %Q, "
74897           "name = CASE "
74898             "WHEN type='table' THEN %Q "
74899             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
74900              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
74901             "ELSE name END "
74902       "WHERE tbl_name=%Q AND "
74903           "(type='table' OR type='index' OR type='trigger');", 
74904       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
74905 #ifndef SQLITE_OMIT_TRIGGER
74906       zName,
74907 #endif
74908       zName, nTabName, zTabName
74909   );
74910
74911 #ifndef SQLITE_OMIT_AUTOINCREMENT
74912   /* If the sqlite_sequence table exists in this database, then update 
74913   ** it with the new table name.
74914   */
74915   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
74916     sqlite3NestedParse(pParse,
74917         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
74918         zDb, zName, pTab->zName);
74919   }
74920 #endif
74921
74922 #ifndef SQLITE_OMIT_TRIGGER
74923   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
74924   ** table. Don't do this if the table being ALTERed is itself located in
74925   ** the temp database.
74926   */
74927   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
74928     sqlite3NestedParse(pParse, 
74929         "UPDATE sqlite_temp_master SET "
74930             "sql = sqlite_rename_trigger(sql, %Q), "
74931             "tbl_name = %Q "
74932             "WHERE %s;", zName, zName, zWhere);
74933     sqlite3DbFree(db, zWhere);
74934   }
74935 #endif
74936
74937 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74938   if( db->flags&SQLITE_ForeignKeys ){
74939     FKey *p;
74940     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74941       Table *pFrom = p->pFrom;
74942       if( pFrom!=pTab ){
74943         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
74944       }
74945     }
74946   }
74947 #endif
74948
74949   /* Drop and reload the internal table schema. */
74950   reloadTableSchema(pParse, pTab, zName);
74951
74952 exit_rename_table:
74953   sqlite3SrcListDelete(db, pSrc);
74954   sqlite3DbFree(db, zName);
74955   db->flags = savedDbFlags;
74956 }
74957
74958
74959 /*
74960 ** Generate code to make sure the file format number is at least minFormat.
74961 ** The generated code will increase the file format number if necessary.
74962 */
74963 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
74964   Vdbe *v;
74965   v = sqlite3GetVdbe(pParse);
74966   /* The VDBE should have been allocated before this routine is called.
74967   ** If that allocation failed, we would have quit before reaching this
74968   ** point */
74969   if( ALWAYS(v) ){
74970     int r1 = sqlite3GetTempReg(pParse);
74971     int r2 = sqlite3GetTempReg(pParse);
74972     int j1;
74973     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
74974     sqlite3VdbeUsesBtree(v, iDb);
74975     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
74976     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
74977     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
74978     sqlite3VdbeJumpHere(v, j1);
74979     sqlite3ReleaseTempReg(pParse, r1);
74980     sqlite3ReleaseTempReg(pParse, r2);
74981   }
74982 }
74983
74984 /*
74985 ** This function is called after an "ALTER TABLE ... ADD" statement
74986 ** has been parsed. Argument pColDef contains the text of the new
74987 ** column definition.
74988 **
74989 ** The Table structure pParse->pNewTable was extended to include
74990 ** the new column during parsing.
74991 */
74992 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
74993   Table *pNew;              /* Copy of pParse->pNewTable */
74994   Table *pTab;              /* Table being altered */
74995   int iDb;                  /* Database number */
74996   const char *zDb;          /* Database name */
74997   const char *zTab;         /* Table name */
74998   char *zCol;               /* Null-terminated column definition */
74999   Column *pCol;             /* The new column */
75000   Expr *pDflt;              /* Default value for the new column */
75001   sqlite3 *db;              /* The database connection; */
75002
75003   db = pParse->db;
75004   if( pParse->nErr || db->mallocFailed ) return;
75005   pNew = pParse->pNewTable;
75006   assert( pNew );
75007
75008   assert( sqlite3BtreeHoldsAllMutexes(db) );
75009   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75010   zDb = db->aDb[iDb].zName;
75011   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
75012   pCol = &pNew->aCol[pNew->nCol-1];
75013   pDflt = pCol->pDflt;
75014   pTab = sqlite3FindTable(db, zTab, zDb);
75015   assert( pTab );
75016
75017 #ifndef SQLITE_OMIT_AUTHORIZATION
75018   /* Invoke the authorization callback. */
75019   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75020     return;
75021   }
75022 #endif
75023
75024   /* If the default value for the new column was specified with a 
75025   ** literal NULL, then set pDflt to 0. This simplifies checking
75026   ** for an SQL NULL default below.
75027   */
75028   if( pDflt && pDflt->op==TK_NULL ){
75029     pDflt = 0;
75030   }
75031
75032   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75033   ** If there is a NOT NULL constraint, then the default value for the
75034   ** column must not be NULL.
75035   */
75036   if( pCol->isPrimKey ){
75037     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75038     return;
75039   }
75040   if( pNew->pIndex ){
75041     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75042     return;
75043   }
75044   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75045     sqlite3ErrorMsg(pParse, 
75046         "Cannot add a REFERENCES column with non-NULL default value");
75047     return;
75048   }
75049   if( pCol->notNull && !pDflt ){
75050     sqlite3ErrorMsg(pParse, 
75051         "Cannot add a NOT NULL column with default value NULL");
75052     return;
75053   }
75054
75055   /* Ensure the default expression is something that sqlite3ValueFromExpr()
75056   ** can handle (i.e. not CURRENT_TIME etc.)
75057   */
75058   if( pDflt ){
75059     sqlite3_value *pVal;
75060     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75061       db->mallocFailed = 1;
75062       return;
75063     }
75064     if( !pVal ){
75065       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75066       return;
75067     }
75068     sqlite3ValueFree(pVal);
75069   }
75070
75071   /* Modify the CREATE TABLE statement. */
75072   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75073   if( zCol ){
75074     char *zEnd = &zCol[pColDef->n-1];
75075     int savedDbFlags = db->flags;
75076     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75077       *zEnd-- = '\0';
75078     }
75079     db->flags |= SQLITE_PreferBuiltin;
75080     sqlite3NestedParse(pParse, 
75081         "UPDATE \"%w\".%s SET "
75082           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75083         "WHERE type = 'table' AND name = %Q", 
75084       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75085       zTab
75086     );
75087     sqlite3DbFree(db, zCol);
75088     db->flags = savedDbFlags;
75089   }
75090
75091   /* If the default value of the new column is NULL, then set the file
75092   ** format to 2. If the default value of the new column is not NULL,
75093   ** the file format becomes 3.
75094   */
75095   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75096
75097   /* Reload the schema of the modified table. */
75098   reloadTableSchema(pParse, pTab, pTab->zName);
75099 }
75100
75101 /*
75102 ** This function is called by the parser after the table-name in
75103 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
75104 ** pSrc is the full-name of the table being altered.
75105 **
75106 ** This routine makes a (partial) copy of the Table structure
75107 ** for the table being altered and sets Parse.pNewTable to point
75108 ** to it. Routines called by the parser as the column definition
75109 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
75110 ** the copy. The copy of the Table structure is deleted by tokenize.c 
75111 ** after parsing is finished.
75112 **
75113 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
75114 ** coding the "ALTER TABLE ... ADD" statement.
75115 */
75116 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75117   Table *pNew;
75118   Table *pTab;
75119   Vdbe *v;
75120   int iDb;
75121   int i;
75122   int nAlloc;
75123   sqlite3 *db = pParse->db;
75124
75125   /* Look up the table being altered. */
75126   assert( pParse->pNewTable==0 );
75127   assert( sqlite3BtreeHoldsAllMutexes(db) );
75128   if( db->mallocFailed ) goto exit_begin_add_column;
75129   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75130   if( !pTab ) goto exit_begin_add_column;
75131
75132 #ifndef SQLITE_OMIT_VIRTUALTABLE
75133   if( IsVirtual(pTab) ){
75134     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75135     goto exit_begin_add_column;
75136   }
75137 #endif
75138
75139   /* Make sure this is not an attempt to ALTER a view. */
75140   if( pTab->pSelect ){
75141     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75142     goto exit_begin_add_column;
75143   }
75144   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75145     goto exit_begin_add_column;
75146   }
75147
75148   assert( pTab->addColOffset>0 );
75149   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75150
75151   /* Put a copy of the Table struct in Parse.pNewTable for the
75152   ** sqlite3AddColumn() function and friends to modify.  But modify
75153   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
75154   ** prefix, we insure that the name will not collide with an existing
75155   ** table because user table are not allowed to have the "sqlite_"
75156   ** prefix on their name.
75157   */
75158   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75159   if( !pNew ) goto exit_begin_add_column;
75160   pParse->pNewTable = pNew;
75161   pNew->nRef = 1;
75162   pNew->nCol = pTab->nCol;
75163   assert( pNew->nCol>0 );
75164   nAlloc = (((pNew->nCol-1)/8)*8)+8;
75165   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75166   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75167   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75168   if( !pNew->aCol || !pNew->zName ){
75169     db->mallocFailed = 1;
75170     goto exit_begin_add_column;
75171   }
75172   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75173   for(i=0; i<pNew->nCol; i++){
75174     Column *pCol = &pNew->aCol[i];
75175     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75176     pCol->zColl = 0;
75177     pCol->zType = 0;
75178     pCol->pDflt = 0;
75179     pCol->zDflt = 0;
75180   }
75181   pNew->pSchema = db->aDb[iDb].pSchema;
75182   pNew->addColOffset = pTab->addColOffset;
75183   pNew->nRef = 1;
75184
75185   /* Begin a transaction and increment the schema cookie.  */
75186   sqlite3BeginWriteOperation(pParse, 0, iDb);
75187   v = sqlite3GetVdbe(pParse);
75188   if( !v ) goto exit_begin_add_column;
75189   sqlite3ChangeCookie(pParse, iDb);
75190
75191 exit_begin_add_column:
75192   sqlite3SrcListDelete(db, pSrc);
75193   return;
75194 }
75195 #endif  /* SQLITE_ALTER_TABLE */
75196
75197 /************** End of alter.c ***********************************************/
75198 /************** Begin file analyze.c *****************************************/
75199 /*
75200 ** 2005 July 8
75201 **
75202 ** The author disclaims copyright to this source code.  In place of
75203 ** a legal notice, here is a blessing:
75204 **
75205 **    May you do good and not evil.
75206 **    May you find forgiveness for yourself and forgive others.
75207 **    May you share freely, never taking more than you give.
75208 **
75209 *************************************************************************
75210 ** This file contains code associated with the ANALYZE command.
75211 */
75212 #ifndef SQLITE_OMIT_ANALYZE
75213
75214 /*
75215 ** This routine generates code that opens the sqlite_stat1 table for
75216 ** writing with cursor iStatCur. If the library was built with the
75217 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75218 ** opened for writing using cursor (iStatCur+1)
75219 **
75220 ** If the sqlite_stat1 tables does not previously exist, it is created.
75221 ** Similarly, if the sqlite_stat2 table does not exist and the library
75222 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
75223 **
75224 ** Argument zWhere may be a pointer to a buffer containing a table name,
75225 ** or it may be a NULL pointer. If it is not NULL, then all entries in
75226 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75227 ** with the named table are deleted. If zWhere==0, then code is generated
75228 ** to delete all stat table entries.
75229 */
75230 static void openStatTable(
75231   Parse *pParse,          /* Parsing context */
75232   int iDb,                /* The database we are looking in */
75233   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
75234   const char *zWhere,     /* Delete entries for this table or index */
75235   const char *zWhereType  /* Either "tbl" or "idx" */
75236 ){
75237   static const struct {
75238     const char *zName;
75239     const char *zCols;
75240   } aTable[] = {
75241     { "sqlite_stat1", "tbl,idx,stat" },
75242 #ifdef SQLITE_ENABLE_STAT2
75243     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75244 #endif
75245   };
75246
75247   int aRoot[] = {0, 0};
75248   u8 aCreateTbl[] = {0, 0};
75249
75250   int i;
75251   sqlite3 *db = pParse->db;
75252   Db *pDb;
75253   Vdbe *v = sqlite3GetVdbe(pParse);
75254   if( v==0 ) return;
75255   assert( sqlite3BtreeHoldsAllMutexes(db) );
75256   assert( sqlite3VdbeDb(v)==db );
75257   pDb = &db->aDb[iDb];
75258
75259   for(i=0; i<ArraySize(aTable); i++){
75260     const char *zTab = aTable[i].zName;
75261     Table *pStat;
75262     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75263       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
75264       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
75265       ** of the new table in register pParse->regRoot. This is important 
75266       ** because the OpenWrite opcode below will be needing it. */
75267       sqlite3NestedParse(pParse,
75268           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75269       );
75270       aRoot[i] = pParse->regRoot;
75271       aCreateTbl[i] = 1;
75272     }else{
75273       /* The table already exists. If zWhere is not NULL, delete all entries 
75274       ** associated with the table zWhere. If zWhere is NULL, delete the
75275       ** entire contents of the table. */
75276       aRoot[i] = pStat->tnum;
75277       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75278       if( zWhere ){
75279         sqlite3NestedParse(pParse,
75280            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75281         );
75282       }else{
75283         /* The sqlite_stat[12] table already exists.  Delete all rows. */
75284         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75285       }
75286     }
75287   }
75288
75289   /* Open the sqlite_stat[12] tables for writing. */
75290   for(i=0; i<ArraySize(aTable); i++){
75291     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75292     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75293     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75294   }
75295 }
75296
75297 /*
75298 ** Generate code to do an analysis of all indices associated with
75299 ** a single table.
75300 */
75301 static void analyzeOneTable(
75302   Parse *pParse,   /* Parser context */
75303   Table *pTab,     /* Table whose indices are to be analyzed */
75304   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75305   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
75306   int iMem         /* Available memory locations begin here */
75307 ){
75308   sqlite3 *db = pParse->db;    /* Database handle */
75309   Index *pIdx;                 /* An index to being analyzed */
75310   int iIdxCur;                 /* Cursor open on index being analyzed */
75311   Vdbe *v;                     /* The virtual machine being built up */
75312   int i;                       /* Loop counter */
75313   int topOfLoop;               /* The top of the loop */
75314   int endOfLoop;               /* The end of the loop */
75315   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
75316   int iDb;                     /* Index of database containing pTab */
75317   int regTabname = iMem++;     /* Register containing table name */
75318   int regIdxname = iMem++;     /* Register containing index name */
75319   int regSampleno = iMem++;    /* Register containing next sample number */
75320   int regCol = iMem++;         /* Content of a column analyzed table */
75321   int regRec = iMem++;         /* Register holding completed record */
75322   int regTemp = iMem++;        /* Temporary use register */
75323   int regRowid = iMem++;       /* Rowid for the inserted record */
75324
75325 #ifdef SQLITE_ENABLE_STAT2
75326   int addr = 0;                /* Instruction address */
75327   int regTemp2 = iMem++;       /* Temporary use register */
75328   int regSamplerecno = iMem++; /* Index of next sample to record */
75329   int regRecno = iMem++;       /* Current sample index */
75330   int regLast = iMem++;        /* Index of last sample to record */
75331   int regFirst = iMem++;       /* Index of first sample to record */
75332 #endif
75333
75334   v = sqlite3GetVdbe(pParse);
75335   if( v==0 || NEVER(pTab==0) ){
75336     return;
75337   }
75338   if( pTab->tnum==0 ){
75339     /* Do not gather statistics on views or virtual tables */
75340     return;
75341   }
75342   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
75343     /* Do not gather statistics on system tables */
75344     return;
75345   }
75346   assert( sqlite3BtreeHoldsAllMutexes(db) );
75347   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75348   assert( iDb>=0 );
75349   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75350 #ifndef SQLITE_OMIT_AUTHORIZATION
75351   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75352       db->aDb[iDb].zName ) ){
75353     return;
75354   }
75355 #endif
75356
75357   /* Establish a read-lock on the table at the shared-cache level. */
75358   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75359
75360   iIdxCur = pParse->nTab++;
75361   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75362   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75363     int nCol;
75364     KeyInfo *pKey;
75365
75366     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75367     nCol = pIdx->nColumn;
75368     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75369     if( iMem+1+(nCol*2)>pParse->nMem ){
75370       pParse->nMem = iMem+1+(nCol*2);
75371     }
75372
75373     /* Open a cursor to the index to be analyzed. */
75374     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75375     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75376         (char *)pKey, P4_KEYINFO_HANDOFF);
75377     VdbeComment((v, "%s", pIdx->zName));
75378
75379     /* Populate the register containing the index name. */
75380     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75381
75382 #ifdef SQLITE_ENABLE_STAT2
75383
75384     /* If this iteration of the loop is generating code to analyze the
75385     ** first index in the pTab->pIndex list, then register regLast has
75386     ** not been populated. In this case populate it now.  */
75387     if( pTab->pIndex==pIdx ){
75388       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75389       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75390       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75391
75392       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
75393       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
75394       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
75395       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
75396       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
75397       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
75398       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
75399       sqlite3VdbeJumpHere(v, addr);
75400     }
75401
75402     /* Zero the regSampleno and regRecno registers. */
75403     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
75404     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
75405     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
75406 #endif
75407
75408     /* The block of memory cells initialized here is used as follows.
75409     **
75410     **    iMem:                
75411     **        The total number of rows in the table.
75412     **
75413     **    iMem+1 .. iMem+nCol: 
75414     **        Number of distinct entries in index considering the 
75415     **        left-most N columns only, where N is between 1 and nCol, 
75416     **        inclusive.
75417     **
75418     **    iMem+nCol+1 .. Mem+2*nCol:  
75419     **        Previous value of indexed columns, from left to right.
75420     **
75421     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
75422     ** initialized to contain an SQL NULL.
75423     */
75424     for(i=0; i<=nCol; i++){
75425       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
75426     }
75427     for(i=0; i<nCol; i++){
75428       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
75429     }
75430
75431     /* Start the analysis loop. This loop runs through all the entries in
75432     ** the index b-tree.  */
75433     endOfLoop = sqlite3VdbeMakeLabel(v);
75434     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
75435     topOfLoop = sqlite3VdbeCurrentAddr(v);
75436     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
75437
75438     for(i=0; i<nCol; i++){
75439       CollSeq *pColl;
75440       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
75441       if( i==0 ){
75442 #ifdef SQLITE_ENABLE_STAT2
75443         /* Check if the record that cursor iIdxCur points to contains a
75444         ** value that should be stored in the sqlite_stat2 table. If so,
75445         ** store it.  */
75446         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
75447         assert( regTabname+1==regIdxname 
75448              && regTabname+2==regSampleno
75449              && regTabname+3==regCol
75450         );
75451         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75452         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
75453         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
75454         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
75455
75456         /* Calculate new values for regSamplerecno and regSampleno.
75457         **
75458         **   sampleno = sampleno + 1
75459         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
75460         */
75461         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
75462         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
75463         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75464         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
75465         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
75466         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
75467         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
75468
75469         sqlite3VdbeJumpHere(v, ne);
75470         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
75471 #endif
75472
75473         /* Always record the very first row */
75474         sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
75475       }
75476       assert( pIdx->azColl!=0 );
75477       assert( pIdx->azColl[i]!=0 );
75478       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
75479       sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
75480                        (char*)pColl, P4_COLLSEQ);
75481       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
75482     }
75483     if( db->mallocFailed ){
75484       /* If a malloc failure has occurred, then the result of the expression 
75485       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
75486       ** below may be negative. Which causes an assert() to fail (or an
75487       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
75488       return;
75489     }
75490     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
75491     for(i=0; i<nCol; i++){
75492       int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
75493       if( i==0 ){
75494         sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
75495       }
75496       sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
75497       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
75498       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
75499     }
75500
75501     /* End of the analysis loop. */
75502     sqlite3VdbeResolveLabel(v, endOfLoop);
75503     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
75504     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75505
75506     /* Store the results in sqlite_stat1.
75507     **
75508     ** The result is a single row of the sqlite_stat1 table.  The first
75509     ** two columns are the names of the table and index.  The third column
75510     ** is a string composed of a list of integer statistics about the
75511     ** index.  The first integer in the list is the total number of entries
75512     ** in the index.  There is one additional integer in the list for each
75513     ** column of the table.  This additional integer is a guess of how many
75514     ** rows of the table the index will select.  If D is the count of distinct
75515     ** values and K is the total number of rows, then the integer is computed
75516     ** as:
75517     **
75518     **        I = (K+D-1)/D
75519     **
75520     ** If K==0 then no entry is made into the sqlite_stat1 table.  
75521     ** If K>0 then it is always the case the D>0 so division by zero
75522     ** is never possible.
75523     */
75524     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
75525     if( jZeroRows<0 ){
75526       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
75527     }
75528     for(i=0; i<nCol; i++){
75529       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
75530       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75531       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
75532       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75533       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
75534       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
75535       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75536     }
75537     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75538     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75539     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75540     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75541   }
75542
75543   /* If the table has no indices, create a single sqlite_stat1 entry
75544   ** containing NULL as the index name and the row count as the content.
75545   */
75546   if( pTab->pIndex==0 ){
75547     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
75548     VdbeComment((v, "%s", pTab->zName));
75549     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
75550     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75551     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
75552   }else{
75553     sqlite3VdbeJumpHere(v, jZeroRows);
75554     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
75555   }
75556   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
75557   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75558   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75559   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75560   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75561   if( pParse->nMem<regRec ) pParse->nMem = regRec;
75562   sqlite3VdbeJumpHere(v, jZeroRows);
75563 }
75564
75565 /*
75566 ** Generate code that will cause the most recent index analysis to
75567 ** be loaded into internal hash tables where is can be used.
75568 */
75569 static void loadAnalysis(Parse *pParse, int iDb){
75570   Vdbe *v = sqlite3GetVdbe(pParse);
75571   if( v ){
75572     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
75573   }
75574 }
75575
75576 /*
75577 ** Generate code that will do an analysis of an entire database
75578 */
75579 static void analyzeDatabase(Parse *pParse, int iDb){
75580   sqlite3 *db = pParse->db;
75581   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
75582   HashElem *k;
75583   int iStatCur;
75584   int iMem;
75585
75586   sqlite3BeginWriteOperation(pParse, 0, iDb);
75587   iStatCur = pParse->nTab;
75588   pParse->nTab += 2;
75589   openStatTable(pParse, iDb, iStatCur, 0, 0);
75590   iMem = pParse->nMem+1;
75591   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75592   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
75593     Table *pTab = (Table*)sqliteHashData(k);
75594     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
75595   }
75596   loadAnalysis(pParse, iDb);
75597 }
75598
75599 /*
75600 ** Generate code that will do an analysis of a single table in
75601 ** a database.  If pOnlyIdx is not NULL then it is a single index
75602 ** in pTab that should be analyzed.
75603 */
75604 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
75605   int iDb;
75606   int iStatCur;
75607
75608   assert( pTab!=0 );
75609   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75610   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75611   sqlite3BeginWriteOperation(pParse, 0, iDb);
75612   iStatCur = pParse->nTab;
75613   pParse->nTab += 2;
75614   if( pOnlyIdx ){
75615     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
75616   }else{
75617     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
75618   }
75619   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
75620   loadAnalysis(pParse, iDb);
75621 }
75622
75623 /*
75624 ** Generate code for the ANALYZE command.  The parser calls this routine
75625 ** when it recognizes an ANALYZE command.
75626 **
75627 **        ANALYZE                            -- 1
75628 **        ANALYZE  <database>                -- 2
75629 **        ANALYZE  ?<database>.?<tablename>  -- 3
75630 **
75631 ** Form 1 causes all indices in all attached databases to be analyzed.
75632 ** Form 2 analyzes all indices the single database named.
75633 ** Form 3 analyzes all indices associated with the named table.
75634 */
75635 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
75636   sqlite3 *db = pParse->db;
75637   int iDb;
75638   int i;
75639   char *z, *zDb;
75640   Table *pTab;
75641   Index *pIdx;
75642   Token *pTableName;
75643
75644   /* Read the database schema. If an error occurs, leave an error message
75645   ** and code in pParse and return NULL. */
75646   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75647   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75648     return;
75649   }
75650
75651   assert( pName2!=0 || pName1==0 );
75652   if( pName1==0 ){
75653     /* Form 1:  Analyze everything */
75654     for(i=0; i<db->nDb; i++){
75655       if( i==1 ) continue;  /* Do not analyze the TEMP database */
75656       analyzeDatabase(pParse, i);
75657     }
75658   }else if( pName2->n==0 ){
75659     /* Form 2:  Analyze the database or table named */
75660     iDb = sqlite3FindDb(db, pName1);
75661     if( iDb>=0 ){
75662       analyzeDatabase(pParse, iDb);
75663     }else{
75664       z = sqlite3NameFromToken(db, pName1);
75665       if( z ){
75666         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
75667           analyzeTable(pParse, pIdx->pTable, pIdx);
75668         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
75669           analyzeTable(pParse, pTab, 0);
75670         }
75671         sqlite3DbFree(db, z);
75672       }
75673     }
75674   }else{
75675     /* Form 3: Analyze the fully qualified table name */
75676     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
75677     if( iDb>=0 ){
75678       zDb = db->aDb[iDb].zName;
75679       z = sqlite3NameFromToken(db, pTableName);
75680       if( z ){
75681         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
75682           analyzeTable(pParse, pIdx->pTable, pIdx);
75683         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
75684           analyzeTable(pParse, pTab, 0);
75685         }
75686         sqlite3DbFree(db, z);
75687       }
75688     }   
75689   }
75690 }
75691
75692 /*
75693 ** Used to pass information from the analyzer reader through to the
75694 ** callback routine.
75695 */
75696 typedef struct analysisInfo analysisInfo;
75697 struct analysisInfo {
75698   sqlite3 *db;
75699   const char *zDatabase;
75700 };
75701
75702 /*
75703 ** This callback is invoked once for each index when reading the
75704 ** sqlite_stat1 table.  
75705 **
75706 **     argv[0] = name of the table
75707 **     argv[1] = name of the index (might be NULL)
75708 **     argv[2] = results of analysis - on integer for each column
75709 **
75710 ** Entries for which argv[1]==NULL simply record the number of rows in
75711 ** the table.
75712 */
75713 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
75714   analysisInfo *pInfo = (analysisInfo*)pData;
75715   Index *pIndex;
75716   Table *pTable;
75717   int i, c, n;
75718   unsigned int v;
75719   const char *z;
75720
75721   assert( argc==3 );
75722   UNUSED_PARAMETER2(NotUsed, argc);
75723
75724   if( argv==0 || argv[0]==0 || argv[2]==0 ){
75725     return 0;
75726   }
75727   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
75728   if( pTable==0 ){
75729     return 0;
75730   }
75731   if( argv[1] ){
75732     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
75733   }else{
75734     pIndex = 0;
75735   }
75736   n = pIndex ? pIndex->nColumn : 0;
75737   z = argv[2];
75738   for(i=0; *z && i<=n; i++){
75739     v = 0;
75740     while( (c=z[0])>='0' && c<='9' ){
75741       v = v*10 + c - '0';
75742       z++;
75743     }
75744     if( i==0 ) pTable->nRowEst = v;
75745     if( pIndex==0 ) break;
75746     pIndex->aiRowEst[i] = v;
75747     if( *z==' ' ) z++;
75748     if( memcmp(z, "unordered", 10)==0 ){
75749       pIndex->bUnordered = 1;
75750       break;
75751     }
75752   }
75753   return 0;
75754 }
75755
75756 /*
75757 ** If the Index.aSample variable is not NULL, delete the aSample[] array
75758 ** and its contents.
75759 */
75760 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
75761 #ifdef SQLITE_ENABLE_STAT2
75762   if( pIdx->aSample ){
75763     int j;
75764     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
75765       IndexSample *p = &pIdx->aSample[j];
75766       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
75767         sqlite3DbFree(db, p->u.z);
75768       }
75769     }
75770     sqlite3DbFree(db, pIdx->aSample);
75771   }
75772 #else
75773   UNUSED_PARAMETER(db);
75774   UNUSED_PARAMETER(pIdx);
75775 #endif
75776 }
75777
75778 /*
75779 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
75780 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
75781 ** arrays. The contents of sqlite_stat2 are used to populate the
75782 ** Index.aSample[] arrays.
75783 **
75784 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
75785 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
75786 ** during compilation and the sqlite_stat2 table is present, no data is 
75787 ** read from it.
75788 **
75789 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
75790 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
75791 ** returned. However, in this case, data is read from the sqlite_stat1
75792 ** table (if it is present) before returning.
75793 **
75794 ** If an OOM error occurs, this function always sets db->mallocFailed.
75795 ** This means if the caller does not care about other errors, the return
75796 ** code may be ignored.
75797 */
75798 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
75799   analysisInfo sInfo;
75800   HashElem *i;
75801   char *zSql;
75802   int rc;
75803
75804   assert( iDb>=0 && iDb<db->nDb );
75805   assert( db->aDb[iDb].pBt!=0 );
75806
75807   /* Clear any prior statistics */
75808   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75809   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
75810     Index *pIdx = sqliteHashData(i);
75811     sqlite3DefaultRowEst(pIdx);
75812     sqlite3DeleteIndexSamples(db, pIdx);
75813     pIdx->aSample = 0;
75814   }
75815
75816   /* Check to make sure the sqlite_stat1 table exists */
75817   sInfo.db = db;
75818   sInfo.zDatabase = db->aDb[iDb].zName;
75819   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
75820     return SQLITE_ERROR;
75821   }
75822
75823   /* Load new statistics out of the sqlite_stat1 table */
75824   zSql = sqlite3MPrintf(db, 
75825       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
75826   if( zSql==0 ){
75827     rc = SQLITE_NOMEM;
75828   }else{
75829     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
75830     sqlite3DbFree(db, zSql);
75831   }
75832
75833
75834   /* Load the statistics from the sqlite_stat2 table. */
75835 #ifdef SQLITE_ENABLE_STAT2
75836   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
75837     rc = SQLITE_ERROR;
75838   }
75839   if( rc==SQLITE_OK ){
75840     sqlite3_stmt *pStmt = 0;
75841
75842     zSql = sqlite3MPrintf(db, 
75843         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
75844     if( !zSql ){
75845       rc = SQLITE_NOMEM;
75846     }else{
75847       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
75848       sqlite3DbFree(db, zSql);
75849     }
75850
75851     if( rc==SQLITE_OK ){
75852       while( sqlite3_step(pStmt)==SQLITE_ROW ){
75853         char *zIndex;   /* Index name */
75854         Index *pIdx;    /* Pointer to the index object */
75855
75856         zIndex = (char *)sqlite3_column_text(pStmt, 0);
75857         pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
75858         if( pIdx ){
75859           int iSample = sqlite3_column_int(pStmt, 1);
75860           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
75861             int eType = sqlite3_column_type(pStmt, 2);
75862
75863             if( pIdx->aSample==0 ){
75864               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
75865               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
75866               if( pIdx->aSample==0 ){
75867                 db->mallocFailed = 1;
75868                 break;
75869               }
75870               memset(pIdx->aSample, 0, sz);
75871             }
75872
75873             assert( pIdx->aSample );
75874             {
75875               IndexSample *pSample = &pIdx->aSample[iSample];
75876               pSample->eType = (u8)eType;
75877               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
75878                 pSample->u.r = sqlite3_column_double(pStmt, 2);
75879               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
75880                 const char *z = (const char *)(
75881                     (eType==SQLITE_BLOB) ?
75882                     sqlite3_column_blob(pStmt, 2):
75883                     sqlite3_column_text(pStmt, 2)
75884                 );
75885                 int n = sqlite3_column_bytes(pStmt, 2);
75886                 if( n>24 ){
75887                   n = 24;
75888                 }
75889                 pSample->nByte = (u8)n;
75890                 if( n < 1){
75891                   pSample->u.z = 0;
75892                 }else{
75893                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
75894                   if( pSample->u.z==0 ){
75895                     db->mallocFailed = 1;
75896                     break;
75897                   }
75898                 }
75899               }
75900             }
75901           }
75902         }
75903       }
75904       rc = sqlite3_finalize(pStmt);
75905     }
75906   }
75907 #endif
75908
75909   if( rc==SQLITE_NOMEM ){
75910     db->mallocFailed = 1;
75911   }
75912   return rc;
75913 }
75914
75915
75916 #endif /* SQLITE_OMIT_ANALYZE */
75917
75918 /************** End of analyze.c *********************************************/
75919 /************** Begin file attach.c ******************************************/
75920 /*
75921 ** 2003 April 6
75922 **
75923 ** The author disclaims copyright to this source code.  In place of
75924 ** a legal notice, here is a blessing:
75925 **
75926 **    May you do good and not evil.
75927 **    May you find forgiveness for yourself and forgive others.
75928 **    May you share freely, never taking more than you give.
75929 **
75930 *************************************************************************
75931 ** This file contains code used to implement the ATTACH and DETACH commands.
75932 */
75933
75934 #ifndef SQLITE_OMIT_ATTACH
75935 /*
75936 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
75937 ** is slightly different from resolving a normal SQL expression, because simple
75938 ** identifiers are treated as strings, not possible column names or aliases.
75939 **
75940 ** i.e. if the parser sees:
75941 **
75942 **     ATTACH DATABASE abc AS def
75943 **
75944 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
75945 ** looking for columns of the same name.
75946 **
75947 ** This only applies to the root node of pExpr, so the statement:
75948 **
75949 **     ATTACH DATABASE abc||def AS 'db2'
75950 **
75951 ** will fail because neither abc or def can be resolved.
75952 */
75953 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
75954 {
75955   int rc = SQLITE_OK;
75956   if( pExpr ){
75957     if( pExpr->op!=TK_ID ){
75958       rc = sqlite3ResolveExprNames(pName, pExpr);
75959       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
75960         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
75961         return SQLITE_ERROR;
75962       }
75963     }else{
75964       pExpr->op = TK_STRING;
75965     }
75966   }
75967   return rc;
75968 }
75969
75970 /*
75971 ** An SQL user-function registered to do the work of an ATTACH statement. The
75972 ** three arguments to the function come directly from an attach statement:
75973 **
75974 **     ATTACH DATABASE x AS y KEY z
75975 **
75976 **     SELECT sqlite_attach(x, y, z)
75977 **
75978 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
75979 ** third argument.
75980 */
75981 static void attachFunc(
75982   sqlite3_context *context,
75983   int NotUsed,
75984   sqlite3_value **argv
75985 ){
75986   int i;
75987   int rc = 0;
75988   sqlite3 *db = sqlite3_context_db_handle(context);
75989   const char *zName;
75990   const char *zFile;
75991   Db *aNew;
75992   char *zErrDyn = 0;
75993
75994   UNUSED_PARAMETER(NotUsed);
75995
75996   zFile = (const char *)sqlite3_value_text(argv[0]);
75997   zName = (const char *)sqlite3_value_text(argv[1]);
75998   if( zFile==0 ) zFile = "";
75999   if( zName==0 ) zName = "";
76000
76001   /* Check for the following errors:
76002   **
76003   **     * Too many attached databases,
76004   **     * Transaction currently open
76005   **     * Specified database name already being used.
76006   */
76007   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
76008     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
76009       db->aLimit[SQLITE_LIMIT_ATTACHED]
76010     );
76011     goto attach_error;
76012   }
76013   if( !db->autoCommit ){
76014     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76015     goto attach_error;
76016   }
76017   for(i=0; i<db->nDb; i++){
76018     char *z = db->aDb[i].zName;
76019     assert( z && zName );
76020     if( sqlite3StrICmp(z, zName)==0 ){
76021       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76022       goto attach_error;
76023     }
76024   }
76025
76026   /* Allocate the new entry in the db->aDb[] array and initialise the schema
76027   ** hash tables.
76028   */
76029   if( db->aDb==db->aDbStatic ){
76030     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76031     if( aNew==0 ) return;
76032     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76033   }else{
76034     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76035     if( aNew==0 ) return;
76036   }
76037   db->aDb = aNew;
76038   aNew = &db->aDb[db->nDb];
76039   memset(aNew, 0, sizeof(*aNew));
76040
76041   /* Open the database file. If the btree is successfully opened, use
76042   ** it to obtain the database schema. At this point the schema may
76043   ** or may not be initialised.
76044   */
76045   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
76046                         db->openFlags | SQLITE_OPEN_MAIN_DB);
76047   db->nDb++;
76048   if( rc==SQLITE_CONSTRAINT ){
76049     rc = SQLITE_ERROR;
76050     zErrDyn = sqlite3MPrintf(db, "database is already attached");
76051   }else if( rc==SQLITE_OK ){
76052     Pager *pPager;
76053     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76054     if( !aNew->pSchema ){
76055       rc = SQLITE_NOMEM;
76056     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76057       zErrDyn = sqlite3MPrintf(db, 
76058         "attached databases must use the same text encoding as main database");
76059       rc = SQLITE_ERROR;
76060     }
76061     pPager = sqlite3BtreePager(aNew->pBt);
76062     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76063     sqlite3BtreeSecureDelete(aNew->pBt,
76064                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76065   }
76066   aNew->safety_level = 3;
76067   aNew->zName = sqlite3DbStrDup(db, zName);
76068   if( rc==SQLITE_OK && aNew->zName==0 ){
76069     rc = SQLITE_NOMEM;
76070   }
76071
76072
76073 #ifdef SQLITE_HAS_CODEC
76074   if( rc==SQLITE_OK ){
76075     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76076     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76077     int nKey;
76078     char *zKey;
76079     int t = sqlite3_value_type(argv[2]);
76080     switch( t ){
76081       case SQLITE_INTEGER:
76082       case SQLITE_FLOAT:
76083         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76084         rc = SQLITE_ERROR;
76085         break;
76086         
76087       case SQLITE_TEXT:
76088       case SQLITE_BLOB:
76089         nKey = sqlite3_value_bytes(argv[2]);
76090         zKey = (char *)sqlite3_value_blob(argv[2]);
76091         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76092         break;
76093
76094       case SQLITE_NULL:
76095         /* No key specified.  Use the key from the main database */
76096         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76097         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76098           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76099         }
76100         break;
76101     }
76102   }
76103 #endif
76104
76105   /* If the file was opened successfully, read the schema for the new database.
76106   ** If this fails, or if opening the file failed, then close the file and 
76107   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76108   ** we found it.
76109   */
76110   if( rc==SQLITE_OK ){
76111     sqlite3BtreeEnterAll(db);
76112     rc = sqlite3Init(db, &zErrDyn);
76113     sqlite3BtreeLeaveAll(db);
76114   }
76115   if( rc ){
76116     int iDb = db->nDb - 1;
76117     assert( iDb>=2 );
76118     if( db->aDb[iDb].pBt ){
76119       sqlite3BtreeClose(db->aDb[iDb].pBt);
76120       db->aDb[iDb].pBt = 0;
76121       db->aDb[iDb].pSchema = 0;
76122     }
76123     sqlite3ResetInternalSchema(db, -1);
76124     db->nDb = iDb;
76125     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76126       db->mallocFailed = 1;
76127       sqlite3DbFree(db, zErrDyn);
76128       zErrDyn = sqlite3MPrintf(db, "out of memory");
76129     }else if( zErrDyn==0 ){
76130       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76131     }
76132     goto attach_error;
76133   }
76134   
76135   return;
76136
76137 attach_error:
76138   /* Return an error if we get here */
76139   if( zErrDyn ){
76140     sqlite3_result_error(context, zErrDyn, -1);
76141     sqlite3DbFree(db, zErrDyn);
76142   }
76143   if( rc ) sqlite3_result_error_code(context, rc);
76144 }
76145
76146 /*
76147 ** An SQL user-function registered to do the work of an DETACH statement. The
76148 ** three arguments to the function come directly from a detach statement:
76149 **
76150 **     DETACH DATABASE x
76151 **
76152 **     SELECT sqlite_detach(x)
76153 */
76154 static void detachFunc(
76155   sqlite3_context *context,
76156   int NotUsed,
76157   sqlite3_value **argv
76158 ){
76159   const char *zName = (const char *)sqlite3_value_text(argv[0]);
76160   sqlite3 *db = sqlite3_context_db_handle(context);
76161   int i;
76162   Db *pDb = 0;
76163   char zErr[128];
76164
76165   UNUSED_PARAMETER(NotUsed);
76166
76167   if( zName==0 ) zName = "";
76168   for(i=0; i<db->nDb; i++){
76169     pDb = &db->aDb[i];
76170     if( pDb->pBt==0 ) continue;
76171     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76172   }
76173
76174   if( i>=db->nDb ){
76175     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76176     goto detach_error;
76177   }
76178   if( i<2 ){
76179     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76180     goto detach_error;
76181   }
76182   if( !db->autoCommit ){
76183     sqlite3_snprintf(sizeof(zErr), zErr,
76184                      "cannot DETACH database within transaction");
76185     goto detach_error;
76186   }
76187   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76188     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76189     goto detach_error;
76190   }
76191
76192   sqlite3BtreeClose(pDb->pBt);
76193   pDb->pBt = 0;
76194   pDb->pSchema = 0;
76195   sqlite3ResetInternalSchema(db, -1);
76196   return;
76197
76198 detach_error:
76199   sqlite3_result_error(context, zErr, -1);
76200 }
76201
76202 /*
76203 ** This procedure generates VDBE code for a single invocation of either the
76204 ** sqlite_detach() or sqlite_attach() SQL user functions.
76205 */
76206 static void codeAttach(
76207   Parse *pParse,       /* The parser context */
76208   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
76209   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76210   Expr *pAuthArg,      /* Expression to pass to authorization callback */
76211   Expr *pFilename,     /* Name of database file */
76212   Expr *pDbname,       /* Name of the database to use internally */
76213   Expr *pKey           /* Database key for encryption extension */
76214 ){
76215   int rc;
76216   NameContext sName;
76217   Vdbe *v;
76218   sqlite3* db = pParse->db;
76219   int regArgs;
76220
76221   memset(&sName, 0, sizeof(NameContext));
76222   sName.pParse = pParse;
76223
76224   if( 
76225       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76226       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76227       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76228   ){
76229     pParse->nErr++;
76230     goto attach_end;
76231   }
76232
76233 #ifndef SQLITE_OMIT_AUTHORIZATION
76234   if( pAuthArg ){
76235     char *zAuthArg;
76236     if( pAuthArg->op==TK_STRING ){
76237       zAuthArg = pAuthArg->u.zToken;
76238     }else{
76239       zAuthArg = 0;
76240     }
76241     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76242     if(rc!=SQLITE_OK ){
76243       goto attach_end;
76244     }
76245   }
76246 #endif /* SQLITE_OMIT_AUTHORIZATION */
76247
76248
76249   v = sqlite3GetVdbe(pParse);
76250   regArgs = sqlite3GetTempRange(pParse, 4);
76251   sqlite3ExprCode(pParse, pFilename, regArgs);
76252   sqlite3ExprCode(pParse, pDbname, regArgs+1);
76253   sqlite3ExprCode(pParse, pKey, regArgs+2);
76254
76255   assert( v || db->mallocFailed );
76256   if( v ){
76257     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76258     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76259     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76260     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76261
76262     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76263     ** statement only). For DETACH, set it to false (expire all existing
76264     ** statements).
76265     */
76266     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76267   }
76268   
76269 attach_end:
76270   sqlite3ExprDelete(db, pFilename);
76271   sqlite3ExprDelete(db, pDbname);
76272   sqlite3ExprDelete(db, pKey);
76273 }
76274
76275 /*
76276 ** Called by the parser to compile a DETACH statement.
76277 **
76278 **     DETACH pDbname
76279 */
76280 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76281   static const FuncDef detach_func = {
76282     1,                /* nArg */
76283     SQLITE_UTF8,      /* iPrefEnc */
76284     0,                /* flags */
76285     0,                /* pUserData */
76286     0,                /* pNext */
76287     detachFunc,       /* xFunc */
76288     0,                /* xStep */
76289     0,                /* xFinalize */
76290     "sqlite_detach",  /* zName */
76291     0,                /* pHash */
76292     0                 /* pDestructor */
76293   };
76294   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76295 }
76296
76297 /*
76298 ** Called by the parser to compile an ATTACH statement.
76299 **
76300 **     ATTACH p AS pDbname KEY pKey
76301 */
76302 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76303   static const FuncDef attach_func = {
76304     3,                /* nArg */
76305     SQLITE_UTF8,      /* iPrefEnc */
76306     0,                /* flags */
76307     0,                /* pUserData */
76308     0,                /* pNext */
76309     attachFunc,       /* xFunc */
76310     0,                /* xStep */
76311     0,                /* xFinalize */
76312     "sqlite_attach",  /* zName */
76313     0,                /* pHash */
76314     0                 /* pDestructor */
76315   };
76316   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76317 }
76318 #endif /* SQLITE_OMIT_ATTACH */
76319
76320 /*
76321 ** Initialize a DbFixer structure.  This routine must be called prior
76322 ** to passing the structure to one of the sqliteFixAAAA() routines below.
76323 **
76324 ** The return value indicates whether or not fixation is required.  TRUE
76325 ** means we do need to fix the database references, FALSE means we do not.
76326 */
76327 SQLITE_PRIVATE int sqlite3FixInit(
76328   DbFixer *pFix,      /* The fixer to be initialized */
76329   Parse *pParse,      /* Error messages will be written here */
76330   int iDb,            /* This is the database that must be used */
76331   const char *zType,  /* "view", "trigger", or "index" */
76332   const Token *pName  /* Name of the view, trigger, or index */
76333 ){
76334   sqlite3 *db;
76335
76336   if( NEVER(iDb<0) || iDb==1 ) return 0;
76337   db = pParse->db;
76338   assert( db->nDb>iDb );
76339   pFix->pParse = pParse;
76340   pFix->zDb = db->aDb[iDb].zName;
76341   pFix->zType = zType;
76342   pFix->pName = pName;
76343   return 1;
76344 }
76345
76346 /*
76347 ** The following set of routines walk through the parse tree and assign
76348 ** a specific database to all table references where the database name
76349 ** was left unspecified in the original SQL statement.  The pFix structure
76350 ** must have been initialized by a prior call to sqlite3FixInit().
76351 **
76352 ** These routines are used to make sure that an index, trigger, or
76353 ** view in one database does not refer to objects in a different database.
76354 ** (Exception: indices, triggers, and views in the TEMP database are
76355 ** allowed to refer to anything.)  If a reference is explicitly made
76356 ** to an object in a different database, an error message is added to
76357 ** pParse->zErrMsg and these routines return non-zero.  If everything
76358 ** checks out, these routines return 0.
76359 */
76360 SQLITE_PRIVATE int sqlite3FixSrcList(
76361   DbFixer *pFix,       /* Context of the fixation */
76362   SrcList *pList       /* The Source list to check and modify */
76363 ){
76364   int i;
76365   const char *zDb;
76366   struct SrcList_item *pItem;
76367
76368   if( NEVER(pList==0) ) return 0;
76369   zDb = pFix->zDb;
76370   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76371     if( pItem->zDatabase==0 ){
76372       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76373     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76374       sqlite3ErrorMsg(pFix->pParse,
76375          "%s %T cannot reference objects in database %s",
76376          pFix->zType, pFix->pName, pItem->zDatabase);
76377       return 1;
76378     }
76379 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76380     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
76381     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
76382 #endif
76383   }
76384   return 0;
76385 }
76386 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76387 SQLITE_PRIVATE int sqlite3FixSelect(
76388   DbFixer *pFix,       /* Context of the fixation */
76389   Select *pSelect      /* The SELECT statement to be fixed to one database */
76390 ){
76391   while( pSelect ){
76392     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
76393       return 1;
76394     }
76395     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
76396       return 1;
76397     }
76398     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
76399       return 1;
76400     }
76401     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
76402       return 1;
76403     }
76404     pSelect = pSelect->pPrior;
76405   }
76406   return 0;
76407 }
76408 SQLITE_PRIVATE int sqlite3FixExpr(
76409   DbFixer *pFix,     /* Context of the fixation */
76410   Expr *pExpr        /* The expression to be fixed to one database */
76411 ){
76412   while( pExpr ){
76413     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
76414     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76415       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
76416     }else{
76417       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
76418     }
76419     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
76420       return 1;
76421     }
76422     pExpr = pExpr->pLeft;
76423   }
76424   return 0;
76425 }
76426 SQLITE_PRIVATE int sqlite3FixExprList(
76427   DbFixer *pFix,     /* Context of the fixation */
76428   ExprList *pList    /* The expression to be fixed to one database */
76429 ){
76430   int i;
76431   struct ExprList_item *pItem;
76432   if( pList==0 ) return 0;
76433   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
76434     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
76435       return 1;
76436     }
76437   }
76438   return 0;
76439 }
76440 #endif
76441
76442 #ifndef SQLITE_OMIT_TRIGGER
76443 SQLITE_PRIVATE int sqlite3FixTriggerStep(
76444   DbFixer *pFix,     /* Context of the fixation */
76445   TriggerStep *pStep /* The trigger step be fixed to one database */
76446 ){
76447   while( pStep ){
76448     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
76449       return 1;
76450     }
76451     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
76452       return 1;
76453     }
76454     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
76455       return 1;
76456     }
76457     pStep = pStep->pNext;
76458   }
76459   return 0;
76460 }
76461 #endif
76462
76463 /************** End of attach.c **********************************************/
76464 /************** Begin file auth.c ********************************************/
76465 /*
76466 ** 2003 January 11
76467 **
76468 ** The author disclaims copyright to this source code.  In place of
76469 ** a legal notice, here is a blessing:
76470 **
76471 **    May you do good and not evil.
76472 **    May you find forgiveness for yourself and forgive others.
76473 **    May you share freely, never taking more than you give.
76474 **
76475 *************************************************************************
76476 ** This file contains code used to implement the sqlite3_set_authorizer()
76477 ** API.  This facility is an optional feature of the library.  Embedded
76478 ** systems that do not need this facility may omit it by recompiling
76479 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
76480 */
76481
76482 /*
76483 ** All of the code in this file may be omitted by defining a single
76484 ** macro.
76485 */
76486 #ifndef SQLITE_OMIT_AUTHORIZATION
76487
76488 /*
76489 ** Set or clear the access authorization function.
76490 **
76491 ** The access authorization function is be called during the compilation
76492 ** phase to verify that the user has read and/or write access permission on
76493 ** various fields of the database.  The first argument to the auth function
76494 ** is a copy of the 3rd argument to this routine.  The second argument
76495 ** to the auth function is one of these constants:
76496 **
76497 **       SQLITE_CREATE_INDEX
76498 **       SQLITE_CREATE_TABLE
76499 **       SQLITE_CREATE_TEMP_INDEX
76500 **       SQLITE_CREATE_TEMP_TABLE
76501 **       SQLITE_CREATE_TEMP_TRIGGER
76502 **       SQLITE_CREATE_TEMP_VIEW
76503 **       SQLITE_CREATE_TRIGGER
76504 **       SQLITE_CREATE_VIEW
76505 **       SQLITE_DELETE
76506 **       SQLITE_DROP_INDEX
76507 **       SQLITE_DROP_TABLE
76508 **       SQLITE_DROP_TEMP_INDEX
76509 **       SQLITE_DROP_TEMP_TABLE
76510 **       SQLITE_DROP_TEMP_TRIGGER
76511 **       SQLITE_DROP_TEMP_VIEW
76512 **       SQLITE_DROP_TRIGGER
76513 **       SQLITE_DROP_VIEW
76514 **       SQLITE_INSERT
76515 **       SQLITE_PRAGMA
76516 **       SQLITE_READ
76517 **       SQLITE_SELECT
76518 **       SQLITE_TRANSACTION
76519 **       SQLITE_UPDATE
76520 **
76521 ** The third and fourth arguments to the auth function are the name of
76522 ** the table and the column that are being accessed.  The auth function
76523 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
76524 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
76525 ** means that the SQL statement will never-run - the sqlite3_exec() call
76526 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
76527 ** should run but attempts to read the specified column will return NULL
76528 ** and attempts to write the column will be ignored.
76529 **
76530 ** Setting the auth function to NULL disables this hook.  The default
76531 ** setting of the auth function is NULL.
76532 */
76533 SQLITE_API int sqlite3_set_authorizer(
76534   sqlite3 *db,
76535   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
76536   void *pArg
76537 ){
76538   sqlite3_mutex_enter(db->mutex);
76539   db->xAuth = xAuth;
76540   db->pAuthArg = pArg;
76541   sqlite3ExpirePreparedStatements(db);
76542   sqlite3_mutex_leave(db->mutex);
76543   return SQLITE_OK;
76544 }
76545
76546 /*
76547 ** Write an error message into pParse->zErrMsg that explains that the
76548 ** user-supplied authorization function returned an illegal value.
76549 */
76550 static void sqliteAuthBadReturnCode(Parse *pParse){
76551   sqlite3ErrorMsg(pParse, "authorizer malfunction");
76552   pParse->rc = SQLITE_ERROR;
76553 }
76554
76555 /*
76556 ** Invoke the authorization callback for permission to read column zCol from
76557 ** table zTab in database zDb. This function assumes that an authorization
76558 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
76559 **
76560 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
76561 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
76562 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
76563 */
76564 SQLITE_PRIVATE int sqlite3AuthReadCol(
76565   Parse *pParse,                  /* The parser context */
76566   const char *zTab,               /* Table name */
76567   const char *zCol,               /* Column name */
76568   int iDb                         /* Index of containing database. */
76569 ){
76570   sqlite3 *db = pParse->db;       /* Database handle */
76571   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
76572   int rc;                         /* Auth callback return code */
76573
76574   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
76575   if( rc==SQLITE_DENY ){
76576     if( db->nDb>2 || iDb!=0 ){
76577       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
76578     }else{
76579       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
76580     }
76581     pParse->rc = SQLITE_AUTH;
76582   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
76583     sqliteAuthBadReturnCode(pParse);
76584   }
76585   return rc;
76586 }
76587
76588 /*
76589 ** The pExpr should be a TK_COLUMN expression.  The table referred to
76590 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
76591 ** Check to see if it is OK to read this particular column.
76592 **
76593 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
76594 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
76595 ** then generate an error.
76596 */
76597 SQLITE_PRIVATE void sqlite3AuthRead(
76598   Parse *pParse,        /* The parser context */
76599   Expr *pExpr,          /* The expression to check authorization on */
76600   Schema *pSchema,      /* The schema of the expression */
76601   SrcList *pTabList     /* All table that pExpr might refer to */
76602 ){
76603   sqlite3 *db = pParse->db;
76604   Table *pTab = 0;      /* The table being read */
76605   const char *zCol;     /* Name of the column of the table */
76606   int iSrc;             /* Index in pTabList->a[] of table being read */
76607   int iDb;              /* The index of the database the expression refers to */
76608   int iCol;             /* Index of column in table */
76609
76610   if( db->xAuth==0 ) return;
76611   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
76612   if( iDb<0 ){
76613     /* An attempt to read a column out of a subquery or other
76614     ** temporary table. */
76615     return;
76616   }
76617
76618   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
76619   if( pExpr->op==TK_TRIGGER ){
76620     pTab = pParse->pTriggerTab;
76621   }else{
76622     assert( pTabList );
76623     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
76624       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
76625         pTab = pTabList->a[iSrc].pTab;
76626         break;
76627       }
76628     }
76629   }
76630   iCol = pExpr->iColumn;
76631   if( NEVER(pTab==0) ) return;
76632
76633   if( iCol>=0 ){
76634     assert( iCol<pTab->nCol );
76635     zCol = pTab->aCol[iCol].zName;
76636   }else if( pTab->iPKey>=0 ){
76637     assert( pTab->iPKey<pTab->nCol );
76638     zCol = pTab->aCol[pTab->iPKey].zName;
76639   }else{
76640     zCol = "ROWID";
76641   }
76642   assert( iDb>=0 && iDb<db->nDb );
76643   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
76644     pExpr->op = TK_NULL;
76645   }
76646 }
76647
76648 /*
76649 ** Do an authorization check using the code and arguments given.  Return
76650 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
76651 ** is returned, then the error count and error message in pParse are
76652 ** modified appropriately.
76653 */
76654 SQLITE_PRIVATE int sqlite3AuthCheck(
76655   Parse *pParse,
76656   int code,
76657   const char *zArg1,
76658   const char *zArg2,
76659   const char *zArg3
76660 ){
76661   sqlite3 *db = pParse->db;
76662   int rc;
76663
76664   /* Don't do any authorization checks if the database is initialising
76665   ** or if the parser is being invoked from within sqlite3_declare_vtab.
76666   */
76667   if( db->init.busy || IN_DECLARE_VTAB ){
76668     return SQLITE_OK;
76669   }
76670
76671   if( db->xAuth==0 ){
76672     return SQLITE_OK;
76673   }
76674   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
76675   if( rc==SQLITE_DENY ){
76676     sqlite3ErrorMsg(pParse, "not authorized");
76677     pParse->rc = SQLITE_AUTH;
76678   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
76679     rc = SQLITE_DENY;
76680     sqliteAuthBadReturnCode(pParse);
76681   }
76682   return rc;
76683 }
76684
76685 /*
76686 ** Push an authorization context.  After this routine is called, the
76687 ** zArg3 argument to authorization callbacks will be zContext until
76688 ** popped.  Or if pParse==0, this routine is a no-op.
76689 */
76690 SQLITE_PRIVATE void sqlite3AuthContextPush(
76691   Parse *pParse,
76692   AuthContext *pContext, 
76693   const char *zContext
76694 ){
76695   assert( pParse );
76696   pContext->pParse = pParse;
76697   pContext->zAuthContext = pParse->zAuthContext;
76698   pParse->zAuthContext = zContext;
76699 }
76700
76701 /*
76702 ** Pop an authorization context that was previously pushed
76703 ** by sqlite3AuthContextPush
76704 */
76705 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
76706   if( pContext->pParse ){
76707     pContext->pParse->zAuthContext = pContext->zAuthContext;
76708     pContext->pParse = 0;
76709   }
76710 }
76711
76712 #endif /* SQLITE_OMIT_AUTHORIZATION */
76713
76714 /************** End of auth.c ************************************************/
76715 /************** Begin file build.c *******************************************/
76716 /*
76717 ** 2001 September 15
76718 **
76719 ** The author disclaims copyright to this source code.  In place of
76720 ** a legal notice, here is a blessing:
76721 **
76722 **    May you do good and not evil.
76723 **    May you find forgiveness for yourself and forgive others.
76724 **    May you share freely, never taking more than you give.
76725 **
76726 *************************************************************************
76727 ** This file contains C code routines that are called by the SQLite parser
76728 ** when syntax rules are reduced.  The routines in this file handle the
76729 ** following kinds of SQL syntax:
76730 **
76731 **     CREATE TABLE
76732 **     DROP TABLE
76733 **     CREATE INDEX
76734 **     DROP INDEX
76735 **     creating ID lists
76736 **     BEGIN TRANSACTION
76737 **     COMMIT
76738 **     ROLLBACK
76739 */
76740
76741 /*
76742 ** This routine is called when a new SQL statement is beginning to
76743 ** be parsed.  Initialize the pParse structure as needed.
76744 */
76745 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
76746   pParse->explain = (u8)explainFlag;
76747   pParse->nVar = 0;
76748 }
76749
76750 #ifndef SQLITE_OMIT_SHARED_CACHE
76751 /*
76752 ** The TableLock structure is only used by the sqlite3TableLock() and
76753 ** codeTableLocks() functions.
76754 */
76755 struct TableLock {
76756   int iDb;             /* The database containing the table to be locked */
76757   int iTab;            /* The root page of the table to be locked */
76758   u8 isWriteLock;      /* True for write lock.  False for a read lock */
76759   const char *zName;   /* Name of the table */
76760 };
76761
76762 /*
76763 ** Record the fact that we want to lock a table at run-time.  
76764 **
76765 ** The table to be locked has root page iTab and is found in database iDb.
76766 ** A read or a write lock can be taken depending on isWritelock.
76767 **
76768 ** This routine just records the fact that the lock is desired.  The
76769 ** code to make the lock occur is generated by a later call to
76770 ** codeTableLocks() which occurs during sqlite3FinishCoding().
76771 */
76772 SQLITE_PRIVATE void sqlite3TableLock(
76773   Parse *pParse,     /* Parsing context */
76774   int iDb,           /* Index of the database containing the table to lock */
76775   int iTab,          /* Root page number of the table to be locked */
76776   u8 isWriteLock,    /* True for a write lock */
76777   const char *zName  /* Name of the table to be locked */
76778 ){
76779   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76780   int i;
76781   int nBytes;
76782   TableLock *p;
76783   assert( iDb>=0 );
76784
76785   for(i=0; i<pToplevel->nTableLock; i++){
76786     p = &pToplevel->aTableLock[i];
76787     if( p->iDb==iDb && p->iTab==iTab ){
76788       p->isWriteLock = (p->isWriteLock || isWriteLock);
76789       return;
76790     }
76791   }
76792
76793   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
76794   pToplevel->aTableLock =
76795       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
76796   if( pToplevel->aTableLock ){
76797     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
76798     p->iDb = iDb;
76799     p->iTab = iTab;
76800     p->isWriteLock = isWriteLock;
76801     p->zName = zName;
76802   }else{
76803     pToplevel->nTableLock = 0;
76804     pToplevel->db->mallocFailed = 1;
76805   }
76806 }
76807
76808 /*
76809 ** Code an OP_TableLock instruction for each table locked by the
76810 ** statement (configured by calls to sqlite3TableLock()).
76811 */
76812 static void codeTableLocks(Parse *pParse){
76813   int i;
76814   Vdbe *pVdbe; 
76815
76816   pVdbe = sqlite3GetVdbe(pParse);
76817   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
76818
76819   for(i=0; i<pParse->nTableLock; i++){
76820     TableLock *p = &pParse->aTableLock[i];
76821     int p1 = p->iDb;
76822     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
76823                       p->zName, P4_STATIC);
76824   }
76825 }
76826 #else
76827   #define codeTableLocks(x)
76828 #endif
76829
76830 /*
76831 ** This routine is called after a single SQL statement has been
76832 ** parsed and a VDBE program to execute that statement has been
76833 ** prepared.  This routine puts the finishing touches on the
76834 ** VDBE program and resets the pParse structure for the next
76835 ** parse.
76836 **
76837 ** Note that if an error occurred, it might be the case that
76838 ** no VDBE code was generated.
76839 */
76840 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
76841   sqlite3 *db;
76842   Vdbe *v;
76843
76844   db = pParse->db;
76845   if( db->mallocFailed ) return;
76846   if( pParse->nested ) return;
76847   if( pParse->nErr ) return;
76848
76849   /* Begin by generating some termination code at the end of the
76850   ** vdbe program
76851   */
76852   v = sqlite3GetVdbe(pParse);
76853   assert( !pParse->isMultiWrite 
76854        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
76855   if( v ){
76856     sqlite3VdbeAddOp0(v, OP_Halt);
76857
76858     /* The cookie mask contains one bit for each database file open.
76859     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
76860     ** set for each database that is used.  Generate code to start a
76861     ** transaction on each used database and to verify the schema cookie
76862     ** on each used database.
76863     */
76864     if( pParse->cookieGoto>0 ){
76865       yDbMask mask;
76866       int iDb;
76867       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
76868       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
76869         if( (mask & pParse->cookieMask)==0 ) continue;
76870         sqlite3VdbeUsesBtree(v, iDb);
76871         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
76872         if( db->init.busy==0 ){
76873           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76874           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
76875                             iDb, pParse->cookieValue[iDb],
76876                             db->aDb[iDb].pSchema->iGeneration);
76877         }
76878       }
76879 #ifndef SQLITE_OMIT_VIRTUALTABLE
76880       {
76881         int i;
76882         for(i=0; i<pParse->nVtabLock; i++){
76883           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
76884           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
76885         }
76886         pParse->nVtabLock = 0;
76887       }
76888 #endif
76889
76890       /* Once all the cookies have been verified and transactions opened, 
76891       ** obtain the required table-locks. This is a no-op unless the 
76892       ** shared-cache feature is enabled.
76893       */
76894       codeTableLocks(pParse);
76895
76896       /* Initialize any AUTOINCREMENT data structures required.
76897       */
76898       sqlite3AutoincrementBegin(pParse);
76899
76900       /* Finally, jump back to the beginning of the executable code. */
76901       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
76902     }
76903   }
76904
76905
76906   /* Get the VDBE program ready for execution
76907   */
76908   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
76909 #ifdef SQLITE_DEBUG
76910     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
76911     sqlite3VdbeTrace(v, trace);
76912 #endif
76913     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
76914     /* A minimum of one cursor is required if autoincrement is used
76915     *  See ticket [a696379c1f08866] */
76916     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
76917     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
76918                          pParse->nTab, pParse->nMaxArg, pParse->explain,
76919                          pParse->isMultiWrite && pParse->mayAbort);
76920     pParse->rc = SQLITE_DONE;
76921     pParse->colNamesSet = 0;
76922   }else{
76923     pParse->rc = SQLITE_ERROR;
76924   }
76925   pParse->nTab = 0;
76926   pParse->nMem = 0;
76927   pParse->nSet = 0;
76928   pParse->nVar = 0;
76929   pParse->cookieMask = 0;
76930   pParse->cookieGoto = 0;
76931 }
76932
76933 /*
76934 ** Run the parser and code generator recursively in order to generate
76935 ** code for the SQL statement given onto the end of the pParse context
76936 ** currently under construction.  When the parser is run recursively
76937 ** this way, the final OP_Halt is not appended and other initialization
76938 ** and finalization steps are omitted because those are handling by the
76939 ** outermost parser.
76940 **
76941 ** Not everything is nestable.  This facility is designed to permit
76942 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
76943 ** care if you decide to try to use this routine for some other purposes.
76944 */
76945 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
76946   va_list ap;
76947   char *zSql;
76948   char *zErrMsg = 0;
76949   sqlite3 *db = pParse->db;
76950 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
76951   char saveBuf[SAVE_SZ];
76952
76953   if( pParse->nErr ) return;
76954   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
76955   va_start(ap, zFormat);
76956   zSql = sqlite3VMPrintf(db, zFormat, ap);
76957   va_end(ap);
76958   if( zSql==0 ){
76959     return;   /* A malloc must have failed */
76960   }
76961   pParse->nested++;
76962   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
76963   memset(&pParse->nVar, 0, SAVE_SZ);
76964   sqlite3RunParser(pParse, zSql, &zErrMsg);
76965   sqlite3DbFree(db, zErrMsg);
76966   sqlite3DbFree(db, zSql);
76967   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
76968   pParse->nested--;
76969 }
76970
76971 /*
76972 ** Locate the in-memory structure that describes a particular database
76973 ** table given the name of that table and (optionally) the name of the
76974 ** database containing the table.  Return NULL if not found.
76975 **
76976 ** If zDatabase is 0, all databases are searched for the table and the
76977 ** first matching table is returned.  (No checking for duplicate table
76978 ** names is done.)  The search order is TEMP first, then MAIN, then any
76979 ** auxiliary databases added using the ATTACH command.
76980 **
76981 ** See also sqlite3LocateTable().
76982 */
76983 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
76984   Table *p = 0;
76985   int i;
76986   int nName;
76987   assert( zName!=0 );
76988   nName = sqlite3Strlen30(zName);
76989   /* All mutexes are required for schema access.  Make sure we hold them. */
76990   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
76991   for(i=OMIT_TEMPDB; i<db->nDb; i++){
76992     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
76993     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
76994     assert( sqlite3SchemaMutexHeld(db, j, 0) );
76995     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
76996     if( p ) break;
76997   }
76998   return p;
76999 }
77000
77001 /*
77002 ** Locate the in-memory structure that describes a particular database
77003 ** table given the name of that table and (optionally) the name of the
77004 ** database containing the table.  Return NULL if not found.  Also leave an
77005 ** error message in pParse->zErrMsg.
77006 **
77007 ** The difference between this routine and sqlite3FindTable() is that this
77008 ** routine leaves an error message in pParse->zErrMsg where
77009 ** sqlite3FindTable() does not.
77010 */
77011 SQLITE_PRIVATE Table *sqlite3LocateTable(
77012   Parse *pParse,         /* context in which to report errors */
77013   int isView,            /* True if looking for a VIEW rather than a TABLE */
77014   const char *zName,     /* Name of the table we are looking for */
77015   const char *zDbase     /* Name of the database.  Might be NULL */
77016 ){
77017   Table *p;
77018
77019   /* Read the database schema. If an error occurs, leave an error message
77020   ** and code in pParse and return NULL. */
77021   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77022     return 0;
77023   }
77024
77025   p = sqlite3FindTable(pParse->db, zName, zDbase);
77026   if( p==0 ){
77027     const char *zMsg = isView ? "no such view" : "no such table";
77028     if( zDbase ){
77029       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77030     }else{
77031       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77032     }
77033     pParse->checkSchema = 1;
77034   }
77035   return p;
77036 }
77037
77038 /*
77039 ** Locate the in-memory structure that describes 
77040 ** a particular index given the name of that index
77041 ** and the name of the database that contains the index.
77042 ** Return NULL if not found.
77043 **
77044 ** If zDatabase is 0, all databases are searched for the
77045 ** table and the first matching index is returned.  (No checking
77046 ** for duplicate index names is done.)  The search order is
77047 ** TEMP first, then MAIN, then any auxiliary databases added
77048 ** using the ATTACH command.
77049 */
77050 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77051   Index *p = 0;
77052   int i;
77053   int nName = sqlite3Strlen30(zName);
77054   /* All mutexes are required for schema access.  Make sure we hold them. */
77055   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77056   for(i=OMIT_TEMPDB; i<db->nDb; i++){
77057     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
77058     Schema *pSchema = db->aDb[j].pSchema;
77059     assert( pSchema );
77060     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77061     assert( sqlite3SchemaMutexHeld(db, j, 0) );
77062     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77063     if( p ) break;
77064   }
77065   return p;
77066 }
77067
77068 /*
77069 ** Reclaim the memory used by an index
77070 */
77071 static void freeIndex(sqlite3 *db, Index *p){
77072 #ifndef SQLITE_OMIT_ANALYZE
77073   sqlite3DeleteIndexSamples(db, p);
77074 #endif
77075   sqlite3DbFree(db, p->zColAff);
77076   sqlite3DbFree(db, p);
77077 }
77078
77079 /*
77080 ** For the index called zIdxName which is found in the database iDb,
77081 ** unlike that index from its Table then remove the index from
77082 ** the index hash table and free all memory structures associated
77083 ** with the index.
77084 */
77085 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77086   Index *pIndex;
77087   int len;
77088   Hash *pHash;
77089
77090   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77091   pHash = &db->aDb[iDb].pSchema->idxHash;
77092   len = sqlite3Strlen30(zIdxName);
77093   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77094   if( ALWAYS(pIndex) ){
77095     if( pIndex->pTable->pIndex==pIndex ){
77096       pIndex->pTable->pIndex = pIndex->pNext;
77097     }else{
77098       Index *p;
77099       /* Justification of ALWAYS();  The index must be on the list of
77100       ** indices. */
77101       p = pIndex->pTable->pIndex;
77102       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77103       if( ALWAYS(p && p->pNext==pIndex) ){
77104         p->pNext = pIndex->pNext;
77105       }
77106     }
77107     freeIndex(db, pIndex);
77108   }
77109   db->flags |= SQLITE_InternChanges;
77110 }
77111
77112 /*
77113 ** Erase all schema information from the in-memory hash tables of
77114 ** a single database.  This routine is called to reclaim memory
77115 ** before the database closes.  It is also called during a rollback
77116 ** if there were schema changes during the transaction or if a
77117 ** schema-cookie mismatch occurs.
77118 **
77119 ** If iDb<0 then reset the internal schema tables for all database
77120 ** files.  If iDb>=0 then reset the internal schema for only the
77121 ** single file indicated.
77122 */
77123 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77124   int i, j;
77125   assert( iDb<db->nDb );
77126
77127   if( iDb>=0 ){
77128     /* Case 1:  Reset the single schema identified by iDb */
77129     Db *pDb = &db->aDb[iDb];
77130     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77131     assert( pDb->pSchema!=0 );
77132     sqlite3SchemaClear(pDb->pSchema);
77133
77134     /* If any database other than TEMP is reset, then also reset TEMP
77135     ** since TEMP might be holding triggers that reference tables in the
77136     ** other database.
77137     */
77138     if( iDb!=1 ){
77139       pDb = &db->aDb[1];
77140       assert( pDb->pSchema!=0 );
77141       sqlite3SchemaClear(pDb->pSchema);
77142     }
77143     return;
77144   }
77145   /* Case 2 (from here to the end): Reset all schemas for all attached
77146   ** databases. */
77147   assert( iDb<0 );
77148   sqlite3BtreeEnterAll(db);
77149   for(i=0; i<db->nDb; i++){
77150     Db *pDb = &db->aDb[i];
77151     if( pDb->pSchema ){
77152       sqlite3SchemaClear(pDb->pSchema);
77153     }
77154   }
77155   db->flags &= ~SQLITE_InternChanges;
77156   sqlite3VtabUnlockList(db);
77157   sqlite3BtreeLeaveAll(db);
77158
77159   /* If one or more of the auxiliary database files has been closed,
77160   ** then remove them from the auxiliary database list.  We take the
77161   ** opportunity to do this here since we have just deleted all of the
77162   ** schema hash tables and therefore do not have to make any changes
77163   ** to any of those tables.
77164   */
77165   for(i=j=2; i<db->nDb; i++){
77166     struct Db *pDb = &db->aDb[i];
77167     if( pDb->pBt==0 ){
77168       sqlite3DbFree(db, pDb->zName);
77169       pDb->zName = 0;
77170       continue;
77171     }
77172     if( j<i ){
77173       db->aDb[j] = db->aDb[i];
77174     }
77175     j++;
77176   }
77177   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77178   db->nDb = j;
77179   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77180     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77181     sqlite3DbFree(db, db->aDb);
77182     db->aDb = db->aDbStatic;
77183   }
77184 }
77185
77186 /*
77187 ** This routine is called when a commit occurs.
77188 */
77189 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77190   db->flags &= ~SQLITE_InternChanges;
77191 }
77192
77193 /*
77194 ** Delete memory allocated for the column names of a table or view (the
77195 ** Table.aCol[] array).
77196 */
77197 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77198   int i;
77199   Column *pCol;
77200   assert( pTable!=0 );
77201   if( (pCol = pTable->aCol)!=0 ){
77202     for(i=0; i<pTable->nCol; i++, pCol++){
77203       sqlite3DbFree(db, pCol->zName);
77204       sqlite3ExprDelete(db, pCol->pDflt);
77205       sqlite3DbFree(db, pCol->zDflt);
77206       sqlite3DbFree(db, pCol->zType);
77207       sqlite3DbFree(db, pCol->zColl);
77208     }
77209     sqlite3DbFree(db, pTable->aCol);
77210   }
77211 }
77212
77213 /*
77214 ** Remove the memory data structures associated with the given
77215 ** Table.  No changes are made to disk by this routine.
77216 **
77217 ** This routine just deletes the data structure.  It does not unlink
77218 ** the table data structure from the hash table.  But it does destroy
77219 ** memory structures of the indices and foreign keys associated with 
77220 ** the table.
77221 */
77222 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77223   Index *pIndex, *pNext;
77224
77225   assert( !pTable || pTable->nRef>0 );
77226
77227   /* Do not delete the table until the reference count reaches zero. */
77228   if( !pTable ) return;
77229   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77230
77231   /* Delete all indices associated with this table. */
77232   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77233     pNext = pIndex->pNext;
77234     assert( pIndex->pSchema==pTable->pSchema );
77235     if( !db || db->pnBytesFreed==0 ){
77236       char *zName = pIndex->zName; 
77237       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77238           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77239       );
77240       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77241       assert( pOld==pIndex || pOld==0 );
77242     }
77243     freeIndex(db, pIndex);
77244   }
77245
77246   /* Delete any foreign keys attached to this table. */
77247   sqlite3FkDelete(db, pTable);
77248
77249   /* Delete the Table structure itself.
77250   */
77251   sqliteDeleteColumnNames(db, pTable);
77252   sqlite3DbFree(db, pTable->zName);
77253   sqlite3DbFree(db, pTable->zColAff);
77254   sqlite3SelectDelete(db, pTable->pSelect);
77255 #ifndef SQLITE_OMIT_CHECK
77256   sqlite3ExprDelete(db, pTable->pCheck);
77257 #endif
77258 #ifndef SQLITE_OMIT_VIRTUALTABLE
77259   sqlite3VtabClear(db, pTable);
77260 #endif
77261   sqlite3DbFree(db, pTable);
77262 }
77263
77264 /*
77265 ** Unlink the given table from the hash tables and the delete the
77266 ** table structure with all its indices and foreign keys.
77267 */
77268 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77269   Table *p;
77270   Db *pDb;
77271
77272   assert( db!=0 );
77273   assert( iDb>=0 && iDb<db->nDb );
77274   assert( zTabName );
77275   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77276   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
77277   pDb = &db->aDb[iDb];
77278   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77279                         sqlite3Strlen30(zTabName),0);
77280   sqlite3DeleteTable(db, p);
77281   db->flags |= SQLITE_InternChanges;
77282 }
77283
77284 /*
77285 ** Given a token, return a string that consists of the text of that
77286 ** token.  Space to hold the returned string
77287 ** is obtained from sqliteMalloc() and must be freed by the calling
77288 ** function.
77289 **
77290 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
77291 ** surround the body of the token are removed.
77292 **
77293 ** Tokens are often just pointers into the original SQL text and so
77294 ** are not \000 terminated and are not persistent.  The returned string
77295 ** is \000 terminated and is persistent.
77296 */
77297 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77298   char *zName;
77299   if( pName ){
77300     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77301     sqlite3Dequote(zName);
77302   }else{
77303     zName = 0;
77304   }
77305   return zName;
77306 }
77307
77308 /*
77309 ** Open the sqlite_master table stored in database number iDb for
77310 ** writing. The table is opened using cursor 0.
77311 */
77312 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77313   Vdbe *v = sqlite3GetVdbe(p);
77314   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77315   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77316   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
77317   if( p->nTab==0 ){
77318     p->nTab = 1;
77319   }
77320 }
77321
77322 /*
77323 ** Parameter zName points to a nul-terminated buffer containing the name
77324 ** of a database ("main", "temp" or the name of an attached db). This
77325 ** function returns the index of the named database in db->aDb[], or
77326 ** -1 if the named db cannot be found.
77327 */
77328 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77329   int i = -1;         /* Database number */
77330   if( zName ){
77331     Db *pDb;
77332     int n = sqlite3Strlen30(zName);
77333     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77334       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
77335           0==sqlite3StrICmp(pDb->zName, zName) ){
77336         break;
77337       }
77338     }
77339   }
77340   return i;
77341 }
77342
77343 /*
77344 ** The token *pName contains the name of a database (either "main" or
77345 ** "temp" or the name of an attached db). This routine returns the
77346 ** index of the named database in db->aDb[], or -1 if the named db 
77347 ** does not exist.
77348 */
77349 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77350   int i;                               /* Database number */
77351   char *zName;                         /* Name we are searching for */
77352   zName = sqlite3NameFromToken(db, pName);
77353   i = sqlite3FindDbName(db, zName);
77354   sqlite3DbFree(db, zName);
77355   return i;
77356 }
77357
77358 /* The table or view or trigger name is passed to this routine via tokens
77359 ** pName1 and pName2. If the table name was fully qualified, for example:
77360 **
77361 ** CREATE TABLE xxx.yyy (...);
77362 ** 
77363 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77364 ** the table name is not fully qualified, i.e.:
77365 **
77366 ** CREATE TABLE yyy(...);
77367 **
77368 ** Then pName1 is set to "yyy" and pName2 is "".
77369 **
77370 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77371 ** pName2) that stores the unqualified table name.  The index of the
77372 ** database "xxx" is returned.
77373 */
77374 SQLITE_PRIVATE int sqlite3TwoPartName(
77375   Parse *pParse,      /* Parsing and code generating context */
77376   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
77377   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
77378   Token **pUnqual     /* Write the unqualified object name here */
77379 ){
77380   int iDb;                    /* Database holding the object */
77381   sqlite3 *db = pParse->db;
77382
77383   if( ALWAYS(pName2!=0) && pName2->n>0 ){
77384     if( db->init.busy ) {
77385       sqlite3ErrorMsg(pParse, "corrupt database");
77386       pParse->nErr++;
77387       return -1;
77388     }
77389     *pUnqual = pName2;
77390     iDb = sqlite3FindDb(db, pName1);
77391     if( iDb<0 ){
77392       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
77393       pParse->nErr++;
77394       return -1;
77395     }
77396   }else{
77397     assert( db->init.iDb==0 || db->init.busy );
77398     iDb = db->init.iDb;
77399     *pUnqual = pName1;
77400   }
77401   return iDb;
77402 }
77403
77404 /*
77405 ** This routine is used to check if the UTF-8 string zName is a legal
77406 ** unqualified name for a new schema object (table, index, view or
77407 ** trigger). All names are legal except those that begin with the string
77408 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
77409 ** is reserved for internal use.
77410 */
77411 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
77412   if( !pParse->db->init.busy && pParse->nested==0 
77413           && (pParse->db->flags & SQLITE_WriteSchema)==0
77414           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77415     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
77416     return SQLITE_ERROR;
77417   }
77418   return SQLITE_OK;
77419 }
77420
77421 /*
77422 ** Begin constructing a new table representation in memory.  This is
77423 ** the first of several action routines that get called in response
77424 ** to a CREATE TABLE statement.  In particular, this routine is called
77425 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
77426 ** flag is true if the table should be stored in the auxiliary database
77427 ** file instead of in the main database file.  This is normally the case
77428 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
77429 ** CREATE and TABLE.
77430 **
77431 ** The new table record is initialized and put in pParse->pNewTable.
77432 ** As more of the CREATE TABLE statement is parsed, additional action
77433 ** routines will be called to add more information to this record.
77434 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
77435 ** is called to complete the construction of the new table record.
77436 */
77437 SQLITE_PRIVATE void sqlite3StartTable(
77438   Parse *pParse,   /* Parser context */
77439   Token *pName1,   /* First part of the name of the table or view */
77440   Token *pName2,   /* Second part of the name of the table or view */
77441   int isTemp,      /* True if this is a TEMP table */
77442   int isView,      /* True if this is a VIEW */
77443   int isVirtual,   /* True if this is a VIRTUAL table */
77444   int noErr        /* Do nothing if table already exists */
77445 ){
77446   Table *pTable;
77447   char *zName = 0; /* The name of the new table */
77448   sqlite3 *db = pParse->db;
77449   Vdbe *v;
77450   int iDb;         /* Database number to create the table in */
77451   Token *pName;    /* Unqualified name of the table to create */
77452
77453   /* The table or view name to create is passed to this routine via tokens
77454   ** pName1 and pName2. If the table name was fully qualified, for example:
77455   **
77456   ** CREATE TABLE xxx.yyy (...);
77457   ** 
77458   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77459   ** the table name is not fully qualified, i.e.:
77460   **
77461   ** CREATE TABLE yyy(...);
77462   **
77463   ** Then pName1 is set to "yyy" and pName2 is "".
77464   **
77465   ** The call below sets the pName pointer to point at the token (pName1 or
77466   ** pName2) that stores the unqualified table name. The variable iDb is
77467   ** set to the index of the database that the table or view is to be
77468   ** created in.
77469   */
77470   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77471   if( iDb<0 ) return;
77472   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
77473     /* If creating a temp table, the name may not be qualified. Unless 
77474     ** the database name is "temp" anyway.  */
77475     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
77476     return;
77477   }
77478   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
77479
77480   pParse->sNameToken = *pName;
77481   zName = sqlite3NameFromToken(db, pName);
77482   if( zName==0 ) return;
77483   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77484     goto begin_table_error;
77485   }
77486   if( db->init.iDb==1 ) isTemp = 1;
77487 #ifndef SQLITE_OMIT_AUTHORIZATION
77488   assert( (isTemp & 1)==isTemp );
77489   {
77490     int code;
77491     char *zDb = db->aDb[iDb].zName;
77492     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
77493       goto begin_table_error;
77494     }
77495     if( isView ){
77496       if( !OMIT_TEMPDB && isTemp ){
77497         code = SQLITE_CREATE_TEMP_VIEW;
77498       }else{
77499         code = SQLITE_CREATE_VIEW;
77500       }
77501     }else{
77502       if( !OMIT_TEMPDB && isTemp ){
77503         code = SQLITE_CREATE_TEMP_TABLE;
77504       }else{
77505         code = SQLITE_CREATE_TABLE;
77506       }
77507     }
77508     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
77509       goto begin_table_error;
77510     }
77511   }
77512 #endif
77513
77514   /* Make sure the new table name does not collide with an existing
77515   ** index or table name in the same database.  Issue an error message if
77516   ** it does. The exception is if the statement being parsed was passed
77517   ** to an sqlite3_declare_vtab() call. In that case only the column names
77518   ** and types will be used, so there is no need to test for namespace
77519   ** collisions.
77520   */
77521   if( !IN_DECLARE_VTAB ){
77522     char *zDb = db->aDb[iDb].zName;
77523     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77524       goto begin_table_error;
77525     }
77526     pTable = sqlite3FindTable(db, zName, zDb);
77527     if( pTable ){
77528       if( !noErr ){
77529         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
77530       }else{
77531         assert( !db->init.busy );
77532         sqlite3CodeVerifySchema(pParse, iDb);
77533       }
77534       goto begin_table_error;
77535     }
77536     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
77537       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
77538       goto begin_table_error;
77539     }
77540   }
77541
77542   pTable = sqlite3DbMallocZero(db, sizeof(Table));
77543   if( pTable==0 ){
77544     db->mallocFailed = 1;
77545     pParse->rc = SQLITE_NOMEM;
77546     pParse->nErr++;
77547     goto begin_table_error;
77548   }
77549   pTable->zName = zName;
77550   pTable->iPKey = -1;
77551   pTable->pSchema = db->aDb[iDb].pSchema;
77552   pTable->nRef = 1;
77553   pTable->nRowEst = 1000000;
77554   assert( pParse->pNewTable==0 );
77555   pParse->pNewTable = pTable;
77556
77557   /* If this is the magic sqlite_sequence table used by autoincrement,
77558   ** then record a pointer to this table in the main database structure
77559   ** so that INSERT can find the table easily.
77560   */
77561 #ifndef SQLITE_OMIT_AUTOINCREMENT
77562   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
77563     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77564     pTable->pSchema->pSeqTab = pTable;
77565   }
77566 #endif
77567
77568   /* Begin generating the code that will insert the table record into
77569   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
77570   ** and allocate the record number for the table entry now.  Before any
77571   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
77572   ** indices to be created and the table record must come before the 
77573   ** indices.  Hence, the record number for the table must be allocated
77574   ** now.
77575   */
77576   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
77577     int j1;
77578     int fileFormat;
77579     int reg1, reg2, reg3;
77580     sqlite3BeginWriteOperation(pParse, 0, iDb);
77581
77582 #ifndef SQLITE_OMIT_VIRTUALTABLE
77583     if( isVirtual ){
77584       sqlite3VdbeAddOp0(v, OP_VBegin);
77585     }
77586 #endif
77587
77588     /* If the file format and encoding in the database have not been set, 
77589     ** set them now.
77590     */
77591     reg1 = pParse->regRowid = ++pParse->nMem;
77592     reg2 = pParse->regRoot = ++pParse->nMem;
77593     reg3 = ++pParse->nMem;
77594     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
77595     sqlite3VdbeUsesBtree(v, iDb);
77596     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
77597     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
77598                   1 : SQLITE_MAX_FILE_FORMAT;
77599     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
77600     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
77601     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
77602     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
77603     sqlite3VdbeJumpHere(v, j1);
77604
77605     /* This just creates a place-holder record in the sqlite_master table.
77606     ** The record created does not contain anything yet.  It will be replaced
77607     ** by the real entry in code generated at sqlite3EndTable().
77608     **
77609     ** The rowid for the new entry is left in register pParse->regRowid.
77610     ** The root page number of the new table is left in reg pParse->regRoot.
77611     ** The rowid and root page number values are needed by the code that
77612     ** sqlite3EndTable will generate.
77613     */
77614 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
77615     if( isView || isVirtual ){
77616       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
77617     }else
77618 #endif
77619     {
77620       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
77621     }
77622     sqlite3OpenMasterTable(pParse, iDb);
77623     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
77624     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
77625     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
77626     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77627     sqlite3VdbeAddOp0(v, OP_Close);
77628   }
77629
77630   /* Normal (non-error) return. */
77631   return;
77632
77633   /* If an error occurs, we jump here */
77634 begin_table_error:
77635   sqlite3DbFree(db, zName);
77636   return;
77637 }
77638
77639 /*
77640 ** This macro is used to compare two strings in a case-insensitive manner.
77641 ** It is slightly faster than calling sqlite3StrICmp() directly, but
77642 ** produces larger code.
77643 **
77644 ** WARNING: This macro is not compatible with the strcmp() family. It
77645 ** returns true if the two strings are equal, otherwise false.
77646 */
77647 #define STRICMP(x, y) (\
77648 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
77649 sqlite3UpperToLower[*(unsigned char *)(y)]     \
77650 && sqlite3StrICmp((x)+1,(y)+1)==0 )
77651
77652 /*
77653 ** Add a new column to the table currently being constructed.
77654 **
77655 ** The parser calls this routine once for each column declaration
77656 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
77657 ** first to get things going.  Then this routine is called for each
77658 ** column.
77659 */
77660 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
77661   Table *p;
77662   int i;
77663   char *z;
77664   Column *pCol;
77665   sqlite3 *db = pParse->db;
77666   if( (p = pParse->pNewTable)==0 ) return;
77667 #if SQLITE_MAX_COLUMN
77668   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77669     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
77670     return;
77671   }
77672 #endif
77673   z = sqlite3NameFromToken(db, pName);
77674   if( z==0 ) return;
77675   for(i=0; i<p->nCol; i++){
77676     if( STRICMP(z, p->aCol[i].zName) ){
77677       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
77678       sqlite3DbFree(db, z);
77679       return;
77680     }
77681   }
77682   if( (p->nCol & 0x7)==0 ){
77683     Column *aNew;
77684     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
77685     if( aNew==0 ){
77686       sqlite3DbFree(db, z);
77687       return;
77688     }
77689     p->aCol = aNew;
77690   }
77691   pCol = &p->aCol[p->nCol];
77692   memset(pCol, 0, sizeof(p->aCol[0]));
77693   pCol->zName = z;
77694  
77695   /* If there is no type specified, columns have the default affinity
77696   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
77697   ** be called next to set pCol->affinity correctly.
77698   */
77699   pCol->affinity = SQLITE_AFF_NONE;
77700   p->nCol++;
77701 }
77702
77703 /*
77704 ** This routine is called by the parser while in the middle of
77705 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
77706 ** been seen on a column.  This routine sets the notNull flag on
77707 ** the column currently under construction.
77708 */
77709 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
77710   Table *p;
77711   p = pParse->pNewTable;
77712   if( p==0 || NEVER(p->nCol<1) ) return;
77713   p->aCol[p->nCol-1].notNull = (u8)onError;
77714 }
77715
77716 /*
77717 ** Scan the column type name zType (length nType) and return the
77718 ** associated affinity type.
77719 **
77720 ** This routine does a case-independent search of zType for the 
77721 ** substrings in the following table. If one of the substrings is
77722 ** found, the corresponding affinity is returned. If zType contains
77723 ** more than one of the substrings, entries toward the top of 
77724 ** the table take priority. For example, if zType is 'BLOBINT', 
77725 ** SQLITE_AFF_INTEGER is returned.
77726 **
77727 ** Substring     | Affinity
77728 ** --------------------------------
77729 ** 'INT'         | SQLITE_AFF_INTEGER
77730 ** 'CHAR'        | SQLITE_AFF_TEXT
77731 ** 'CLOB'        | SQLITE_AFF_TEXT
77732 ** 'TEXT'        | SQLITE_AFF_TEXT
77733 ** 'BLOB'        | SQLITE_AFF_NONE
77734 ** 'REAL'        | SQLITE_AFF_REAL
77735 ** 'FLOA'        | SQLITE_AFF_REAL
77736 ** 'DOUB'        | SQLITE_AFF_REAL
77737 **
77738 ** If none of the substrings in the above table are found,
77739 ** SQLITE_AFF_NUMERIC is returned.
77740 */
77741 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
77742   u32 h = 0;
77743   char aff = SQLITE_AFF_NUMERIC;
77744
77745   if( zIn ) while( zIn[0] ){
77746     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
77747     zIn++;
77748     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
77749       aff = SQLITE_AFF_TEXT; 
77750     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
77751       aff = SQLITE_AFF_TEXT;
77752     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
77753       aff = SQLITE_AFF_TEXT;
77754     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
77755         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
77756       aff = SQLITE_AFF_NONE;
77757 #ifndef SQLITE_OMIT_FLOATING_POINT
77758     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
77759         && aff==SQLITE_AFF_NUMERIC ){
77760       aff = SQLITE_AFF_REAL;
77761     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
77762         && aff==SQLITE_AFF_NUMERIC ){
77763       aff = SQLITE_AFF_REAL;
77764     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
77765         && aff==SQLITE_AFF_NUMERIC ){
77766       aff = SQLITE_AFF_REAL;
77767 #endif
77768     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
77769       aff = SQLITE_AFF_INTEGER;
77770       break;
77771     }
77772   }
77773
77774   return aff;
77775 }
77776
77777 /*
77778 ** This routine is called by the parser while in the middle of
77779 ** parsing a CREATE TABLE statement.  The pFirst token is the first
77780 ** token in the sequence of tokens that describe the type of the
77781 ** column currently under construction.   pLast is the last token
77782 ** in the sequence.  Use this information to construct a string
77783 ** that contains the typename of the column and store that string
77784 ** in zType.
77785 */ 
77786 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
77787   Table *p;
77788   Column *pCol;
77789
77790   p = pParse->pNewTable;
77791   if( p==0 || NEVER(p->nCol<1) ) return;
77792   pCol = &p->aCol[p->nCol-1];
77793   assert( pCol->zType==0 );
77794   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
77795   pCol->affinity = sqlite3AffinityType(pCol->zType);
77796 }
77797
77798 /*
77799 ** The expression is the default value for the most recently added column
77800 ** of the table currently under construction.
77801 **
77802 ** Default value expressions must be constant.  Raise an exception if this
77803 ** is not the case.
77804 **
77805 ** This routine is called by the parser while in the middle of
77806 ** parsing a CREATE TABLE statement.
77807 */
77808 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
77809   Table *p;
77810   Column *pCol;
77811   sqlite3 *db = pParse->db;
77812   p = pParse->pNewTable;
77813   if( p!=0 ){
77814     pCol = &(p->aCol[p->nCol-1]);
77815     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
77816       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
77817           pCol->zName);
77818     }else{
77819       /* A copy of pExpr is used instead of the original, as pExpr contains
77820       ** tokens that point to volatile memory. The 'span' of the expression
77821       ** is required by pragma table_info.
77822       */
77823       sqlite3ExprDelete(db, pCol->pDflt);
77824       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
77825       sqlite3DbFree(db, pCol->zDflt);
77826       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
77827                                      (int)(pSpan->zEnd - pSpan->zStart));
77828     }
77829   }
77830   sqlite3ExprDelete(db, pSpan->pExpr);
77831 }
77832
77833 /*
77834 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
77835 ** of columns that form the primary key.  If pList is NULL, then the
77836 ** most recently added column of the table is the primary key.
77837 **
77838 ** A table can have at most one primary key.  If the table already has
77839 ** a primary key (and this is the second primary key) then create an
77840 ** error.
77841 **
77842 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
77843 ** then we will try to use that column as the rowid.  Set the Table.iPKey
77844 ** field of the table under construction to be the index of the
77845 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
77846 ** no INTEGER PRIMARY KEY.
77847 **
77848 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
77849 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
77850 */
77851 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
77852   Parse *pParse,    /* Parsing context */
77853   ExprList *pList,  /* List of field names to be indexed */
77854   int onError,      /* What to do with a uniqueness conflict */
77855   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
77856   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
77857 ){
77858   Table *pTab = pParse->pNewTable;
77859   char *zType = 0;
77860   int iCol = -1, i;
77861   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
77862   if( pTab->tabFlags & TF_HasPrimaryKey ){
77863     sqlite3ErrorMsg(pParse, 
77864       "table \"%s\" has more than one primary key", pTab->zName);
77865     goto primary_key_exit;
77866   }
77867   pTab->tabFlags |= TF_HasPrimaryKey;
77868   if( pList==0 ){
77869     iCol = pTab->nCol - 1;
77870     pTab->aCol[iCol].isPrimKey = 1;
77871   }else{
77872     for(i=0; i<pList->nExpr; i++){
77873       for(iCol=0; iCol<pTab->nCol; iCol++){
77874         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
77875           break;
77876         }
77877       }
77878       if( iCol<pTab->nCol ){
77879         pTab->aCol[iCol].isPrimKey = 1;
77880       }
77881     }
77882     if( pList->nExpr>1 ) iCol = -1;
77883   }
77884   if( iCol>=0 && iCol<pTab->nCol ){
77885     zType = pTab->aCol[iCol].zType;
77886   }
77887   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
77888         && sortOrder==SQLITE_SO_ASC ){
77889     pTab->iPKey = iCol;
77890     pTab->keyConf = (u8)onError;
77891     assert( autoInc==0 || autoInc==1 );
77892     pTab->tabFlags |= autoInc*TF_Autoincrement;
77893   }else if( autoInc ){
77894 #ifndef SQLITE_OMIT_AUTOINCREMENT
77895     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
77896        "INTEGER PRIMARY KEY");
77897 #endif
77898   }else{
77899     Index *p;
77900     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
77901     if( p ){
77902       p->autoIndex = 2;
77903     }
77904     pList = 0;
77905   }
77906
77907 primary_key_exit:
77908   sqlite3ExprListDelete(pParse->db, pList);
77909   return;
77910 }
77911
77912 /*
77913 ** Add a new CHECK constraint to the table currently under construction.
77914 */
77915 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
77916   Parse *pParse,    /* Parsing context */
77917   Expr *pCheckExpr  /* The check expression */
77918 ){
77919   sqlite3 *db = pParse->db;
77920 #ifndef SQLITE_OMIT_CHECK
77921   Table *pTab = pParse->pNewTable;
77922   if( pTab && !IN_DECLARE_VTAB ){
77923     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
77924   }else
77925 #endif
77926   {
77927     sqlite3ExprDelete(db, pCheckExpr);
77928   }
77929 }
77930
77931 /*
77932 ** Set the collation function of the most recently parsed table column
77933 ** to the CollSeq given.
77934 */
77935 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
77936   Table *p;
77937   int i;
77938   char *zColl;              /* Dequoted name of collation sequence */
77939   sqlite3 *db;
77940
77941   if( (p = pParse->pNewTable)==0 ) return;
77942   i = p->nCol-1;
77943   db = pParse->db;
77944   zColl = sqlite3NameFromToken(db, pToken);
77945   if( !zColl ) return;
77946
77947   if( sqlite3LocateCollSeq(pParse, zColl) ){
77948     Index *pIdx;
77949     p->aCol[i].zColl = zColl;
77950   
77951     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
77952     ** then an index may have been created on this column before the
77953     ** collation type was added. Correct this if it is the case.
77954     */
77955     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
77956       assert( pIdx->nColumn==1 );
77957       if( pIdx->aiColumn[0]==i ){
77958         pIdx->azColl[0] = p->aCol[i].zColl;
77959       }
77960     }
77961   }else{
77962     sqlite3DbFree(db, zColl);
77963   }
77964 }
77965
77966 /*
77967 ** This function returns the collation sequence for database native text
77968 ** encoding identified by the string zName, length nName.
77969 **
77970 ** If the requested collation sequence is not available, or not available
77971 ** in the database native encoding, the collation factory is invoked to
77972 ** request it. If the collation factory does not supply such a sequence,
77973 ** and the sequence is available in another text encoding, then that is
77974 ** returned instead.
77975 **
77976 ** If no versions of the requested collations sequence are available, or
77977 ** another error occurs, NULL is returned and an error message written into
77978 ** pParse.
77979 **
77980 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
77981 ** invokes the collation factory if the named collation cannot be found
77982 ** and generates an error message.
77983 **
77984 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
77985 */
77986 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
77987   sqlite3 *db = pParse->db;
77988   u8 enc = ENC(db);
77989   u8 initbusy = db->init.busy;
77990   CollSeq *pColl;
77991
77992   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
77993   if( !initbusy && (!pColl || !pColl->xCmp) ){
77994     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
77995     if( !pColl ){
77996       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
77997     }
77998   }
77999
78000   return pColl;
78001 }
78002
78003
78004 /*
78005 ** Generate code that will increment the schema cookie.
78006 **
78007 ** The schema cookie is used to determine when the schema for the
78008 ** database changes.  After each schema change, the cookie value
78009 ** changes.  When a process first reads the schema it records the
78010 ** cookie.  Thereafter, whenever it goes to access the database,
78011 ** it checks the cookie to make sure the schema has not changed
78012 ** since it was last read.
78013 **
78014 ** This plan is not completely bullet-proof.  It is possible for
78015 ** the schema to change multiple times and for the cookie to be
78016 ** set back to prior value.  But schema changes are infrequent
78017 ** and the probability of hitting the same cookie value is only
78018 ** 1 chance in 2^32.  So we're safe enough.
78019 */
78020 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78021   int r1 = sqlite3GetTempReg(pParse);
78022   sqlite3 *db = pParse->db;
78023   Vdbe *v = pParse->pVdbe;
78024   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78025   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78026   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78027   sqlite3ReleaseTempReg(pParse, r1);
78028 }
78029
78030 /*
78031 ** Measure the number of characters needed to output the given
78032 ** identifier.  The number returned includes any quotes used
78033 ** but does not include the null terminator.
78034 **
78035 ** The estimate is conservative.  It might be larger that what is
78036 ** really needed.
78037 */
78038 static int identLength(const char *z){
78039   int n;
78040   for(n=0; *z; n++, z++){
78041     if( *z=='"' ){ n++; }
78042   }
78043   return n + 2;
78044 }
78045
78046 /*
78047 ** The first parameter is a pointer to an output buffer. The second 
78048 ** parameter is a pointer to an integer that contains the offset at
78049 ** which to write into the output buffer. This function copies the
78050 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
78051 ** to the specified offset in the buffer and updates *pIdx to refer
78052 ** to the first byte after the last byte written before returning.
78053 ** 
78054 ** If the string zSignedIdent consists entirely of alpha-numeric
78055 ** characters, does not begin with a digit and is not an SQL keyword,
78056 ** then it is copied to the output buffer exactly as it is. Otherwise,
78057 ** it is quoted using double-quotes.
78058 */
78059 static void identPut(char *z, int *pIdx, char *zSignedIdent){
78060   unsigned char *zIdent = (unsigned char*)zSignedIdent;
78061   int i, j, needQuote;
78062   i = *pIdx;
78063
78064   for(j=0; zIdent[j]; j++){
78065     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78066   }
78067   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78068   if( !needQuote ){
78069     needQuote = zIdent[j];
78070   }
78071
78072   if( needQuote ) z[i++] = '"';
78073   for(j=0; zIdent[j]; j++){
78074     z[i++] = zIdent[j];
78075     if( zIdent[j]=='"' ) z[i++] = '"';
78076   }
78077   if( needQuote ) z[i++] = '"';
78078   z[i] = 0;
78079   *pIdx = i;
78080 }
78081
78082 /*
78083 ** Generate a CREATE TABLE statement appropriate for the given
78084 ** table.  Memory to hold the text of the statement is obtained
78085 ** from sqliteMalloc() and must be freed by the calling function.
78086 */
78087 static char *createTableStmt(sqlite3 *db, Table *p){
78088   int i, k, n;
78089   char *zStmt;
78090   char *zSep, *zSep2, *zEnd;
78091   Column *pCol;
78092   n = 0;
78093   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78094     n += identLength(pCol->zName) + 5;
78095   }
78096   n += identLength(p->zName);
78097   if( n<50 ){ 
78098     zSep = "";
78099     zSep2 = ",";
78100     zEnd = ")";
78101   }else{
78102     zSep = "\n  ";
78103     zSep2 = ",\n  ";
78104     zEnd = "\n)";
78105   }
78106   n += 35 + 6*p->nCol;
78107   zStmt = sqlite3DbMallocRaw(0, n);
78108   if( zStmt==0 ){
78109     db->mallocFailed = 1;
78110     return 0;
78111   }
78112   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78113   k = sqlite3Strlen30(zStmt);
78114   identPut(zStmt, &k, p->zName);
78115   zStmt[k++] = '(';
78116   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78117     static const char * const azType[] = {
78118         /* SQLITE_AFF_TEXT    */ " TEXT",
78119         /* SQLITE_AFF_NONE    */ "",
78120         /* SQLITE_AFF_NUMERIC */ " NUM",
78121         /* SQLITE_AFF_INTEGER */ " INT",
78122         /* SQLITE_AFF_REAL    */ " REAL"
78123     };
78124     int len;
78125     const char *zType;
78126
78127     sqlite3_snprintf(n-k, &zStmt[k], zSep);
78128     k += sqlite3Strlen30(&zStmt[k]);
78129     zSep = zSep2;
78130     identPut(zStmt, &k, pCol->zName);
78131     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78132     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78133     testcase( pCol->affinity==SQLITE_AFF_TEXT );
78134     testcase( pCol->affinity==SQLITE_AFF_NONE );
78135     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78136     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78137     testcase( pCol->affinity==SQLITE_AFF_REAL );
78138     
78139     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78140     len = sqlite3Strlen30(zType);
78141     assert( pCol->affinity==SQLITE_AFF_NONE 
78142             || pCol->affinity==sqlite3AffinityType(zType) );
78143     memcpy(&zStmt[k], zType, len);
78144     k += len;
78145     assert( k<=n );
78146   }
78147   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78148   return zStmt;
78149 }
78150
78151 /*
78152 ** This routine is called to report the final ")" that terminates
78153 ** a CREATE TABLE statement.
78154 **
78155 ** The table structure that other action routines have been building
78156 ** is added to the internal hash tables, assuming no errors have
78157 ** occurred.
78158 **
78159 ** An entry for the table is made in the master table on disk, unless
78160 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
78161 ** it means we are reading the sqlite_master table because we just
78162 ** connected to the database or because the sqlite_master table has
78163 ** recently changed, so the entry for this table already exists in
78164 ** the sqlite_master table.  We do not want to create it again.
78165 **
78166 ** If the pSelect argument is not NULL, it means that this routine
78167 ** was called to create a table generated from a 
78168 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
78169 ** the new table will match the result set of the SELECT.
78170 */
78171 SQLITE_PRIVATE void sqlite3EndTable(
78172   Parse *pParse,          /* Parse context */
78173   Token *pCons,           /* The ',' token after the last column defn. */
78174   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
78175   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
78176 ){
78177   Table *p;
78178   sqlite3 *db = pParse->db;
78179   int iDb;
78180
78181   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78182     return;
78183   }
78184   p = pParse->pNewTable;
78185   if( p==0 ) return;
78186
78187   assert( !db->init.busy || !pSelect );
78188
78189   iDb = sqlite3SchemaToIndex(db, p->pSchema);
78190
78191 #ifndef SQLITE_OMIT_CHECK
78192   /* Resolve names in all CHECK constraint expressions.
78193   */
78194   if( p->pCheck ){
78195     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
78196     NameContext sNC;                /* Name context for pParse->pNewTable */
78197
78198     memset(&sNC, 0, sizeof(sNC));
78199     memset(&sSrc, 0, sizeof(sSrc));
78200     sSrc.nSrc = 1;
78201     sSrc.a[0].zName = p->zName;
78202     sSrc.a[0].pTab = p;
78203     sSrc.a[0].iCursor = -1;
78204     sNC.pParse = pParse;
78205     sNC.pSrcList = &sSrc;
78206     sNC.isCheck = 1;
78207     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78208       return;
78209     }
78210   }
78211 #endif /* !defined(SQLITE_OMIT_CHECK) */
78212
78213   /* If the db->init.busy is 1 it means we are reading the SQL off the
78214   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78215   ** So do not write to the disk again.  Extract the root page number
78216   ** for the table from the db->init.newTnum field.  (The page number
78217   ** should have been put there by the sqliteOpenCb routine.)
78218   */
78219   if( db->init.busy ){
78220     p->tnum = db->init.newTnum;
78221   }
78222
78223   /* If not initializing, then create a record for the new table
78224   ** in the SQLITE_MASTER table of the database.
78225   **
78226   ** If this is a TEMPORARY table, write the entry into the auxiliary
78227   ** file instead of into the main database file.
78228   */
78229   if( !db->init.busy ){
78230     int n;
78231     Vdbe *v;
78232     char *zType;    /* "view" or "table" */
78233     char *zType2;   /* "VIEW" or "TABLE" */
78234     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
78235
78236     v = sqlite3GetVdbe(pParse);
78237     if( NEVER(v==0) ) return;
78238
78239     sqlite3VdbeAddOp1(v, OP_Close, 0);
78240
78241     /* 
78242     ** Initialize zType for the new view or table.
78243     */
78244     if( p->pSelect==0 ){
78245       /* A regular table */
78246       zType = "table";
78247       zType2 = "TABLE";
78248 #ifndef SQLITE_OMIT_VIEW
78249     }else{
78250       /* A view */
78251       zType = "view";
78252       zType2 = "VIEW";
78253 #endif
78254     }
78255
78256     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78257     ** statement to populate the new table. The root-page number for the
78258     ** new table is in register pParse->regRoot.
78259     **
78260     ** Once the SELECT has been coded by sqlite3Select(), it is in a
78261     ** suitable state to query for the column names and types to be used
78262     ** by the new table.
78263     **
78264     ** A shared-cache write-lock is not required to write to the new table,
78265     ** as a schema-lock must have already been obtained to create it. Since
78266     ** a schema-lock excludes all other database users, the write-lock would
78267     ** be redundant.
78268     */
78269     if( pSelect ){
78270       SelectDest dest;
78271       Table *pSelTab;
78272
78273       assert(pParse->nTab==1);
78274       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78275       sqlite3VdbeChangeP5(v, 1);
78276       pParse->nTab = 2;
78277       sqlite3SelectDestInit(&dest, SRT_Table, 1);
78278       sqlite3Select(pParse, pSelect, &dest);
78279       sqlite3VdbeAddOp1(v, OP_Close, 1);
78280       if( pParse->nErr==0 ){
78281         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78282         if( pSelTab==0 ) return;
78283         assert( p->aCol==0 );
78284         p->nCol = pSelTab->nCol;
78285         p->aCol = pSelTab->aCol;
78286         pSelTab->nCol = 0;
78287         pSelTab->aCol = 0;
78288         sqlite3DeleteTable(db, pSelTab);
78289       }
78290     }
78291
78292     /* Compute the complete text of the CREATE statement */
78293     if( pSelect ){
78294       zStmt = createTableStmt(db, p);
78295     }else{
78296       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78297       zStmt = sqlite3MPrintf(db, 
78298           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78299       );
78300     }
78301
78302     /* A slot for the record has already been allocated in the 
78303     ** SQLITE_MASTER table.  We just need to update that slot with all
78304     ** the information we've collected.
78305     */
78306     sqlite3NestedParse(pParse,
78307       "UPDATE %Q.%s "
78308          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78309        "WHERE rowid=#%d",
78310       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78311       zType,
78312       p->zName,
78313       p->zName,
78314       pParse->regRoot,
78315       zStmt,
78316       pParse->regRowid
78317     );
78318     sqlite3DbFree(db, zStmt);
78319     sqlite3ChangeCookie(pParse, iDb);
78320
78321 #ifndef SQLITE_OMIT_AUTOINCREMENT
78322     /* Check to see if we need to create an sqlite_sequence table for
78323     ** keeping track of autoincrement keys.
78324     */
78325     if( p->tabFlags & TF_Autoincrement ){
78326       Db *pDb = &db->aDb[iDb];
78327       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78328       if( pDb->pSchema->pSeqTab==0 ){
78329         sqlite3NestedParse(pParse,
78330           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78331           pDb->zName
78332         );
78333       }
78334     }
78335 #endif
78336
78337     /* Reparse everything to update our internal data structures */
78338     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
78339         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
78340   }
78341
78342
78343   /* Add the table to the in-memory representation of the database.
78344   */
78345   if( db->init.busy ){
78346     Table *pOld;
78347     Schema *pSchema = p->pSchema;
78348     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78349     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78350                              sqlite3Strlen30(p->zName),p);
78351     if( pOld ){
78352       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
78353       db->mallocFailed = 1;
78354       return;
78355     }
78356     pParse->pNewTable = 0;
78357     db->nTable++;
78358     db->flags |= SQLITE_InternChanges;
78359
78360 #ifndef SQLITE_OMIT_ALTERTABLE
78361     if( !p->pSelect ){
78362       const char *zName = (const char *)pParse->sNameToken.z;
78363       int nName;
78364       assert( !pSelect && pCons && pEnd );
78365       if( pCons->z==0 ){
78366         pCons = pEnd;
78367       }
78368       nName = (int)((const char *)pCons->z - zName);
78369       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78370     }
78371 #endif
78372   }
78373 }
78374
78375 #ifndef SQLITE_OMIT_VIEW
78376 /*
78377 ** The parser calls this routine in order to create a new VIEW
78378 */
78379 SQLITE_PRIVATE void sqlite3CreateView(
78380   Parse *pParse,     /* The parsing context */
78381   Token *pBegin,     /* The CREATE token that begins the statement */
78382   Token *pName1,     /* The token that holds the name of the view */
78383   Token *pName2,     /* The token that holds the name of the view */
78384   Select *pSelect,   /* A SELECT statement that will become the new view */
78385   int isTemp,        /* TRUE for a TEMPORARY view */
78386   int noErr          /* Suppress error messages if VIEW already exists */
78387 ){
78388   Table *p;
78389   int n;
78390   const char *z;
78391   Token sEnd;
78392   DbFixer sFix;
78393   Token *pName;
78394   int iDb;
78395   sqlite3 *db = pParse->db;
78396
78397   if( pParse->nVar>0 ){
78398     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
78399     sqlite3SelectDelete(db, pSelect);
78400     return;
78401   }
78402   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
78403   p = pParse->pNewTable;
78404   if( p==0 || pParse->nErr ){
78405     sqlite3SelectDelete(db, pSelect);
78406     return;
78407   }
78408   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78409   iDb = sqlite3SchemaToIndex(db, p->pSchema);
78410   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
78411     && sqlite3FixSelect(&sFix, pSelect)
78412   ){
78413     sqlite3SelectDelete(db, pSelect);
78414     return;
78415   }
78416
78417   /* Make a copy of the entire SELECT statement that defines the view.
78418   ** This will force all the Expr.token.z values to be dynamically
78419   ** allocated rather than point to the input string - which means that
78420   ** they will persist after the current sqlite3_exec() call returns.
78421   */
78422   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
78423   sqlite3SelectDelete(db, pSelect);
78424   if( db->mallocFailed ){
78425     return;
78426   }
78427   if( !db->init.busy ){
78428     sqlite3ViewGetColumnNames(pParse, p);
78429   }
78430
78431   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
78432   ** the end.
78433   */
78434   sEnd = pParse->sLastToken;
78435   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
78436     sEnd.z += sEnd.n;
78437   }
78438   sEnd.n = 0;
78439   n = (int)(sEnd.z - pBegin->z);
78440   z = pBegin->z;
78441   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
78442   sEnd.z = &z[n-1];
78443   sEnd.n = 1;
78444
78445   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
78446   sqlite3EndTable(pParse, 0, &sEnd, 0);
78447   return;
78448 }
78449 #endif /* SQLITE_OMIT_VIEW */
78450
78451 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78452 /*
78453 ** The Table structure pTable is really a VIEW.  Fill in the names of
78454 ** the columns of the view in the pTable structure.  Return the number
78455 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
78456 */
78457 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
78458   Table *pSelTab;   /* A fake table from which we get the result set */
78459   Select *pSel;     /* Copy of the SELECT that implements the view */
78460   int nErr = 0;     /* Number of errors encountered */
78461   int n;            /* Temporarily holds the number of cursors assigned */
78462   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
78463   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78464
78465   assert( pTable );
78466
78467 #ifndef SQLITE_OMIT_VIRTUALTABLE
78468   if( sqlite3VtabCallConnect(pParse, pTable) ){
78469     return SQLITE_ERROR;
78470   }
78471   if( IsVirtual(pTable) ) return 0;
78472 #endif
78473
78474 #ifndef SQLITE_OMIT_VIEW
78475   /* A positive nCol means the columns names for this view are
78476   ** already known.
78477   */
78478   if( pTable->nCol>0 ) return 0;
78479
78480   /* A negative nCol is a special marker meaning that we are currently
78481   ** trying to compute the column names.  If we enter this routine with
78482   ** a negative nCol, it means two or more views form a loop, like this:
78483   **
78484   **     CREATE VIEW one AS SELECT * FROM two;
78485   **     CREATE VIEW two AS SELECT * FROM one;
78486   **
78487   ** Actually, the error above is now caught prior to reaching this point.
78488   ** But the following test is still important as it does come up
78489   ** in the following:
78490   ** 
78491   **     CREATE TABLE main.ex1(a);
78492   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
78493   **     SELECT * FROM temp.ex1;
78494   */
78495   if( pTable->nCol<0 ){
78496     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
78497     return 1;
78498   }
78499   assert( pTable->nCol>=0 );
78500
78501   /* If we get this far, it means we need to compute the table names.
78502   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
78503   ** "*" elements in the results set of the view and will assign cursors
78504   ** to the elements of the FROM clause.  But we do not want these changes
78505   ** to be permanent.  So the computation is done on a copy of the SELECT
78506   ** statement that defines the view.
78507   */
78508   assert( pTable->pSelect );
78509   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
78510   if( pSel ){
78511     u8 enableLookaside = db->lookaside.bEnabled;
78512     n = pParse->nTab;
78513     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
78514     pTable->nCol = -1;
78515     db->lookaside.bEnabled = 0;
78516 #ifndef SQLITE_OMIT_AUTHORIZATION
78517     xAuth = db->xAuth;
78518     db->xAuth = 0;
78519     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78520     db->xAuth = xAuth;
78521 #else
78522     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78523 #endif
78524     db->lookaside.bEnabled = enableLookaside;
78525     pParse->nTab = n;
78526     if( pSelTab ){
78527       assert( pTable->aCol==0 );
78528       pTable->nCol = pSelTab->nCol;
78529       pTable->aCol = pSelTab->aCol;
78530       pSelTab->nCol = 0;
78531       pSelTab->aCol = 0;
78532       sqlite3DeleteTable(db, pSelTab);
78533       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
78534       pTable->pSchema->flags |= DB_UnresetViews;
78535     }else{
78536       pTable->nCol = 0;
78537       nErr++;
78538     }
78539     sqlite3SelectDelete(db, pSel);
78540   } else {
78541     nErr++;
78542   }
78543 #endif /* SQLITE_OMIT_VIEW */
78544   return nErr;  
78545 }
78546 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
78547
78548 #ifndef SQLITE_OMIT_VIEW
78549 /*
78550 ** Clear the column names from every VIEW in database idx.
78551 */
78552 static void sqliteViewResetAll(sqlite3 *db, int idx){
78553   HashElem *i;
78554   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
78555   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
78556   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
78557     Table *pTab = sqliteHashData(i);
78558     if( pTab->pSelect ){
78559       sqliteDeleteColumnNames(db, pTab);
78560       pTab->aCol = 0;
78561       pTab->nCol = 0;
78562     }
78563   }
78564   DbClearProperty(db, idx, DB_UnresetViews);
78565 }
78566 #else
78567 # define sqliteViewResetAll(A,B)
78568 #endif /* SQLITE_OMIT_VIEW */
78569
78570 /*
78571 ** This function is called by the VDBE to adjust the internal schema
78572 ** used by SQLite when the btree layer moves a table root page. The
78573 ** root-page of a table or index in database iDb has changed from iFrom
78574 ** to iTo.
78575 **
78576 ** Ticket #1728:  The symbol table might still contain information
78577 ** on tables and/or indices that are the process of being deleted.
78578 ** If you are unlucky, one of those deleted indices or tables might
78579 ** have the same rootpage number as the real table or index that is
78580 ** being moved.  So we cannot stop searching after the first match 
78581 ** because the first match might be for one of the deleted indices
78582 ** or tables and not the table/index that is actually being moved.
78583 ** We must continue looping until all tables and indices with
78584 ** rootpage==iFrom have been converted to have a rootpage of iTo
78585 ** in order to be certain that we got the right one.
78586 */
78587 #ifndef SQLITE_OMIT_AUTOVACUUM
78588 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
78589   HashElem *pElem;
78590   Hash *pHash;
78591   Db *pDb;
78592
78593   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78594   pDb = &db->aDb[iDb];
78595   pHash = &pDb->pSchema->tblHash;
78596   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78597     Table *pTab = sqliteHashData(pElem);
78598     if( pTab->tnum==iFrom ){
78599       pTab->tnum = iTo;
78600     }
78601   }
78602   pHash = &pDb->pSchema->idxHash;
78603   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78604     Index *pIdx = sqliteHashData(pElem);
78605     if( pIdx->tnum==iFrom ){
78606       pIdx->tnum = iTo;
78607     }
78608   }
78609 }
78610 #endif
78611
78612 /*
78613 ** Write code to erase the table with root-page iTable from database iDb.
78614 ** Also write code to modify the sqlite_master table and internal schema
78615 ** if a root-page of another table is moved by the btree-layer whilst
78616 ** erasing iTable (this can happen with an auto-vacuum database).
78617 */ 
78618 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
78619   Vdbe *v = sqlite3GetVdbe(pParse);
78620   int r1 = sqlite3GetTempReg(pParse);
78621   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
78622   sqlite3MayAbort(pParse);
78623 #ifndef SQLITE_OMIT_AUTOVACUUM
78624   /* OP_Destroy stores an in integer r1. If this integer
78625   ** is non-zero, then it is the root page number of a table moved to
78626   ** location iTable. The following code modifies the sqlite_master table to
78627   ** reflect this.
78628   **
78629   ** The "#NNN" in the SQL is a special constant that means whatever value
78630   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
78631   ** token for additional information.
78632   */
78633   sqlite3NestedParse(pParse, 
78634      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
78635      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
78636 #endif
78637   sqlite3ReleaseTempReg(pParse, r1);
78638 }
78639
78640 /*
78641 ** Write VDBE code to erase table pTab and all associated indices on disk.
78642 ** Code to update the sqlite_master tables and internal schema definitions
78643 ** in case a root-page belonging to another table is moved by the btree layer
78644 ** is also added (this can happen with an auto-vacuum database).
78645 */
78646 static void destroyTable(Parse *pParse, Table *pTab){
78647 #ifdef SQLITE_OMIT_AUTOVACUUM
78648   Index *pIdx;
78649   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78650   destroyRootPage(pParse, pTab->tnum, iDb);
78651   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78652     destroyRootPage(pParse, pIdx->tnum, iDb);
78653   }
78654 #else
78655   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
78656   ** is not defined), then it is important to call OP_Destroy on the
78657   ** table and index root-pages in order, starting with the numerically 
78658   ** largest root-page number. This guarantees that none of the root-pages
78659   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
78660   ** following were coded:
78661   **
78662   ** OP_Destroy 4 0
78663   ** ...
78664   ** OP_Destroy 5 0
78665   **
78666   ** and root page 5 happened to be the largest root-page number in the
78667   ** database, then root page 5 would be moved to page 4 by the 
78668   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
78669   ** a free-list page.
78670   */
78671   int iTab = pTab->tnum;
78672   int iDestroyed = 0;
78673
78674   while( 1 ){
78675     Index *pIdx;
78676     int iLargest = 0;
78677
78678     if( iDestroyed==0 || iTab<iDestroyed ){
78679       iLargest = iTab;
78680     }
78681     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78682       int iIdx = pIdx->tnum;
78683       assert( pIdx->pSchema==pTab->pSchema );
78684       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
78685         iLargest = iIdx;
78686       }
78687     }
78688     if( iLargest==0 ){
78689       return;
78690     }else{
78691       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78692       destroyRootPage(pParse, iLargest, iDb);
78693       iDestroyed = iLargest;
78694     }
78695   }
78696 #endif
78697 }
78698
78699 /*
78700 ** This routine is called to do the work of a DROP TABLE statement.
78701 ** pName is the name of the table to be dropped.
78702 */
78703 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
78704   Table *pTab;
78705   Vdbe *v;
78706   sqlite3 *db = pParse->db;
78707   int iDb;
78708
78709   if( db->mallocFailed ){
78710     goto exit_drop_table;
78711   }
78712   assert( pParse->nErr==0 );
78713   assert( pName->nSrc==1 );
78714   if( noErr ) db->suppressErr++;
78715   pTab = sqlite3LocateTable(pParse, isView, 
78716                             pName->a[0].zName, pName->a[0].zDatabase);
78717   if( noErr ) db->suppressErr--;
78718
78719   if( pTab==0 ){
78720     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
78721     goto exit_drop_table;
78722   }
78723   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78724   assert( iDb>=0 && iDb<db->nDb );
78725
78726   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
78727   ** it is initialized.
78728   */
78729   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
78730     goto exit_drop_table;
78731   }
78732 #ifndef SQLITE_OMIT_AUTHORIZATION
78733   {
78734     int code;
78735     const char *zTab = SCHEMA_TABLE(iDb);
78736     const char *zDb = db->aDb[iDb].zName;
78737     const char *zArg2 = 0;
78738     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
78739       goto exit_drop_table;
78740     }
78741     if( isView ){
78742       if( !OMIT_TEMPDB && iDb==1 ){
78743         code = SQLITE_DROP_TEMP_VIEW;
78744       }else{
78745         code = SQLITE_DROP_VIEW;
78746       }
78747 #ifndef SQLITE_OMIT_VIRTUALTABLE
78748     }else if( IsVirtual(pTab) ){
78749       code = SQLITE_DROP_VTABLE;
78750       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
78751 #endif
78752     }else{
78753       if( !OMIT_TEMPDB && iDb==1 ){
78754         code = SQLITE_DROP_TEMP_TABLE;
78755       }else{
78756         code = SQLITE_DROP_TABLE;
78757       }
78758     }
78759     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
78760       goto exit_drop_table;
78761     }
78762     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
78763       goto exit_drop_table;
78764     }
78765   }
78766 #endif
78767   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
78768     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
78769     goto exit_drop_table;
78770   }
78771
78772 #ifndef SQLITE_OMIT_VIEW
78773   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
78774   ** on a table.
78775   */
78776   if( isView && pTab->pSelect==0 ){
78777     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
78778     goto exit_drop_table;
78779   }
78780   if( !isView && pTab->pSelect ){
78781     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
78782     goto exit_drop_table;
78783   }
78784 #endif
78785
78786   /* Generate code to remove the table from the master table
78787   ** on disk.
78788   */
78789   v = sqlite3GetVdbe(pParse);
78790   if( v ){
78791     Trigger *pTrigger;
78792     Db *pDb = &db->aDb[iDb];
78793     sqlite3BeginWriteOperation(pParse, 1, iDb);
78794
78795 #ifndef SQLITE_OMIT_VIRTUALTABLE
78796     if( IsVirtual(pTab) ){
78797       sqlite3VdbeAddOp0(v, OP_VBegin);
78798     }
78799 #endif
78800     sqlite3FkDropTable(pParse, pName, pTab);
78801
78802     /* Drop all triggers associated with the table being dropped. Code
78803     ** is generated to remove entries from sqlite_master and/or
78804     ** sqlite_temp_master if required.
78805     */
78806     pTrigger = sqlite3TriggerList(pParse, pTab);
78807     while( pTrigger ){
78808       assert( pTrigger->pSchema==pTab->pSchema || 
78809           pTrigger->pSchema==db->aDb[1].pSchema );
78810       sqlite3DropTriggerPtr(pParse, pTrigger);
78811       pTrigger = pTrigger->pNext;
78812     }
78813
78814 #ifndef SQLITE_OMIT_AUTOINCREMENT
78815     /* Remove any entries of the sqlite_sequence table associated with
78816     ** the table being dropped. This is done before the table is dropped
78817     ** at the btree level, in case the sqlite_sequence table needs to
78818     ** move as a result of the drop (can happen in auto-vacuum mode).
78819     */
78820     if( pTab->tabFlags & TF_Autoincrement ){
78821       sqlite3NestedParse(pParse,
78822         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
78823         pDb->zName, pTab->zName
78824       );
78825     }
78826 #endif
78827
78828     /* Drop all SQLITE_MASTER table and index entries that refer to the
78829     ** table. The program name loops through the master table and deletes
78830     ** every row that refers to a table of the same name as the one being
78831     ** dropped. Triggers are handled seperately because a trigger can be
78832     ** created in the temp database that refers to a table in another
78833     ** database.
78834     */
78835     sqlite3NestedParse(pParse, 
78836         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
78837         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
78838
78839     /* Drop any statistics from the sqlite_stat1 table, if it exists */
78840     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
78841       sqlite3NestedParse(pParse,
78842         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
78843       );
78844     }
78845
78846     if( !isView && !IsVirtual(pTab) ){
78847       destroyTable(pParse, pTab);
78848     }
78849
78850     /* Remove the table entry from SQLite's internal schema and modify
78851     ** the schema cookie.
78852     */
78853     if( IsVirtual(pTab) ){
78854       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
78855     }
78856     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78857     sqlite3ChangeCookie(pParse, iDb);
78858   }
78859   sqliteViewResetAll(db, iDb);
78860
78861 exit_drop_table:
78862   sqlite3SrcListDelete(db, pName);
78863 }
78864
78865 /*
78866 ** This routine is called to create a new foreign key on the table
78867 ** currently under construction.  pFromCol determines which columns
78868 ** in the current table point to the foreign key.  If pFromCol==0 then
78869 ** connect the key to the last column inserted.  pTo is the name of
78870 ** the table referred to.  pToCol is a list of tables in the other
78871 ** pTo table that the foreign key points to.  flags contains all
78872 ** information about the conflict resolution algorithms specified
78873 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
78874 **
78875 ** An FKey structure is created and added to the table currently
78876 ** under construction in the pParse->pNewTable field.
78877 **
78878 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
78879 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
78880 */
78881 SQLITE_PRIVATE void sqlite3CreateForeignKey(
78882   Parse *pParse,       /* Parsing context */
78883   ExprList *pFromCol,  /* Columns in this table that point to other table */
78884   Token *pTo,          /* Name of the other table */
78885   ExprList *pToCol,    /* Columns in the other table */
78886   int flags            /* Conflict resolution algorithms. */
78887 ){
78888   sqlite3 *db = pParse->db;
78889 #ifndef SQLITE_OMIT_FOREIGN_KEY
78890   FKey *pFKey = 0;
78891   FKey *pNextTo;
78892   Table *p = pParse->pNewTable;
78893   int nByte;
78894   int i;
78895   int nCol;
78896   char *z;
78897
78898   assert( pTo!=0 );
78899   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
78900   if( pFromCol==0 ){
78901     int iCol = p->nCol-1;
78902     if( NEVER(iCol<0) ) goto fk_end;
78903     if( pToCol && pToCol->nExpr!=1 ){
78904       sqlite3ErrorMsg(pParse, "foreign key on %s"
78905          " should reference only one column of table %T",
78906          p->aCol[iCol].zName, pTo);
78907       goto fk_end;
78908     }
78909     nCol = 1;
78910   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
78911     sqlite3ErrorMsg(pParse,
78912         "number of columns in foreign key does not match the number of "
78913         "columns in the referenced table");
78914     goto fk_end;
78915   }else{
78916     nCol = pFromCol->nExpr;
78917   }
78918   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
78919   if( pToCol ){
78920     for(i=0; i<pToCol->nExpr; i++){
78921       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
78922     }
78923   }
78924   pFKey = sqlite3DbMallocZero(db, nByte );
78925   if( pFKey==0 ){
78926     goto fk_end;
78927   }
78928   pFKey->pFrom = p;
78929   pFKey->pNextFrom = p->pFKey;
78930   z = (char*)&pFKey->aCol[nCol];
78931   pFKey->zTo = z;
78932   memcpy(z, pTo->z, pTo->n);
78933   z[pTo->n] = 0;
78934   sqlite3Dequote(z);
78935   z += pTo->n+1;
78936   pFKey->nCol = nCol;
78937   if( pFromCol==0 ){
78938     pFKey->aCol[0].iFrom = p->nCol-1;
78939   }else{
78940     for(i=0; i<nCol; i++){
78941       int j;
78942       for(j=0; j<p->nCol; j++){
78943         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
78944           pFKey->aCol[i].iFrom = j;
78945           break;
78946         }
78947       }
78948       if( j>=p->nCol ){
78949         sqlite3ErrorMsg(pParse, 
78950           "unknown column \"%s\" in foreign key definition", 
78951           pFromCol->a[i].zName);
78952         goto fk_end;
78953       }
78954     }
78955   }
78956   if( pToCol ){
78957     for(i=0; i<nCol; i++){
78958       int n = sqlite3Strlen30(pToCol->a[i].zName);
78959       pFKey->aCol[i].zCol = z;
78960       memcpy(z, pToCol->a[i].zName, n);
78961       z[n] = 0;
78962       z += n+1;
78963     }
78964   }
78965   pFKey->isDeferred = 0;
78966   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
78967   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
78968
78969   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
78970   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
78971       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
78972   );
78973   if( pNextTo==pFKey ){
78974     db->mallocFailed = 1;
78975     goto fk_end;
78976   }
78977   if( pNextTo ){
78978     assert( pNextTo->pPrevTo==0 );
78979     pFKey->pNextTo = pNextTo;
78980     pNextTo->pPrevTo = pFKey;
78981   }
78982
78983   /* Link the foreign key to the table as the last step.
78984   */
78985   p->pFKey = pFKey;
78986   pFKey = 0;
78987
78988 fk_end:
78989   sqlite3DbFree(db, pFKey);
78990 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
78991   sqlite3ExprListDelete(db, pFromCol);
78992   sqlite3ExprListDelete(db, pToCol);
78993 }
78994
78995 /*
78996 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
78997 ** clause is seen as part of a foreign key definition.  The isDeferred
78998 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
78999 ** The behavior of the most recently created foreign key is adjusted
79000 ** accordingly.
79001 */
79002 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
79003 #ifndef SQLITE_OMIT_FOREIGN_KEY
79004   Table *pTab;
79005   FKey *pFKey;
79006   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
79007   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
79008   pFKey->isDeferred = (u8)isDeferred;
79009 #endif
79010 }
79011
79012 /*
79013 ** Generate code that will erase and refill index *pIdx.  This is
79014 ** used to initialize a newly created index or to recompute the
79015 ** content of an index in response to a REINDEX command.
79016 **
79017 ** if memRootPage is not negative, it means that the index is newly
79018 ** created.  The register specified by memRootPage contains the
79019 ** root page number of the index.  If memRootPage is negative, then
79020 ** the index already exists and must be cleared before being refilled and
79021 ** the root page number of the index is taken from pIndex->tnum.
79022 */
79023 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79024   Table *pTab = pIndex->pTable;  /* The table that is indexed */
79025   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
79026   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
79027   int addr1;                     /* Address of top of loop */
79028   int tnum;                      /* Root page of index */
79029   Vdbe *v;                       /* Generate code into this virtual machine */
79030   KeyInfo *pKey;                 /* KeyInfo for index */
79031   int regIdxKey;                 /* Registers containing the index key */
79032   int regRecord;                 /* Register holding assemblied index record */
79033   sqlite3 *db = pParse->db;      /* The database connection */
79034   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79035
79036 #ifndef SQLITE_OMIT_AUTHORIZATION
79037   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79038       db->aDb[iDb].zName ) ){
79039     return;
79040   }
79041 #endif
79042
79043   /* Require a write-lock on the table to perform this operation */
79044   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79045
79046   v = sqlite3GetVdbe(pParse);
79047   if( v==0 ) return;
79048   if( memRootPage>=0 ){
79049     tnum = memRootPage;
79050   }else{
79051     tnum = pIndex->tnum;
79052     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79053   }
79054   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79055   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
79056                     (char *)pKey, P4_KEYINFO_HANDOFF);
79057   if( memRootPage>=0 ){
79058     sqlite3VdbeChangeP5(v, 1);
79059   }
79060   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79061   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79062   regRecord = sqlite3GetTempReg(pParse);
79063   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79064   if( pIndex->onError!=OE_None ){
79065     const int regRowid = regIdxKey + pIndex->nColumn;
79066     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79067     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79068
79069     /* The registers accessed by the OP_IsUnique opcode were allocated
79070     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79071     ** call above. Just before that function was freed they were released
79072     ** (made available to the compiler for reuse) using 
79073     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79074     ** opcode use the values stored within seems dangerous. However, since
79075     ** we can be sure that no other temp registers have been allocated
79076     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79077     */
79078     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79079     sqlite3HaltConstraint(
79080         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79081   }
79082   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79083   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79084   sqlite3ReleaseTempReg(pParse, regRecord);
79085   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79086   sqlite3VdbeJumpHere(v, addr1);
79087   sqlite3VdbeAddOp1(v, OP_Close, iTab);
79088   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79089 }
79090
79091 /*
79092 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
79093 ** and pTblList is the name of the table that is to be indexed.  Both will 
79094 ** be NULL for a primary key or an index that is created to satisfy a
79095 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
79096 ** as the table to be indexed.  pParse->pNewTable is a table that is
79097 ** currently being constructed by a CREATE TABLE statement.
79098 **
79099 ** pList is a list of columns to be indexed.  pList will be NULL if this
79100 ** is a primary key or unique-constraint on the most recent column added
79101 ** to the table currently under construction.  
79102 **
79103 ** If the index is created successfully, return a pointer to the new Index
79104 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79105 ** as the tables primary key (Index.autoIndex==2).
79106 */
79107 SQLITE_PRIVATE Index *sqlite3CreateIndex(
79108   Parse *pParse,     /* All information about this parse */
79109   Token *pName1,     /* First part of index name. May be NULL */
79110   Token *pName2,     /* Second part of index name. May be NULL */
79111   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79112   ExprList *pList,   /* A list of columns to be indexed */
79113   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79114   Token *pStart,     /* The CREATE token that begins this statement */
79115   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
79116   int sortOrder,     /* Sort order of primary key when pList==NULL */
79117   int ifNotExist     /* Omit error if index already exists */
79118 ){
79119   Index *pRet = 0;     /* Pointer to return */
79120   Table *pTab = 0;     /* Table to be indexed */
79121   Index *pIndex = 0;   /* The index to be created */
79122   char *zName = 0;     /* Name of the index */
79123   int nName;           /* Number of characters in zName */
79124   int i, j;
79125   Token nullId;        /* Fake token for an empty ID list */
79126   DbFixer sFix;        /* For assigning database names to pTable */
79127   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
79128   sqlite3 *db = pParse->db;
79129   Db *pDb;             /* The specific table containing the indexed database */
79130   int iDb;             /* Index of the database that is being written */
79131   Token *pName = 0;    /* Unqualified name of the index to create */
79132   struct ExprList_item *pListItem; /* For looping over pList */
79133   int nCol;
79134   int nExtra = 0;
79135   char *zExtra;
79136
79137   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79138   assert( pParse->nErr==0 );      /* Never called with prior errors */
79139   if( db->mallocFailed || IN_DECLARE_VTAB ){
79140     goto exit_create_index;
79141   }
79142   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79143     goto exit_create_index;
79144   }
79145
79146   /*
79147   ** Find the table that is to be indexed.  Return early if not found.
79148   */
79149   if( pTblName!=0 ){
79150
79151     /* Use the two-part index name to determine the database 
79152     ** to search for the table. 'Fix' the table name to this db
79153     ** before looking up the table.
79154     */
79155     assert( pName1 && pName2 );
79156     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79157     if( iDb<0 ) goto exit_create_index;
79158
79159 #ifndef SQLITE_OMIT_TEMPDB
79160     /* If the index name was unqualified, check if the the table
79161     ** is a temp table. If so, set the database to 1. Do not do this
79162     ** if initialising a database schema.
79163     */
79164     if( !db->init.busy ){
79165       pTab = sqlite3SrcListLookup(pParse, pTblName);
79166       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79167         iDb = 1;
79168       }
79169     }
79170 #endif
79171
79172     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79173         sqlite3FixSrcList(&sFix, pTblName)
79174     ){
79175       /* Because the parser constructs pTblName from a single identifier,
79176       ** sqlite3FixSrcList can never fail. */
79177       assert(0);
79178     }
79179     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
79180         pTblName->a[0].zDatabase);
79181     if( !pTab || db->mallocFailed ) goto exit_create_index;
79182     assert( db->aDb[iDb].pSchema==pTab->pSchema );
79183   }else{
79184     assert( pName==0 );
79185     pTab = pParse->pNewTable;
79186     if( !pTab ) goto exit_create_index;
79187     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79188   }
79189   pDb = &db->aDb[iDb];
79190
79191   assert( pTab!=0 );
79192   assert( pParse->nErr==0 );
79193   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
79194        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
79195     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79196     goto exit_create_index;
79197   }
79198 #ifndef SQLITE_OMIT_VIEW
79199   if( pTab->pSelect ){
79200     sqlite3ErrorMsg(pParse, "views may not be indexed");
79201     goto exit_create_index;
79202   }
79203 #endif
79204 #ifndef SQLITE_OMIT_VIRTUALTABLE
79205   if( IsVirtual(pTab) ){
79206     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79207     goto exit_create_index;
79208   }
79209 #endif
79210
79211   /*
79212   ** Find the name of the index.  Make sure there is not already another
79213   ** index or table with the same name.  
79214   **
79215   ** Exception:  If we are reading the names of permanent indices from the
79216   ** sqlite_master table (because some other process changed the schema) and
79217   ** one of the index names collides with the name of a temporary table or
79218   ** index, then we will continue to process this index.
79219   **
79220   ** If pName==0 it means that we are
79221   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
79222   ** own name.
79223   */
79224   if( pName ){
79225     zName = sqlite3NameFromToken(db, pName);
79226     if( zName==0 ) goto exit_create_index;
79227     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79228       goto exit_create_index;
79229     }
79230     if( !db->init.busy ){
79231       if( sqlite3FindTable(db, zName, 0)!=0 ){
79232         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79233         goto exit_create_index;
79234       }
79235     }
79236     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79237       if( !ifNotExist ){
79238         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79239       }else{
79240         assert( !db->init.busy );
79241         sqlite3CodeVerifySchema(pParse, iDb);
79242       }
79243       goto exit_create_index;
79244     }
79245   }else{
79246     int n;
79247     Index *pLoop;
79248     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79249     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79250     if( zName==0 ){
79251       goto exit_create_index;
79252     }
79253   }
79254
79255   /* Check for authorization to create an index.
79256   */
79257 #ifndef SQLITE_OMIT_AUTHORIZATION
79258   {
79259     const char *zDb = pDb->zName;
79260     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79261       goto exit_create_index;
79262     }
79263     i = SQLITE_CREATE_INDEX;
79264     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79265     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79266       goto exit_create_index;
79267     }
79268   }
79269 #endif
79270
79271   /* If pList==0, it means this routine was called to make a primary
79272   ** key out of the last column added to the table under construction.
79273   ** So create a fake list to simulate this.
79274   */
79275   if( pList==0 ){
79276     nullId.z = pTab->aCol[pTab->nCol-1].zName;
79277     nullId.n = sqlite3Strlen30((char*)nullId.z);
79278     pList = sqlite3ExprListAppend(pParse, 0, 0);
79279     if( pList==0 ) goto exit_create_index;
79280     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79281     pList->a[0].sortOrder = (u8)sortOrder;
79282   }
79283
79284   /* Figure out how many bytes of space are required to store explicitly
79285   ** specified collation sequence names.
79286   */
79287   for(i=0; i<pList->nExpr; i++){
79288     Expr *pExpr = pList->a[i].pExpr;
79289     if( pExpr ){
79290       CollSeq *pColl = pExpr->pColl;
79291       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
79292       ** failure we have quit before reaching this point. */
79293       if( ALWAYS(pColl) ){
79294         nExtra += (1 + sqlite3Strlen30(pColl->zName));
79295       }
79296     }
79297   }
79298
79299   /* 
79300   ** Allocate the index structure. 
79301   */
79302   nName = sqlite3Strlen30(zName);
79303   nCol = pList->nExpr;
79304   pIndex = sqlite3DbMallocZero(db, 
79305       sizeof(Index) +              /* Index structure  */
79306       sizeof(int)*nCol +           /* Index.aiColumn   */
79307       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
79308       sizeof(char *)*nCol +        /* Index.azColl     */
79309       sizeof(u8)*nCol +            /* Index.aSortOrder */
79310       nName + 1 +                  /* Index.zName      */
79311       nExtra                       /* Collation sequence names */
79312   );
79313   if( db->mallocFailed ){
79314     goto exit_create_index;
79315   }
79316   pIndex->azColl = (char**)(&pIndex[1]);
79317   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79318   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79319   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79320   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79321   zExtra = (char *)(&pIndex->zName[nName+1]);
79322   memcpy(pIndex->zName, zName, nName+1);
79323   pIndex->pTable = pTab;
79324   pIndex->nColumn = pList->nExpr;
79325   pIndex->onError = (u8)onError;
79326   pIndex->autoIndex = (u8)(pName==0);
79327   pIndex->pSchema = db->aDb[iDb].pSchema;
79328   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79329
79330   /* Check to see if we should honor DESC requests on index columns
79331   */
79332   if( pDb->pSchema->file_format>=4 ){
79333     sortOrderMask = -1;   /* Honor DESC */
79334   }else{
79335     sortOrderMask = 0;    /* Ignore DESC */
79336   }
79337
79338   /* Scan the names of the columns of the table to be indexed and
79339   ** load the column indices into the Index structure.  Report an error
79340   ** if any column is not found.
79341   **
79342   ** TODO:  Add a test to make sure that the same column is not named
79343   ** more than once within the same index.  Only the first instance of
79344   ** the column will ever be used by the optimizer.  Note that using the
79345   ** same column more than once cannot be an error because that would 
79346   ** break backwards compatibility - it needs to be a warning.
79347   */
79348   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79349     const char *zColName = pListItem->zName;
79350     Column *pTabCol;
79351     int requestedSortOrder;
79352     char *zColl;                   /* Collation sequence name */
79353
79354     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79355       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79356     }
79357     if( j>=pTab->nCol ){
79358       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79359         pTab->zName, zColName);
79360       pParse->checkSchema = 1;
79361       goto exit_create_index;
79362     }
79363     pIndex->aiColumn[i] = j;
79364     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
79365     ** the way the "idxlist" non-terminal is constructed by the parser,
79366     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79367     ** must exist or else there must have been an OOM error.  But if there
79368     ** was an OOM error, we would never reach this point. */
79369     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79370       int nColl;
79371       zColl = pListItem->pExpr->pColl->zName;
79372       nColl = sqlite3Strlen30(zColl) + 1;
79373       assert( nExtra>=nColl );
79374       memcpy(zExtra, zColl, nColl);
79375       zColl = zExtra;
79376       zExtra += nColl;
79377       nExtra -= nColl;
79378     }else{
79379       zColl = pTab->aCol[j].zColl;
79380       if( !zColl ){
79381         zColl = db->pDfltColl->zName;
79382       }
79383     }
79384     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
79385       goto exit_create_index;
79386     }
79387     pIndex->azColl[i] = zColl;
79388     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
79389     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
79390   }
79391   sqlite3DefaultRowEst(pIndex);
79392
79393   if( pTab==pParse->pNewTable ){
79394     /* This routine has been called to create an automatic index as a
79395     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
79396     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
79397     ** i.e. one of:
79398     **
79399     ** CREATE TABLE t(x PRIMARY KEY, y);
79400     ** CREATE TABLE t(x, y, UNIQUE(x, y));
79401     **
79402     ** Either way, check to see if the table already has such an index. If
79403     ** so, don't bother creating this one. This only applies to
79404     ** automatically created indices. Users can do as they wish with
79405     ** explicit indices.
79406     **
79407     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
79408     ** (and thus suppressing the second one) even if they have different
79409     ** sort orders.
79410     **
79411     ** If there are different collating sequences or if the columns of
79412     ** the constraint occur in different orders, then the constraints are
79413     ** considered distinct and both result in separate indices.
79414     */
79415     Index *pIdx;
79416     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79417       int k;
79418       assert( pIdx->onError!=OE_None );
79419       assert( pIdx->autoIndex );
79420       assert( pIndex->onError!=OE_None );
79421
79422       if( pIdx->nColumn!=pIndex->nColumn ) continue;
79423       for(k=0; k<pIdx->nColumn; k++){
79424         const char *z1;
79425         const char *z2;
79426         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
79427         z1 = pIdx->azColl[k];
79428         z2 = pIndex->azColl[k];
79429         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
79430       }
79431       if( k==pIdx->nColumn ){
79432         if( pIdx->onError!=pIndex->onError ){
79433           /* This constraint creates the same index as a previous
79434           ** constraint specified somewhere in the CREATE TABLE statement.
79435           ** However the ON CONFLICT clauses are different. If both this 
79436           ** constraint and the previous equivalent constraint have explicit
79437           ** ON CONFLICT clauses this is an error. Otherwise, use the
79438           ** explicitly specified behaviour for the index.
79439           */
79440           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
79441             sqlite3ErrorMsg(pParse, 
79442                 "conflicting ON CONFLICT clauses specified", 0);
79443           }
79444           if( pIdx->onError==OE_Default ){
79445             pIdx->onError = pIndex->onError;
79446           }
79447         }
79448         goto exit_create_index;
79449       }
79450     }
79451   }
79452
79453   /* Link the new Index structure to its table and to the other
79454   ** in-memory database structures. 
79455   */
79456   if( db->init.busy ){
79457     Index *p;
79458     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79459     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
79460                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
79461                           pIndex);
79462     if( p ){
79463       assert( p==pIndex );  /* Malloc must have failed */
79464       db->mallocFailed = 1;
79465       goto exit_create_index;
79466     }
79467     db->flags |= SQLITE_InternChanges;
79468     if( pTblName!=0 ){
79469       pIndex->tnum = db->init.newTnum;
79470     }
79471   }
79472
79473   /* If the db->init.busy is 0 then create the index on disk.  This
79474   ** involves writing the index into the master table and filling in the
79475   ** index with the current table contents.
79476   **
79477   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
79478   ** command.  db->init.busy is 1 when a database is opened and 
79479   ** CREATE INDEX statements are read out of the master table.  In
79480   ** the latter case the index already exists on disk, which is why
79481   ** we don't want to recreate it.
79482   **
79483   ** If pTblName==0 it means this index is generated as a primary key
79484   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
79485   ** has just been created, it contains no data and the index initialization
79486   ** step can be skipped.
79487   */
79488   else{ /* if( db->init.busy==0 ) */
79489     Vdbe *v;
79490     char *zStmt;
79491     int iMem = ++pParse->nMem;
79492
79493     v = sqlite3GetVdbe(pParse);
79494     if( v==0 ) goto exit_create_index;
79495
79496
79497     /* Create the rootpage for the index
79498     */
79499     sqlite3BeginWriteOperation(pParse, 1, iDb);
79500     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
79501
79502     /* Gather the complete text of the CREATE INDEX statement into
79503     ** the zStmt variable
79504     */
79505     if( pStart ){
79506       assert( pEnd!=0 );
79507       /* A named index with an explicit CREATE INDEX statement */
79508       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
79509         onError==OE_None ? "" : " UNIQUE",
79510         pEnd->z - pName->z + 1,
79511         pName->z);
79512     }else{
79513       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
79514       /* zStmt = sqlite3MPrintf(""); */
79515       zStmt = 0;
79516     }
79517
79518     /* Add an entry in sqlite_master for this index
79519     */
79520     sqlite3NestedParse(pParse, 
79521         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
79522         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79523         pIndex->zName,
79524         pTab->zName,
79525         iMem,
79526         zStmt
79527     );
79528     sqlite3DbFree(db, zStmt);
79529
79530     /* Fill the index with data and reparse the schema. Code an OP_Expire
79531     ** to invalidate all pre-compiled statements.
79532     */
79533     if( pTblName ){
79534       sqlite3RefillIndex(pParse, pIndex, iMem);
79535       sqlite3ChangeCookie(pParse, iDb);
79536       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
79537          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 
79538          P4_DYNAMIC);
79539       sqlite3VdbeAddOp1(v, OP_Expire, 0);
79540     }
79541   }
79542
79543   /* When adding an index to the list of indices for a table, make
79544   ** sure all indices labeled OE_Replace come after all those labeled
79545   ** OE_Ignore.  This is necessary for the correct constraint check
79546   ** processing (in sqlite3GenerateConstraintChecks()) as part of
79547   ** UPDATE and INSERT statements.  
79548   */
79549   if( db->init.busy || pTblName==0 ){
79550     if( onError!=OE_Replace || pTab->pIndex==0
79551          || pTab->pIndex->onError==OE_Replace){
79552       pIndex->pNext = pTab->pIndex;
79553       pTab->pIndex = pIndex;
79554     }else{
79555       Index *pOther = pTab->pIndex;
79556       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
79557         pOther = pOther->pNext;
79558       }
79559       pIndex->pNext = pOther->pNext;
79560       pOther->pNext = pIndex;
79561     }
79562     pRet = pIndex;
79563     pIndex = 0;
79564   }
79565
79566   /* Clean up before exiting */
79567 exit_create_index:
79568   if( pIndex ){
79569     sqlite3DbFree(db, pIndex->zColAff);
79570     sqlite3DbFree(db, pIndex);
79571   }
79572   sqlite3ExprListDelete(db, pList);
79573   sqlite3SrcListDelete(db, pTblName);
79574   sqlite3DbFree(db, zName);
79575   return pRet;
79576 }
79577
79578 /*
79579 ** Fill the Index.aiRowEst[] array with default information - information
79580 ** to be used when we have not run the ANALYZE command.
79581 **
79582 ** aiRowEst[0] is suppose to contain the number of elements in the index.
79583 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
79584 ** number of rows in the table that match any particular value of the
79585 ** first column of the index.  aiRowEst[2] is an estimate of the number
79586 ** of rows that match any particular combiniation of the first 2 columns
79587 ** of the index.  And so forth.  It must always be the case that
79588 *
79589 **           aiRowEst[N]<=aiRowEst[N-1]
79590 **           aiRowEst[N]>=1
79591 **
79592 ** Apart from that, we have little to go on besides intuition as to
79593 ** how aiRowEst[] should be initialized.  The numbers generated here
79594 ** are based on typical values found in actual indices.
79595 */
79596 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
79597   unsigned *a = pIdx->aiRowEst;
79598   int i;
79599   unsigned n;
79600   assert( a!=0 );
79601   a[0] = pIdx->pTable->nRowEst;
79602   if( a[0]<10 ) a[0] = 10;
79603   n = 10;
79604   for(i=1; i<=pIdx->nColumn; i++){
79605     a[i] = n;
79606     if( n>5 ) n--;
79607   }
79608   if( pIdx->onError!=OE_None ){
79609     a[pIdx->nColumn] = 1;
79610   }
79611 }
79612
79613 /*
79614 ** This routine will drop an existing named index.  This routine
79615 ** implements the DROP INDEX statement.
79616 */
79617 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
79618   Index *pIndex;
79619   Vdbe *v;
79620   sqlite3 *db = pParse->db;
79621   int iDb;
79622
79623   assert( pParse->nErr==0 );   /* Never called with prior errors */
79624   if( db->mallocFailed ){
79625     goto exit_drop_index;
79626   }
79627   assert( pName->nSrc==1 );
79628   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79629     goto exit_drop_index;
79630   }
79631   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
79632   if( pIndex==0 ){
79633     if( !ifExists ){
79634       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
79635     }else{
79636       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79637     }
79638     pParse->checkSchema = 1;
79639     goto exit_drop_index;
79640   }
79641   if( pIndex->autoIndex ){
79642     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
79643       "or PRIMARY KEY constraint cannot be dropped", 0);
79644     goto exit_drop_index;
79645   }
79646   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79647 #ifndef SQLITE_OMIT_AUTHORIZATION
79648   {
79649     int code = SQLITE_DROP_INDEX;
79650     Table *pTab = pIndex->pTable;
79651     const char *zDb = db->aDb[iDb].zName;
79652     const char *zTab = SCHEMA_TABLE(iDb);
79653     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
79654       goto exit_drop_index;
79655     }
79656     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
79657     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
79658       goto exit_drop_index;
79659     }
79660   }
79661 #endif
79662
79663   /* Generate code to remove the index and from the master table */
79664   v = sqlite3GetVdbe(pParse);
79665   if( v ){
79666     sqlite3BeginWriteOperation(pParse, 1, iDb);
79667     sqlite3NestedParse(pParse,
79668        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
79669        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79670        pIndex->zName
79671     );
79672     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79673       sqlite3NestedParse(pParse,
79674         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
79675         db->aDb[iDb].zName, pIndex->zName
79676       );
79677     }
79678     sqlite3ChangeCookie(pParse, iDb);
79679     destroyRootPage(pParse, pIndex->tnum, iDb);
79680     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
79681   }
79682
79683 exit_drop_index:
79684   sqlite3SrcListDelete(db, pName);
79685 }
79686
79687 /*
79688 ** pArray is a pointer to an array of objects.  Each object in the
79689 ** array is szEntry bytes in size.  This routine allocates a new
79690 ** object on the end of the array.
79691 **
79692 ** *pnEntry is the number of entries already in use.  *pnAlloc is
79693 ** the previously allocated size of the array.  initSize is the
79694 ** suggested initial array size allocation.
79695 **
79696 ** The index of the new entry is returned in *pIdx.
79697 **
79698 ** This routine returns a pointer to the array of objects.  This
79699 ** might be the same as the pArray parameter or it might be a different
79700 ** pointer if the array was resized.
79701 */
79702 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
79703   sqlite3 *db,      /* Connection to notify of malloc failures */
79704   void *pArray,     /* Array of objects.  Might be reallocated */
79705   int szEntry,      /* Size of each object in the array */
79706   int initSize,     /* Suggested initial allocation, in elements */
79707   int *pnEntry,     /* Number of objects currently in use */
79708   int *pnAlloc,     /* Current size of the allocation, in elements */
79709   int *pIdx         /* Write the index of a new slot here */
79710 ){
79711   char *z;
79712   if( *pnEntry >= *pnAlloc ){
79713     void *pNew;
79714     int newSize;
79715     newSize = (*pnAlloc)*2 + initSize;
79716     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
79717     if( pNew==0 ){
79718       *pIdx = -1;
79719       return pArray;
79720     }
79721     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
79722     pArray = pNew;
79723   }
79724   z = (char*)pArray;
79725   memset(&z[*pnEntry * szEntry], 0, szEntry);
79726   *pIdx = *pnEntry;
79727   ++*pnEntry;
79728   return pArray;
79729 }
79730
79731 /*
79732 ** Append a new element to the given IdList.  Create a new IdList if
79733 ** need be.
79734 **
79735 ** A new IdList is returned, or NULL if malloc() fails.
79736 */
79737 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
79738   int i;
79739   if( pList==0 ){
79740     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
79741     if( pList==0 ) return 0;
79742     pList->nAlloc = 0;
79743   }
79744   pList->a = sqlite3ArrayAllocate(
79745       db,
79746       pList->a,
79747       sizeof(pList->a[0]),
79748       5,
79749       &pList->nId,
79750       &pList->nAlloc,
79751       &i
79752   );
79753   if( i<0 ){
79754     sqlite3IdListDelete(db, pList);
79755     return 0;
79756   }
79757   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
79758   return pList;
79759 }
79760
79761 /*
79762 ** Delete an IdList.
79763 */
79764 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
79765   int i;
79766   if( pList==0 ) return;
79767   for(i=0; i<pList->nId; i++){
79768     sqlite3DbFree(db, pList->a[i].zName);
79769   }
79770   sqlite3DbFree(db, pList->a);
79771   sqlite3DbFree(db, pList);
79772 }
79773
79774 /*
79775 ** Return the index in pList of the identifier named zId.  Return -1
79776 ** if not found.
79777 */
79778 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
79779   int i;
79780   if( pList==0 ) return -1;
79781   for(i=0; i<pList->nId; i++){
79782     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
79783   }
79784   return -1;
79785 }
79786
79787 /*
79788 ** Expand the space allocated for the given SrcList object by
79789 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
79790 ** New slots are zeroed.
79791 **
79792 ** For example, suppose a SrcList initially contains two entries: A,B.
79793 ** To append 3 new entries onto the end, do this:
79794 **
79795 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
79796 **
79797 ** After the call above it would contain:  A, B, nil, nil, nil.
79798 ** If the iStart argument had been 1 instead of 2, then the result
79799 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
79800 ** the iStart value would be 0.  The result then would
79801 ** be: nil, nil, nil, A, B.
79802 **
79803 ** If a memory allocation fails the SrcList is unchanged.  The
79804 ** db->mallocFailed flag will be set to true.
79805 */
79806 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
79807   sqlite3 *db,       /* Database connection to notify of OOM errors */
79808   SrcList *pSrc,     /* The SrcList to be enlarged */
79809   int nExtra,        /* Number of new slots to add to pSrc->a[] */
79810   int iStart         /* Index in pSrc->a[] of first new slot */
79811 ){
79812   int i;
79813
79814   /* Sanity checking on calling parameters */
79815   assert( iStart>=0 );
79816   assert( nExtra>=1 );
79817   assert( pSrc!=0 );
79818   assert( iStart<=pSrc->nSrc );
79819
79820   /* Allocate additional space if needed */
79821   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
79822     SrcList *pNew;
79823     int nAlloc = pSrc->nSrc+nExtra;
79824     int nGot;
79825     pNew = sqlite3DbRealloc(db, pSrc,
79826                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
79827     if( pNew==0 ){
79828       assert( db->mallocFailed );
79829       return pSrc;
79830     }
79831     pSrc = pNew;
79832     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
79833     pSrc->nAlloc = (u16)nGot;
79834   }
79835
79836   /* Move existing slots that come after the newly inserted slots
79837   ** out of the way */
79838   for(i=pSrc->nSrc-1; i>=iStart; i--){
79839     pSrc->a[i+nExtra] = pSrc->a[i];
79840   }
79841   pSrc->nSrc += (i16)nExtra;
79842
79843   /* Zero the newly allocated slots */
79844   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
79845   for(i=iStart; i<iStart+nExtra; i++){
79846     pSrc->a[i].iCursor = -1;
79847   }
79848
79849   /* Return a pointer to the enlarged SrcList */
79850   return pSrc;
79851 }
79852
79853
79854 /*
79855 ** Append a new table name to the given SrcList.  Create a new SrcList if
79856 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
79857 **
79858 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
79859 ** SrcList might be the same as the SrcList that was input or it might be
79860 ** a new one.  If an OOM error does occurs, then the prior value of pList
79861 ** that is input to this routine is automatically freed.
79862 **
79863 ** If pDatabase is not null, it means that the table has an optional
79864 ** database name prefix.  Like this:  "database.table".  The pDatabase
79865 ** points to the table name and the pTable points to the database name.
79866 ** The SrcList.a[].zName field is filled with the table name which might
79867 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
79868 ** SrcList.a[].zDatabase is filled with the database name from pTable,
79869 ** or with NULL if no database is specified.
79870 **
79871 ** In other words, if call like this:
79872 **
79873 **         sqlite3SrcListAppend(D,A,B,0);
79874 **
79875 ** Then B is a table name and the database name is unspecified.  If called
79876 ** like this:
79877 **
79878 **         sqlite3SrcListAppend(D,A,B,C);
79879 **
79880 ** Then C is the table name and B is the database name.  If C is defined
79881 ** then so is B.  In other words, we never have a case where:
79882 **
79883 **         sqlite3SrcListAppend(D,A,0,C);
79884 **
79885 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
79886 ** before being added to the SrcList.
79887 */
79888 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
79889   sqlite3 *db,        /* Connection to notify of malloc failures */
79890   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
79891   Token *pTable,      /* Table to append */
79892   Token *pDatabase    /* Database of the table */
79893 ){
79894   struct SrcList_item *pItem;
79895   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
79896   if( pList==0 ){
79897     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
79898     if( pList==0 ) return 0;
79899     pList->nAlloc = 1;
79900   }
79901   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
79902   if( db->mallocFailed ){
79903     sqlite3SrcListDelete(db, pList);
79904     return 0;
79905   }
79906   pItem = &pList->a[pList->nSrc-1];
79907   if( pDatabase && pDatabase->z==0 ){
79908     pDatabase = 0;
79909   }
79910   if( pDatabase ){
79911     Token *pTemp = pDatabase;
79912     pDatabase = pTable;
79913     pTable = pTemp;
79914   }
79915   pItem->zName = sqlite3NameFromToken(db, pTable);
79916   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
79917   return pList;
79918 }
79919
79920 /*
79921 ** Assign VdbeCursor index numbers to all tables in a SrcList
79922 */
79923 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
79924   int i;
79925   struct SrcList_item *pItem;
79926   assert(pList || pParse->db->mallocFailed );
79927   if( pList ){
79928     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
79929       if( pItem->iCursor>=0 ) break;
79930       pItem->iCursor = pParse->nTab++;
79931       if( pItem->pSelect ){
79932         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
79933       }
79934     }
79935   }
79936 }
79937
79938 /*
79939 ** Delete an entire SrcList including all its substructure.
79940 */
79941 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
79942   int i;
79943   struct SrcList_item *pItem;
79944   if( pList==0 ) return;
79945   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
79946     sqlite3DbFree(db, pItem->zDatabase);
79947     sqlite3DbFree(db, pItem->zName);
79948     sqlite3DbFree(db, pItem->zAlias);
79949     sqlite3DbFree(db, pItem->zIndex);
79950     sqlite3DeleteTable(db, pItem->pTab);
79951     sqlite3SelectDelete(db, pItem->pSelect);
79952     sqlite3ExprDelete(db, pItem->pOn);
79953     sqlite3IdListDelete(db, pItem->pUsing);
79954   }
79955   sqlite3DbFree(db, pList);
79956 }
79957
79958 /*
79959 ** This routine is called by the parser to add a new term to the
79960 ** end of a growing FROM clause.  The "p" parameter is the part of
79961 ** the FROM clause that has already been constructed.  "p" is NULL
79962 ** if this is the first term of the FROM clause.  pTable and pDatabase
79963 ** are the name of the table and database named in the FROM clause term.
79964 ** pDatabase is NULL if the database name qualifier is missing - the
79965 ** usual case.  If the term has a alias, then pAlias points to the
79966 ** alias token.  If the term is a subquery, then pSubquery is the
79967 ** SELECT statement that the subquery encodes.  The pTable and
79968 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
79969 ** parameters are the content of the ON and USING clauses.
79970 **
79971 ** Return a new SrcList which encodes is the FROM with the new
79972 ** term added.
79973 */
79974 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
79975   Parse *pParse,          /* Parsing context */
79976   SrcList *p,             /* The left part of the FROM clause already seen */
79977   Token *pTable,          /* Name of the table to add to the FROM clause */
79978   Token *pDatabase,       /* Name of the database containing pTable */
79979   Token *pAlias,          /* The right-hand side of the AS subexpression */
79980   Select *pSubquery,      /* A subquery used in place of a table name */
79981   Expr *pOn,              /* The ON clause of a join */
79982   IdList *pUsing          /* The USING clause of a join */
79983 ){
79984   struct SrcList_item *pItem;
79985   sqlite3 *db = pParse->db;
79986   if( !p && (pOn || pUsing) ){
79987     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
79988       (pOn ? "ON" : "USING")
79989     );
79990     goto append_from_error;
79991   }
79992   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
79993   if( p==0 || NEVER(p->nSrc==0) ){
79994     goto append_from_error;
79995   }
79996   pItem = &p->a[p->nSrc-1];
79997   assert( pAlias!=0 );
79998   if( pAlias->n ){
79999     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
80000   }
80001   pItem->pSelect = pSubquery;
80002   pItem->pOn = pOn;
80003   pItem->pUsing = pUsing;
80004   return p;
80005
80006  append_from_error:
80007   assert( p==0 );
80008   sqlite3ExprDelete(db, pOn);
80009   sqlite3IdListDelete(db, pUsing);
80010   sqlite3SelectDelete(db, pSubquery);
80011   return 0;
80012 }
80013
80014 /*
80015 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
80016 ** element of the source-list passed as the second argument.
80017 */
80018 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80019   assert( pIndexedBy!=0 );
80020   if( p && ALWAYS(p->nSrc>0) ){
80021     struct SrcList_item *pItem = &p->a[p->nSrc-1];
80022     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80023     if( pIndexedBy->n==1 && !pIndexedBy->z ){
80024       /* A "NOT INDEXED" clause was supplied. See parse.y 
80025       ** construct "indexed_opt" for details. */
80026       pItem->notIndexed = 1;
80027     }else{
80028       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80029     }
80030   }
80031 }
80032
80033 /*
80034 ** When building up a FROM clause in the parser, the join operator
80035 ** is initially attached to the left operand.  But the code generator
80036 ** expects the join operator to be on the right operand.  This routine
80037 ** Shifts all join operators from left to right for an entire FROM
80038 ** clause.
80039 **
80040 ** Example: Suppose the join is like this:
80041 **
80042 **           A natural cross join B
80043 **
80044 ** The operator is "natural cross join".  The A and B operands are stored
80045 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
80046 ** operator with A.  This routine shifts that operator over to B.
80047 */
80048 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80049   if( p && p->a ){
80050     int i;
80051     for(i=p->nSrc-1; i>0; i--){
80052       p->a[i].jointype = p->a[i-1].jointype;
80053     }
80054     p->a[0].jointype = 0;
80055   }
80056 }
80057
80058 /*
80059 ** Begin a transaction
80060 */
80061 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80062   sqlite3 *db;
80063   Vdbe *v;
80064   int i;
80065
80066   assert( pParse!=0 );
80067   db = pParse->db;
80068   assert( db!=0 );
80069 /*  if( db->aDb[0].pBt==0 ) return; */
80070   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80071     return;
80072   }
80073   v = sqlite3GetVdbe(pParse);
80074   if( !v ) return;
80075   if( type!=TK_DEFERRED ){
80076     for(i=0; i<db->nDb; i++){
80077       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80078       sqlite3VdbeUsesBtree(v, i);
80079     }
80080   }
80081   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80082 }
80083
80084 /*
80085 ** Commit a transaction
80086 */
80087 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80088   sqlite3 *db;
80089   Vdbe *v;
80090
80091   assert( pParse!=0 );
80092   db = pParse->db;
80093   assert( db!=0 );
80094 /*  if( db->aDb[0].pBt==0 ) return; */
80095   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80096     return;
80097   }
80098   v = sqlite3GetVdbe(pParse);
80099   if( v ){
80100     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80101   }
80102 }
80103
80104 /*
80105 ** Rollback a transaction
80106 */
80107 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80108   sqlite3 *db;
80109   Vdbe *v;
80110
80111   assert( pParse!=0 );
80112   db = pParse->db;
80113   assert( db!=0 );
80114 /*  if( db->aDb[0].pBt==0 ) return; */
80115   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80116     return;
80117   }
80118   v = sqlite3GetVdbe(pParse);
80119   if( v ){
80120     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80121   }
80122 }
80123
80124 /*
80125 ** This function is called by the parser when it parses a command to create,
80126 ** release or rollback an SQL savepoint. 
80127 */
80128 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80129   char *zName = sqlite3NameFromToken(pParse->db, pName);
80130   if( zName ){
80131     Vdbe *v = sqlite3GetVdbe(pParse);
80132 #ifndef SQLITE_OMIT_AUTHORIZATION
80133     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80134     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80135 #endif
80136     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80137       sqlite3DbFree(pParse->db, zName);
80138       return;
80139     }
80140     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80141   }
80142 }
80143
80144 /*
80145 ** Make sure the TEMP database is open and available for use.  Return
80146 ** the number of errors.  Leave any error messages in the pParse structure.
80147 */
80148 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80149   sqlite3 *db = pParse->db;
80150   if( db->aDb[1].pBt==0 && !pParse->explain ){
80151     int rc;
80152     Btree *pBt;
80153     static const int flags = 
80154           SQLITE_OPEN_READWRITE |
80155           SQLITE_OPEN_CREATE |
80156           SQLITE_OPEN_EXCLUSIVE |
80157           SQLITE_OPEN_DELETEONCLOSE |
80158           SQLITE_OPEN_TEMP_DB;
80159
80160     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
80161     if( rc!=SQLITE_OK ){
80162       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80163         "file for storing temporary tables");
80164       pParse->rc = rc;
80165       return 1;
80166     }
80167     db->aDb[1].pBt = pBt;
80168     assert( db->aDb[1].pSchema );
80169     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80170       db->mallocFailed = 1;
80171       return 1;
80172     }
80173   }
80174   return 0;
80175 }
80176
80177 /*
80178 ** Generate VDBE code that will verify the schema cookie and start
80179 ** a read-transaction for all named database files.
80180 **
80181 ** It is important that all schema cookies be verified and all
80182 ** read transactions be started before anything else happens in
80183 ** the VDBE program.  But this routine can be called after much other
80184 ** code has been generated.  So here is what we do:
80185 **
80186 ** The first time this routine is called, we code an OP_Goto that
80187 ** will jump to a subroutine at the end of the program.  Then we
80188 ** record every database that needs its schema verified in the
80189 ** pParse->cookieMask field.  Later, after all other code has been
80190 ** generated, the subroutine that does the cookie verifications and
80191 ** starts the transactions will be coded and the OP_Goto P2 value
80192 ** will be made to point to that subroutine.  The generation of the
80193 ** cookie verification subroutine code happens in sqlite3FinishCoding().
80194 **
80195 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80196 ** schema on any databases.  This can be used to position the OP_Goto
80197 ** early in the code, before we know if any database tables will be used.
80198 */
80199 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80200   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80201
80202   if( pToplevel->cookieGoto==0 ){
80203     Vdbe *v = sqlite3GetVdbe(pToplevel);
80204     if( v==0 ) return;  /* This only happens if there was a prior error */
80205     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80206   }
80207   if( iDb>=0 ){
80208     sqlite3 *db = pToplevel->db;
80209     yDbMask mask;
80210
80211     assert( iDb<db->nDb );
80212     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80213     assert( iDb<SQLITE_MAX_ATTACHED+2 );
80214     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80215     mask = ((yDbMask)1)<<iDb;
80216     if( (pToplevel->cookieMask & mask)==0 ){
80217       pToplevel->cookieMask |= mask;
80218       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80219       if( !OMIT_TEMPDB && iDb==1 ){
80220         sqlite3OpenTempDatabase(pToplevel);
80221       }
80222     }
80223   }
80224 }
80225
80226 /*
80227 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
80228 ** attached database. Otherwise, invoke it for the database named zDb only.
80229 */
80230 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80231   sqlite3 *db = pParse->db;
80232   int i;
80233   for(i=0; i<db->nDb; i++){
80234     Db *pDb = &db->aDb[i];
80235     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80236       sqlite3CodeVerifySchema(pParse, i);
80237     }
80238   }
80239 }
80240
80241 /*
80242 ** Generate VDBE code that prepares for doing an operation that
80243 ** might change the database.
80244 **
80245 ** This routine starts a new transaction if we are not already within
80246 ** a transaction.  If we are already within a transaction, then a checkpoint
80247 ** is set if the setStatement parameter is true.  A checkpoint should
80248 ** be set for operations that might fail (due to a constraint) part of
80249 ** the way through and which will need to undo some writes without having to
80250 ** rollback the whole transaction.  For operations where all constraints
80251 ** can be checked before any changes are made to the database, it is never
80252 ** necessary to undo a write and the checkpoint should not be set.
80253 */
80254 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80255   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80256   sqlite3CodeVerifySchema(pParse, iDb);
80257   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80258   pToplevel->isMultiWrite |= setStatement;
80259 }
80260
80261 /*
80262 ** Indicate that the statement currently under construction might write
80263 ** more than one entry (example: deleting one row then inserting another,
80264 ** inserting multiple rows in a table, or inserting a row and index entries.)
80265 ** If an abort occurs after some of these writes have completed, then it will
80266 ** be necessary to undo the completed writes.
80267 */
80268 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80269   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80270   pToplevel->isMultiWrite = 1;
80271 }
80272
80273 /* 
80274 ** The code generator calls this routine if is discovers that it is
80275 ** possible to abort a statement prior to completion.  In order to 
80276 ** perform this abort without corrupting the database, we need to make
80277 ** sure that the statement is protected by a statement transaction.
80278 **
80279 ** Technically, we only need to set the mayAbort flag if the
80280 ** isMultiWrite flag was previously set.  There is a time dependency
80281 ** such that the abort must occur after the multiwrite.  This makes
80282 ** some statements involving the REPLACE conflict resolution algorithm
80283 ** go a little faster.  But taking advantage of this time dependency
80284 ** makes it more difficult to prove that the code is correct (in 
80285 ** particular, it prevents us from writing an effective
80286 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
80287 ** to take the safe route and skip the optimization.
80288 */
80289 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80290   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80291   pToplevel->mayAbort = 1;
80292 }
80293
80294 /*
80295 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80296 ** error. The onError parameter determines which (if any) of the statement
80297 ** and/or current transaction is rolled back.
80298 */
80299 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80300   Vdbe *v = sqlite3GetVdbe(pParse);
80301   if( onError==OE_Abort ){
80302     sqlite3MayAbort(pParse);
80303   }
80304   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80305 }
80306
80307 /*
80308 ** Check to see if pIndex uses the collating sequence pColl.  Return
80309 ** true if it does and false if it does not.
80310 */
80311 #ifndef SQLITE_OMIT_REINDEX
80312 static int collationMatch(const char *zColl, Index *pIndex){
80313   int i;
80314   assert( zColl!=0 );
80315   for(i=0; i<pIndex->nColumn; i++){
80316     const char *z = pIndex->azColl[i];
80317     assert( z!=0 );
80318     if( 0==sqlite3StrICmp(z, zColl) ){
80319       return 1;
80320     }
80321   }
80322   return 0;
80323 }
80324 #endif
80325
80326 /*
80327 ** Recompute all indices of pTab that use the collating sequence pColl.
80328 ** If pColl==0 then recompute all indices of pTab.
80329 */
80330 #ifndef SQLITE_OMIT_REINDEX
80331 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80332   Index *pIndex;              /* An index associated with pTab */
80333
80334   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80335     if( zColl==0 || collationMatch(zColl, pIndex) ){
80336       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80337       sqlite3BeginWriteOperation(pParse, 0, iDb);
80338       sqlite3RefillIndex(pParse, pIndex, -1);
80339     }
80340   }
80341 }
80342 #endif
80343
80344 /*
80345 ** Recompute all indices of all tables in all databases where the
80346 ** indices use the collating sequence pColl.  If pColl==0 then recompute
80347 ** all indices everywhere.
80348 */
80349 #ifndef SQLITE_OMIT_REINDEX
80350 static void reindexDatabases(Parse *pParse, char const *zColl){
80351   Db *pDb;                    /* A single database */
80352   int iDb;                    /* The database index number */
80353   sqlite3 *db = pParse->db;   /* The database connection */
80354   HashElem *k;                /* For looping over tables in pDb */
80355   Table *pTab;                /* A table in the database */
80356
80357   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
80358   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80359     assert( pDb!=0 );
80360     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
80361       pTab = (Table*)sqliteHashData(k);
80362       reindexTable(pParse, pTab, zColl);
80363     }
80364   }
80365 }
80366 #endif
80367
80368 /*
80369 ** Generate code for the REINDEX command.
80370 **
80371 **        REINDEX                            -- 1
80372 **        REINDEX  <collation>               -- 2
80373 **        REINDEX  ?<database>.?<tablename>  -- 3
80374 **        REINDEX  ?<database>.?<indexname>  -- 4
80375 **
80376 ** Form 1 causes all indices in all attached databases to be rebuilt.
80377 ** Form 2 rebuilds all indices in all databases that use the named
80378 ** collating function.  Forms 3 and 4 rebuild the named index or all
80379 ** indices associated with the named table.
80380 */
80381 #ifndef SQLITE_OMIT_REINDEX
80382 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
80383   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
80384   char *z;                    /* Name of a table or index */
80385   const char *zDb;            /* Name of the database */
80386   Table *pTab;                /* A table in the database */
80387   Index *pIndex;              /* An index associated with pTab */
80388   int iDb;                    /* The database index number */
80389   sqlite3 *db = pParse->db;   /* The database connection */
80390   Token *pObjName;            /* Name of the table or index to be reindexed */
80391
80392   /* Read the database schema. If an error occurs, leave an error message
80393   ** and code in pParse and return NULL. */
80394   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80395     return;
80396   }
80397
80398   if( pName1==0 ){
80399     reindexDatabases(pParse, 0);
80400     return;
80401   }else if( NEVER(pName2==0) || pName2->z==0 ){
80402     char *zColl;
80403     assert( pName1->z );
80404     zColl = sqlite3NameFromToken(pParse->db, pName1);
80405     if( !zColl ) return;
80406     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80407     if( pColl ){
80408       reindexDatabases(pParse, zColl);
80409       sqlite3DbFree(db, zColl);
80410       return;
80411     }
80412     sqlite3DbFree(db, zColl);
80413   }
80414   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
80415   if( iDb<0 ) return;
80416   z = sqlite3NameFromToken(db, pObjName);
80417   if( z==0 ) return;
80418   zDb = db->aDb[iDb].zName;
80419   pTab = sqlite3FindTable(db, z, zDb);
80420   if( pTab ){
80421     reindexTable(pParse, pTab, 0);
80422     sqlite3DbFree(db, z);
80423     return;
80424   }
80425   pIndex = sqlite3FindIndex(db, z, zDb);
80426   sqlite3DbFree(db, z);
80427   if( pIndex ){
80428     sqlite3BeginWriteOperation(pParse, 0, iDb);
80429     sqlite3RefillIndex(pParse, pIndex, -1);
80430     return;
80431   }
80432   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
80433 }
80434 #endif
80435
80436 /*
80437 ** Return a dynamicly allocated KeyInfo structure that can be used
80438 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
80439 **
80440 ** If successful, a pointer to the new structure is returned. In this case
80441 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
80442 ** pointer. If an error occurs (out of memory or missing collation 
80443 ** sequence), NULL is returned and the state of pParse updated to reflect
80444 ** the error.
80445 */
80446 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
80447   int i;
80448   int nCol = pIdx->nColumn;
80449   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
80450   sqlite3 *db = pParse->db;
80451   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
80452
80453   if( pKey ){
80454     pKey->db = pParse->db;
80455     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
80456     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
80457     for(i=0; i<nCol; i++){
80458       char *zColl = pIdx->azColl[i];
80459       assert( zColl );
80460       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
80461       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
80462     }
80463     pKey->nField = (u16)nCol;
80464   }
80465
80466   if( pParse->nErr ){
80467     sqlite3DbFree(db, pKey);
80468     pKey = 0;
80469   }
80470   return pKey;
80471 }
80472
80473 /************** End of build.c ***********************************************/
80474 /************** Begin file callback.c ****************************************/
80475 /*
80476 ** 2005 May 23 
80477 **
80478 ** The author disclaims copyright to this source code.  In place of
80479 ** a legal notice, here is a blessing:
80480 **
80481 **    May you do good and not evil.
80482 **    May you find forgiveness for yourself and forgive others.
80483 **    May you share freely, never taking more than you give.
80484 **
80485 *************************************************************************
80486 **
80487 ** This file contains functions used to access the internal hash tables
80488 ** of user defined functions and collation sequences.
80489 */
80490
80491
80492 /*
80493 ** Invoke the 'collation needed' callback to request a collation sequence
80494 ** in the encoding enc of name zName, length nName.
80495 */
80496 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
80497   assert( !db->xCollNeeded || !db->xCollNeeded16 );
80498   if( db->xCollNeeded ){
80499     char *zExternal = sqlite3DbStrDup(db, zName);
80500     if( !zExternal ) return;
80501     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
80502     sqlite3DbFree(db, zExternal);
80503   }
80504 #ifndef SQLITE_OMIT_UTF16
80505   if( db->xCollNeeded16 ){
80506     char const *zExternal;
80507     sqlite3_value *pTmp = sqlite3ValueNew(db);
80508     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
80509     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
80510     if( zExternal ){
80511       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
80512     }
80513     sqlite3ValueFree(pTmp);
80514   }
80515 #endif
80516 }
80517
80518 /*
80519 ** This routine is called if the collation factory fails to deliver a
80520 ** collation function in the best encoding but there may be other versions
80521 ** of this collation function (for other text encodings) available. Use one
80522 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
80523 ** possible.
80524 */
80525 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
80526   CollSeq *pColl2;
80527   char *z = pColl->zName;
80528   int i;
80529   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
80530   for(i=0; i<3; i++){
80531     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
80532     if( pColl2->xCmp!=0 ){
80533       memcpy(pColl, pColl2, sizeof(CollSeq));
80534       pColl->xDel = 0;         /* Do not copy the destructor */
80535       return SQLITE_OK;
80536     }
80537   }
80538   return SQLITE_ERROR;
80539 }
80540
80541 /*
80542 ** This function is responsible for invoking the collation factory callback
80543 ** or substituting a collation sequence of a different encoding when the
80544 ** requested collation sequence is not available in the desired encoding.
80545 ** 
80546 ** If it is not NULL, then pColl must point to the database native encoding 
80547 ** collation sequence with name zName, length nName.
80548 **
80549 ** The return value is either the collation sequence to be used in database
80550 ** db for collation type name zName, length nName, or NULL, if no collation
80551 ** sequence can be found.
80552 **
80553 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
80554 */
80555 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
80556   sqlite3* db,          /* The database connection */
80557   u8 enc,               /* The desired encoding for the collating sequence */
80558   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
80559   const char *zName     /* Collating sequence name */
80560 ){
80561   CollSeq *p;
80562
80563   p = pColl;
80564   if( !p ){
80565     p = sqlite3FindCollSeq(db, enc, zName, 0);
80566   }
80567   if( !p || !p->xCmp ){
80568     /* No collation sequence of this type for this encoding is registered.
80569     ** Call the collation factory to see if it can supply us with one.
80570     */
80571     callCollNeeded(db, enc, zName);
80572     p = sqlite3FindCollSeq(db, enc, zName, 0);
80573   }
80574   if( p && !p->xCmp && synthCollSeq(db, p) ){
80575     p = 0;
80576   }
80577   assert( !p || p->xCmp );
80578   return p;
80579 }
80580
80581 /*
80582 ** This routine is called on a collation sequence before it is used to
80583 ** check that it is defined. An undefined collation sequence exists when
80584 ** a database is loaded that contains references to collation sequences
80585 ** that have not been defined by sqlite3_create_collation() etc.
80586 **
80587 ** If required, this routine calls the 'collation needed' callback to
80588 ** request a definition of the collating sequence. If this doesn't work, 
80589 ** an equivalent collating sequence that uses a text encoding different
80590 ** from the main database is substituted, if one is available.
80591 */
80592 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
80593   if( pColl ){
80594     const char *zName = pColl->zName;
80595     sqlite3 *db = pParse->db;
80596     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
80597     if( !p ){
80598       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80599       pParse->nErr++;
80600       return SQLITE_ERROR;
80601     }
80602     assert( p==pColl );
80603   }
80604   return SQLITE_OK;
80605 }
80606
80607
80608
80609 /*
80610 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
80611 ** specified by zName and nName is not found and parameter 'create' is
80612 ** true, then create a new entry. Otherwise return NULL.
80613 **
80614 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
80615 ** array of three CollSeq structures. The first is the collation sequence
80616 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
80617 **
80618 ** Stored immediately after the three collation sequences is a copy of
80619 ** the collation sequence name. A pointer to this string is stored in
80620 ** each collation sequence structure.
80621 */
80622 static CollSeq *findCollSeqEntry(
80623   sqlite3 *db,          /* Database connection */
80624   const char *zName,    /* Name of the collating sequence */
80625   int create            /* Create a new entry if true */
80626 ){
80627   CollSeq *pColl;
80628   int nName = sqlite3Strlen30(zName);
80629   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
80630
80631   if( 0==pColl && create ){
80632     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
80633     if( pColl ){
80634       CollSeq *pDel = 0;
80635       pColl[0].zName = (char*)&pColl[3];
80636       pColl[0].enc = SQLITE_UTF8;
80637       pColl[1].zName = (char*)&pColl[3];
80638       pColl[1].enc = SQLITE_UTF16LE;
80639       pColl[2].zName = (char*)&pColl[3];
80640       pColl[2].enc = SQLITE_UTF16BE;
80641       memcpy(pColl[0].zName, zName, nName);
80642       pColl[0].zName[nName] = 0;
80643       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
80644
80645       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
80646       ** return the pColl pointer to be deleted (because it wasn't added
80647       ** to the hash table).
80648       */
80649       assert( pDel==0 || pDel==pColl );
80650       if( pDel!=0 ){
80651         db->mallocFailed = 1;
80652         sqlite3DbFree(db, pDel);
80653         pColl = 0;
80654       }
80655     }
80656   }
80657   return pColl;
80658 }
80659
80660 /*
80661 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
80662 ** Return the CollSeq* pointer for the collation sequence named zName
80663 ** for the encoding 'enc' from the database 'db'.
80664 **
80665 ** If the entry specified is not found and 'create' is true, then create a
80666 ** new entry.  Otherwise return NULL.
80667 **
80668 ** A separate function sqlite3LocateCollSeq() is a wrapper around
80669 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
80670 ** if necessary and generates an error message if the collating sequence
80671 ** cannot be found.
80672 **
80673 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
80674 */
80675 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
80676   sqlite3 *db,
80677   u8 enc,
80678   const char *zName,
80679   int create
80680 ){
80681   CollSeq *pColl;
80682   if( zName ){
80683     pColl = findCollSeqEntry(db, zName, create);
80684   }else{
80685     pColl = db->pDfltColl;
80686   }
80687   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
80688   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
80689   if( pColl ) pColl += enc-1;
80690   return pColl;
80691 }
80692
80693 /* During the search for the best function definition, this procedure
80694 ** is called to test how well the function passed as the first argument
80695 ** matches the request for a function with nArg arguments in a system
80696 ** that uses encoding enc. The value returned indicates how well the
80697 ** request is matched. A higher value indicates a better match.
80698 **
80699 ** The returned value is always between 0 and 6, as follows:
80700 **
80701 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
80702 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
80703 **    encoding is requested, or vice versa.
80704 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
80705 **    requested, or vice versa.
80706 ** 3: A variable arguments function using the same text encoding.
80707 ** 4: A function with the exact number of arguments requested that
80708 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
80709 ** 5: A function with the exact number of arguments requested that
80710 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
80711 ** 6: An exact match.
80712 **
80713 */
80714 static int matchQuality(FuncDef *p, int nArg, u8 enc){
80715   int match = 0;
80716   if( p->nArg==-1 || p->nArg==nArg 
80717    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
80718   ){
80719     match = 1;
80720     if( p->nArg==nArg || nArg==-1 ){
80721       match = 4;
80722     }
80723     if( enc==p->iPrefEnc ){
80724       match += 2;
80725     }
80726     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
80727              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
80728       match += 1;
80729     }
80730   }
80731   return match;
80732 }
80733
80734 /*
80735 ** Search a FuncDefHash for a function with the given name.  Return
80736 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
80737 */
80738 static FuncDef *functionSearch(
80739   FuncDefHash *pHash,  /* Hash table to search */
80740   int h,               /* Hash of the name */
80741   const char *zFunc,   /* Name of function */
80742   int nFunc            /* Number of bytes in zFunc */
80743 ){
80744   FuncDef *p;
80745   for(p=pHash->a[h]; p; p=p->pHash){
80746     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
80747       return p;
80748     }
80749   }
80750   return 0;
80751 }
80752
80753 /*
80754 ** Insert a new FuncDef into a FuncDefHash hash table.
80755 */
80756 SQLITE_PRIVATE void sqlite3FuncDefInsert(
80757   FuncDefHash *pHash,  /* The hash table into which to insert */
80758   FuncDef *pDef        /* The function definition to insert */
80759 ){
80760   FuncDef *pOther;
80761   int nName = sqlite3Strlen30(pDef->zName);
80762   u8 c1 = (u8)pDef->zName[0];
80763   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
80764   pOther = functionSearch(pHash, h, pDef->zName, nName);
80765   if( pOther ){
80766     assert( pOther!=pDef && pOther->pNext!=pDef );
80767     pDef->pNext = pOther->pNext;
80768     pOther->pNext = pDef;
80769   }else{
80770     pDef->pNext = 0;
80771     pDef->pHash = pHash->a[h];
80772     pHash->a[h] = pDef;
80773   }
80774 }
80775   
80776   
80777
80778 /*
80779 ** Locate a user function given a name, a number of arguments and a flag
80780 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
80781 ** pointer to the FuncDef structure that defines that function, or return
80782 ** NULL if the function does not exist.
80783 **
80784 ** If the createFlag argument is true, then a new (blank) FuncDef
80785 ** structure is created and liked into the "db" structure if a
80786 ** no matching function previously existed.  When createFlag is true
80787 ** and the nArg parameter is -1, then only a function that accepts
80788 ** any number of arguments will be returned.
80789 **
80790 ** If createFlag is false and nArg is -1, then the first valid
80791 ** function found is returned.  A function is valid if either xFunc
80792 ** or xStep is non-zero.
80793 **
80794 ** If createFlag is false, then a function with the required name and
80795 ** number of arguments may be returned even if the eTextRep flag does not
80796 ** match that requested.
80797 */
80798 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
80799   sqlite3 *db,       /* An open database */
80800   const char *zName, /* Name of the function.  Not null-terminated */
80801   int nName,         /* Number of characters in the name */
80802   int nArg,          /* Number of arguments.  -1 means any number */
80803   u8 enc,            /* Preferred text encoding */
80804   int createFlag     /* Create new entry if true and does not otherwise exist */
80805 ){
80806   FuncDef *p;         /* Iterator variable */
80807   FuncDef *pBest = 0; /* Best match found so far */
80808   int bestScore = 0;  /* Score of best match */
80809   int h;              /* Hash value */
80810
80811
80812   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
80813   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
80814
80815   /* First search for a match amongst the application-defined functions.
80816   */
80817   p = functionSearch(&db->aFunc, h, zName, nName);
80818   while( p ){
80819     int score = matchQuality(p, nArg, enc);
80820     if( score>bestScore ){
80821       pBest = p;
80822       bestScore = score;
80823     }
80824     p = p->pNext;
80825   }
80826
80827   /* If no match is found, search the built-in functions.
80828   **
80829   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
80830   ** functions even if a prior app-defined function was found.  And give
80831   ** priority to built-in functions.
80832   **
80833   ** Except, if createFlag is true, that means that we are trying to
80834   ** install a new function.  Whatever FuncDef structure is returned it will
80835   ** have fields overwritten with new information appropriate for the
80836   ** new function.  But the FuncDefs for built-in functions are read-only.
80837   ** So we must not search for built-ins when creating a new function.
80838   */ 
80839   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
80840     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80841     bestScore = 0;
80842     p = functionSearch(pHash, h, zName, nName);
80843     while( p ){
80844       int score = matchQuality(p, nArg, enc);
80845       if( score>bestScore ){
80846         pBest = p;
80847         bestScore = score;
80848       }
80849       p = p->pNext;
80850     }
80851   }
80852
80853   /* If the createFlag parameter is true and the search did not reveal an
80854   ** exact match for the name, number of arguments and encoding, then add a
80855   ** new entry to the hash table and return it.
80856   */
80857   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
80858       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
80859     pBest->zName = (char *)&pBest[1];
80860     pBest->nArg = (u16)nArg;
80861     pBest->iPrefEnc = enc;
80862     memcpy(pBest->zName, zName, nName);
80863     pBest->zName[nName] = 0;
80864     sqlite3FuncDefInsert(&db->aFunc, pBest);
80865   }
80866
80867   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
80868     return pBest;
80869   }
80870   return 0;
80871 }
80872
80873 /*
80874 ** Free all resources held by the schema structure. The void* argument points
80875 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
80876 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
80877 ** of the schema hash tables).
80878 **
80879 ** The Schema.cache_size variable is not cleared.
80880 */
80881 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
80882   Hash temp1;
80883   Hash temp2;
80884   HashElem *pElem;
80885   Schema *pSchema = (Schema *)p;
80886
80887   temp1 = pSchema->tblHash;
80888   temp2 = pSchema->trigHash;
80889   sqlite3HashInit(&pSchema->trigHash);
80890   sqlite3HashClear(&pSchema->idxHash);
80891   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
80892     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
80893   }
80894   sqlite3HashClear(&temp2);
80895   sqlite3HashInit(&pSchema->tblHash);
80896   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
80897     Table *pTab = sqliteHashData(pElem);
80898     sqlite3DeleteTable(0, pTab);
80899   }
80900   sqlite3HashClear(&temp1);
80901   sqlite3HashClear(&pSchema->fkeyHash);
80902   pSchema->pSeqTab = 0;
80903   if( pSchema->flags & DB_SchemaLoaded ){
80904     pSchema->iGeneration++;
80905     pSchema->flags &= ~DB_SchemaLoaded;
80906   }
80907 }
80908
80909 /*
80910 ** Find and return the schema associated with a BTree.  Create
80911 ** a new one if necessary.
80912 */
80913 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
80914   Schema * p;
80915   if( pBt ){
80916     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
80917   }else{
80918     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
80919   }
80920   if( !p ){
80921     db->mallocFailed = 1;
80922   }else if ( 0==p->file_format ){
80923     sqlite3HashInit(&p->tblHash);
80924     sqlite3HashInit(&p->idxHash);
80925     sqlite3HashInit(&p->trigHash);
80926     sqlite3HashInit(&p->fkeyHash);
80927     p->enc = SQLITE_UTF8;
80928   }
80929   return p;
80930 }
80931
80932 /************** End of callback.c ********************************************/
80933 /************** Begin file delete.c ******************************************/
80934 /*
80935 ** 2001 September 15
80936 **
80937 ** The author disclaims copyright to this source code.  In place of
80938 ** a legal notice, here is a blessing:
80939 **
80940 **    May you do good and not evil.
80941 **    May you find forgiveness for yourself and forgive others.
80942 **    May you share freely, never taking more than you give.
80943 **
80944 *************************************************************************
80945 ** This file contains C code routines that are called by the parser
80946 ** in order to generate code for DELETE FROM statements.
80947 */
80948
80949 /*
80950 ** While a SrcList can in general represent multiple tables and subqueries
80951 ** (as in the FROM clause of a SELECT statement) in this case it contains
80952 ** the name of a single table, as one might find in an INSERT, DELETE,
80953 ** or UPDATE statement.  Look up that table in the symbol table and
80954 ** return a pointer.  Set an error message and return NULL if the table 
80955 ** name is not found or if any other error occurs.
80956 **
80957 ** The following fields are initialized appropriate in pSrc:
80958 **
80959 **    pSrc->a[0].pTab       Pointer to the Table object
80960 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
80961 **
80962 */
80963 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
80964   struct SrcList_item *pItem = pSrc->a;
80965   Table *pTab;
80966   assert( pItem && pSrc->nSrc==1 );
80967   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
80968   sqlite3DeleteTable(pParse->db, pItem->pTab);
80969   pItem->pTab = pTab;
80970   if( pTab ){
80971     pTab->nRef++;
80972   }
80973   if( sqlite3IndexedByLookup(pParse, pItem) ){
80974     pTab = 0;
80975   }
80976   return pTab;
80977 }
80978
80979 /*
80980 ** Check to make sure the given table is writable.  If it is not
80981 ** writable, generate an error message and return 1.  If it is
80982 ** writable return 0;
80983 */
80984 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
80985   /* A table is not writable under the following circumstances:
80986   **
80987   **   1) It is a virtual table and no implementation of the xUpdate method
80988   **      has been provided, or
80989   **   2) It is a system table (i.e. sqlite_master), this call is not
80990   **      part of a nested parse and writable_schema pragma has not 
80991   **      been specified.
80992   **
80993   ** In either case leave an error message in pParse and return non-zero.
80994   */
80995   if( ( IsVirtual(pTab) 
80996      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
80997    || ( (pTab->tabFlags & TF_Readonly)!=0
80998      && (pParse->db->flags & SQLITE_WriteSchema)==0
80999      && pParse->nested==0 )
81000   ){
81001     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
81002     return 1;
81003   }
81004
81005 #ifndef SQLITE_OMIT_VIEW
81006   if( !viewOk && pTab->pSelect ){
81007     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
81008     return 1;
81009   }
81010 #endif
81011   return 0;
81012 }
81013
81014
81015 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81016 /*
81017 ** Evaluate a view and store its result in an ephemeral table.  The
81018 ** pWhere argument is an optional WHERE clause that restricts the
81019 ** set of rows in the view that are to be added to the ephemeral table.
81020 */
81021 SQLITE_PRIVATE void sqlite3MaterializeView(
81022   Parse *pParse,       /* Parsing context */
81023   Table *pView,        /* View definition */
81024   Expr *pWhere,        /* Optional WHERE clause to be added */
81025   int iCur             /* Cursor number for ephemerial table */
81026 ){
81027   SelectDest dest;
81028   Select *pDup;
81029   sqlite3 *db = pParse->db;
81030
81031   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81032   if( pWhere ){
81033     SrcList *pFrom;
81034     
81035     pWhere = sqlite3ExprDup(db, pWhere, 0);
81036     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81037     if( pFrom ){
81038       assert( pFrom->nSrc==1 );
81039       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81040       pFrom->a[0].pSelect = pDup;
81041       assert( pFrom->a[0].pOn==0 );
81042       assert( pFrom->a[0].pUsing==0 );
81043     }else{
81044       sqlite3SelectDelete(db, pDup);
81045     }
81046     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81047   }
81048   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81049   sqlite3Select(pParse, pDup, &dest);
81050   sqlite3SelectDelete(db, pDup);
81051 }
81052 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81053
81054 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81055 /*
81056 ** Generate an expression tree to implement the WHERE, ORDER BY,
81057 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81058 **
81059 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81060 **                            \__________________________/
81061 **                               pLimitWhere (pInClause)
81062 */
81063 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81064   Parse *pParse,               /* The parser context */
81065   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
81066   Expr *pWhere,                /* The WHERE clause.  May be null */
81067   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
81068   Expr *pLimit,                /* The LIMIT clause.  May be null */
81069   Expr *pOffset,               /* The OFFSET clause.  May be null */
81070   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
81071 ){
81072   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
81073   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
81074   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
81075   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
81076   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
81077   Select *pSelect = NULL;      /* Complete SELECT tree */
81078
81079   /* Check that there isn't an ORDER BY without a LIMIT clause.
81080   */
81081   if( pOrderBy && (pLimit == 0) ) {
81082     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81083     pParse->parseError = 1;
81084     goto limit_where_cleanup_2;
81085   }
81086
81087   /* We only need to generate a select expression if there
81088   ** is a limit/offset term to enforce.
81089   */
81090   if( pLimit == 0 ) {
81091     /* if pLimit is null, pOffset will always be null as well. */
81092     assert( pOffset == 0 );
81093     return pWhere;
81094   }
81095
81096   /* Generate a select expression tree to enforce the limit/offset 
81097   ** term for the DELETE or UPDATE statement.  For example:
81098   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81099   ** becomes:
81100   **   DELETE FROM table_a WHERE rowid IN ( 
81101   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81102   **   );
81103   */
81104
81105   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81106   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81107   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81108   if( pEList == 0 ) goto limit_where_cleanup_2;
81109
81110   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81111   ** and the SELECT subtree. */
81112   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81113   if( pSelectSrc == 0 ) {
81114     sqlite3ExprListDelete(pParse->db, pEList);
81115     goto limit_where_cleanup_2;
81116   }
81117
81118   /* generate the SELECT expression tree. */
81119   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81120                              pOrderBy,0,pLimit,pOffset);
81121   if( pSelect == 0 ) return 0;
81122
81123   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81124   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81125   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81126   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81127   if( pInClause == 0 ) goto limit_where_cleanup_1;
81128
81129   pInClause->x.pSelect = pSelect;
81130   pInClause->flags |= EP_xIsSelect;
81131   sqlite3ExprSetHeight(pParse, pInClause);
81132   return pInClause;
81133
81134   /* something went wrong. clean up anything allocated. */
81135 limit_where_cleanup_1:
81136   sqlite3SelectDelete(pParse->db, pSelect);
81137   return 0;
81138
81139 limit_where_cleanup_2:
81140   sqlite3ExprDelete(pParse->db, pWhere);
81141   sqlite3ExprListDelete(pParse->db, pOrderBy);
81142   sqlite3ExprDelete(pParse->db, pLimit);
81143   sqlite3ExprDelete(pParse->db, pOffset);
81144   return 0;
81145 }
81146 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81147
81148 /*
81149 ** Generate code for a DELETE FROM statement.
81150 **
81151 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81152 **                 \________/       \________________/
81153 **                  pTabList              pWhere
81154 */
81155 SQLITE_PRIVATE void sqlite3DeleteFrom(
81156   Parse *pParse,         /* The parser context */
81157   SrcList *pTabList,     /* The table from which we should delete things */
81158   Expr *pWhere           /* The WHERE clause.  May be null */
81159 ){
81160   Vdbe *v;               /* The virtual database engine */
81161   Table *pTab;           /* The table from which records will be deleted */
81162   const char *zDb;       /* Name of database holding pTab */
81163   int end, addr = 0;     /* A couple addresses of generated code */
81164   int i;                 /* Loop counter */
81165   WhereInfo *pWInfo;     /* Information about the WHERE clause */
81166   Index *pIdx;           /* For looping over indices of the table */
81167   int iCur;              /* VDBE Cursor number for pTab */
81168   sqlite3 *db;           /* Main database structure */
81169   AuthContext sContext;  /* Authorization context */
81170   NameContext sNC;       /* Name context to resolve expressions in */
81171   int iDb;               /* Database number */
81172   int memCnt = -1;       /* Memory cell used for change counting */
81173   int rcauth;            /* Value returned by authorization callback */
81174
81175 #ifndef SQLITE_OMIT_TRIGGER
81176   int isView;                  /* True if attempting to delete from a view */
81177   Trigger *pTrigger;           /* List of table triggers, if required */
81178 #endif
81179
81180   memset(&sContext, 0, sizeof(sContext));
81181   db = pParse->db;
81182   if( pParse->nErr || db->mallocFailed ){
81183     goto delete_from_cleanup;
81184   }
81185   assert( pTabList->nSrc==1 );
81186
81187   /* Locate the table which we want to delete.  This table has to be
81188   ** put in an SrcList structure because some of the subroutines we
81189   ** will be calling are designed to work with multiple tables and expect
81190   ** an SrcList* parameter instead of just a Table* parameter.
81191   */
81192   pTab = sqlite3SrcListLookup(pParse, pTabList);
81193   if( pTab==0 )  goto delete_from_cleanup;
81194
81195   /* Figure out if we have any triggers and if the table being
81196   ** deleted from is a view
81197   */
81198 #ifndef SQLITE_OMIT_TRIGGER
81199   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81200   isView = pTab->pSelect!=0;
81201 #else
81202 # define pTrigger 0
81203 # define isView 0
81204 #endif
81205 #ifdef SQLITE_OMIT_VIEW
81206 # undef isView
81207 # define isView 0
81208 #endif
81209
81210   /* If pTab is really a view, make sure it has been initialized.
81211   */
81212   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81213     goto delete_from_cleanup;
81214   }
81215
81216   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81217     goto delete_from_cleanup;
81218   }
81219   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81220   assert( iDb<db->nDb );
81221   zDb = db->aDb[iDb].zName;
81222   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81223   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81224   if( rcauth==SQLITE_DENY ){
81225     goto delete_from_cleanup;
81226   }
81227   assert(!isView || pTrigger);
81228
81229   /* Assign  cursor number to the table and all its indices.
81230   */
81231   assert( pTabList->nSrc==1 );
81232   iCur = pTabList->a[0].iCursor = pParse->nTab++;
81233   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81234     pParse->nTab++;
81235   }
81236
81237   /* Start the view context
81238   */
81239   if( isView ){
81240     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81241   }
81242
81243   /* Begin generating code.
81244   */
81245   v = sqlite3GetVdbe(pParse);
81246   if( v==0 ){
81247     goto delete_from_cleanup;
81248   }
81249   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81250   sqlite3BeginWriteOperation(pParse, 1, iDb);
81251
81252   /* If we are trying to delete from a view, realize that view into
81253   ** a ephemeral table.
81254   */
81255 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81256   if( isView ){
81257     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81258   }
81259 #endif
81260
81261   /* Resolve the column names in the WHERE clause.
81262   */
81263   memset(&sNC, 0, sizeof(sNC));
81264   sNC.pParse = pParse;
81265   sNC.pSrcList = pTabList;
81266   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81267     goto delete_from_cleanup;
81268   }
81269
81270   /* Initialize the counter of the number of rows deleted, if
81271   ** we are counting rows.
81272   */
81273   if( db->flags & SQLITE_CountRows ){
81274     memCnt = ++pParse->nMem;
81275     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81276   }
81277
81278 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81279   /* Special case: A DELETE without a WHERE clause deletes everything.
81280   ** It is easier just to erase the whole table. Prior to version 3.6.5,
81281   ** this optimization caused the row change count (the value returned by 
81282   ** API function sqlite3_count_changes) to be set incorrectly.  */
81283   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
81284    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81285   ){
81286     assert( !isView );
81287     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81288                       pTab->zName, P4_STATIC);
81289     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81290       assert( pIdx->pSchema==pTab->pSchema );
81291       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81292     }
81293   }else
81294 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81295   /* The usual case: There is a WHERE clause so we have to scan through
81296   ** the table and pick which records to delete.
81297   */
81298   {
81299     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
81300     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
81301     int regRowid;                   /* Actual register containing rowids */
81302
81303     /* Collect rowids of every row to be deleted.
81304     */
81305     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81306     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81307     if( pWInfo==0 ) goto delete_from_cleanup;
81308     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81309     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81310     if( db->flags & SQLITE_CountRows ){
81311       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81312     }
81313     sqlite3WhereEnd(pWInfo);
81314
81315     /* Delete every item whose key was written to the list during the
81316     ** database scan.  We have to delete items after the scan is complete
81317     ** because deleting an item can change the scan order.  */
81318     end = sqlite3VdbeMakeLabel(v);
81319
81320     /* Unless this is a view, open cursors for the table we are 
81321     ** deleting from and all its indices. If this is a view, then the
81322     ** only effect this statement has is to fire the INSTEAD OF 
81323     ** triggers.  */
81324     if( !isView ){
81325       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81326     }
81327
81328     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81329
81330     /* Delete the row */
81331 #ifndef SQLITE_OMIT_VIRTUALTABLE
81332     if( IsVirtual(pTab) ){
81333       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81334       sqlite3VtabMakeWritable(pParse, pTab);
81335       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81336       sqlite3MayAbort(pParse);
81337     }else
81338 #endif
81339     {
81340       int count = (pParse->nested==0);    /* True to count changes */
81341       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81342     }
81343
81344     /* End of the delete loop */
81345     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81346     sqlite3VdbeResolveLabel(v, end);
81347
81348     /* Close the cursors open on the table and its indexes. */
81349     if( !isView && !IsVirtual(pTab) ){
81350       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81351         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81352       }
81353       sqlite3VdbeAddOp1(v, OP_Close, iCur);
81354     }
81355   }
81356
81357   /* Update the sqlite_sequence table by storing the content of the
81358   ** maximum rowid counter values recorded while inserting into
81359   ** autoincrement tables.
81360   */
81361   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81362     sqlite3AutoincrementEnd(pParse);
81363   }
81364
81365   /* Return the number of rows that were deleted. If this routine is 
81366   ** generating code because of a call to sqlite3NestedParse(), do not
81367   ** invoke the callback function.
81368   */
81369   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81370     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81371     sqlite3VdbeSetNumCols(v, 1);
81372     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81373   }
81374
81375 delete_from_cleanup:
81376   sqlite3AuthContextPop(&sContext);
81377   sqlite3SrcListDelete(db, pTabList);
81378   sqlite3ExprDelete(db, pWhere);
81379   return;
81380 }
81381 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81382 ** thely may interfere with compilation of other functions in this file
81383 ** (or in another file, if this file becomes part of the amalgamation).  */
81384 #ifdef isView
81385  #undef isView
81386 #endif
81387 #ifdef pTrigger
81388  #undef pTrigger
81389 #endif
81390
81391 /*
81392 ** This routine generates VDBE code that causes a single row of a
81393 ** single table to be deleted.
81394 **
81395 ** The VDBE must be in a particular state when this routine is called.
81396 ** These are the requirements:
81397 **
81398 **   1.  A read/write cursor pointing to pTab, the table containing the row
81399 **       to be deleted, must be opened as cursor number $iCur.
81400 **
81401 **   2.  Read/write cursors for all indices of pTab must be open as
81402 **       cursor number base+i for the i-th index.
81403 **
81404 **   3.  The record number of the row to be deleted must be stored in
81405 **       memory cell iRowid.
81406 **
81407 ** This routine generates code to remove both the table record and all 
81408 ** index entries that point to that record.
81409 */
81410 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
81411   Parse *pParse,     /* Parsing context */
81412   Table *pTab,       /* Table containing the row to be deleted */
81413   int iCur,          /* Cursor number for the table */
81414   int iRowid,        /* Memory cell that contains the rowid to delete */
81415   int count,         /* If non-zero, increment the row change counter */
81416   Trigger *pTrigger, /* List of triggers to (potentially) fire */
81417   int onconf         /* Default ON CONFLICT policy for triggers */
81418 ){
81419   Vdbe *v = pParse->pVdbe;        /* Vdbe */
81420   int iOld = 0;                   /* First register in OLD.* array */
81421   int iLabel;                     /* Label resolved to end of generated code */
81422
81423   /* Vdbe is guaranteed to have been allocated by this stage. */
81424   assert( v );
81425
81426   /* Seek cursor iCur to the row to delete. If this row no longer exists 
81427   ** (this can happen if a trigger program has already deleted it), do
81428   ** not attempt to delete it or fire any DELETE triggers.  */
81429   iLabel = sqlite3VdbeMakeLabel(v);
81430   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81431  
81432   /* If there are any triggers to fire, allocate a range of registers to
81433   ** use for the old.* references in the triggers.  */
81434   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
81435     u32 mask;                     /* Mask of OLD.* columns in use */
81436     int iCol;                     /* Iterator used while populating OLD.* */
81437
81438     /* TODO: Could use temporary registers here. Also could attempt to
81439     ** avoid copying the contents of the rowid register.  */
81440     mask = sqlite3TriggerColmask(
81441         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
81442     );
81443     mask |= sqlite3FkOldmask(pParse, pTab);
81444     iOld = pParse->nMem+1;
81445     pParse->nMem += (1 + pTab->nCol);
81446
81447     /* Populate the OLD.* pseudo-table register array. These values will be 
81448     ** used by any BEFORE and AFTER triggers that exist.  */
81449     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
81450     for(iCol=0; iCol<pTab->nCol; iCol++){
81451       if( mask==0xffffffff || mask&(1<<iCol) ){
81452         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
81453       }
81454     }
81455
81456     /* Invoke BEFORE DELETE trigger programs. */
81457     sqlite3CodeRowTrigger(pParse, pTrigger, 
81458         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
81459     );
81460
81461     /* Seek the cursor to the row to be deleted again. It may be that
81462     ** the BEFORE triggers coded above have already removed the row
81463     ** being deleted. Do not attempt to delete the row a second time, and 
81464     ** do not fire AFTER triggers.  */
81465     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81466
81467     /* Do FK processing. This call checks that any FK constraints that
81468     ** refer to this table (i.e. constraints attached to other tables) 
81469     ** are not violated by deleting this row.  */
81470     sqlite3FkCheck(pParse, pTab, iOld, 0);
81471   }
81472
81473   /* Delete the index and table entries. Skip this step if pTab is really
81474   ** a view (in which case the only effect of the DELETE statement is to
81475   ** fire the INSTEAD OF triggers).  */ 
81476   if( pTab->pSelect==0 ){
81477     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
81478     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
81479     if( count ){
81480       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
81481     }
81482   }
81483
81484   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
81485   ** handle rows (possibly in other tables) that refer via a foreign key
81486   ** to the row just deleted. */ 
81487   sqlite3FkActions(pParse, pTab, 0, iOld);
81488
81489   /* Invoke AFTER DELETE trigger programs. */
81490   sqlite3CodeRowTrigger(pParse, pTrigger, 
81491       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
81492   );
81493
81494   /* Jump here if the row had already been deleted before any BEFORE
81495   ** trigger programs were invoked. Or if a trigger program throws a 
81496   ** RAISE(IGNORE) exception.  */
81497   sqlite3VdbeResolveLabel(v, iLabel);
81498 }
81499
81500 /*
81501 ** This routine generates VDBE code that causes the deletion of all
81502 ** index entries associated with a single row of a single table.
81503 **
81504 ** The VDBE must be in a particular state when this routine is called.
81505 ** These are the requirements:
81506 **
81507 **   1.  A read/write cursor pointing to pTab, the table containing the row
81508 **       to be deleted, must be opened as cursor number "iCur".
81509 **
81510 **   2.  Read/write cursors for all indices of pTab must be open as
81511 **       cursor number iCur+i for the i-th index.
81512 **
81513 **   3.  The "iCur" cursor must be pointing to the row that is to be
81514 **       deleted.
81515 */
81516 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
81517   Parse *pParse,     /* Parsing and code generating context */
81518   Table *pTab,       /* Table containing the row to be deleted */
81519   int iCur,          /* Cursor number for the table */
81520   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
81521 ){
81522   int i;
81523   Index *pIdx;
81524   int r1;
81525
81526   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81527     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
81528     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
81529     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
81530   }
81531 }
81532
81533 /*
81534 ** Generate code that will assemble an index key and put it in register
81535 ** regOut.  The key with be for index pIdx which is an index on pTab.
81536 ** iCur is the index of a cursor open on the pTab table and pointing to
81537 ** the entry that needs indexing.
81538 **
81539 ** Return a register number which is the first in a block of
81540 ** registers that holds the elements of the index key.  The
81541 ** block of registers has already been deallocated by the time
81542 ** this routine returns.
81543 */
81544 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
81545   Parse *pParse,     /* Parsing context */
81546   Index *pIdx,       /* The index for which to generate a key */
81547   int iCur,          /* Cursor number for the pIdx->pTable table */
81548   int regOut,        /* Write the new index key to this register */
81549   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
81550 ){
81551   Vdbe *v = pParse->pVdbe;
81552   int j;
81553   Table *pTab = pIdx->pTable;
81554   int regBase;
81555   int nCol;
81556
81557   nCol = pIdx->nColumn;
81558   regBase = sqlite3GetTempRange(pParse, nCol+1);
81559   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
81560   for(j=0; j<nCol; j++){
81561     int idx = pIdx->aiColumn[j];
81562     if( idx==pTab->iPKey ){
81563       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
81564     }else{
81565       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
81566       sqlite3ColumnDefault(v, pTab, idx, -1);
81567     }
81568   }
81569   if( doMakeRec ){
81570     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
81571     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
81572   }
81573   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
81574   return regBase;
81575 }
81576
81577 /************** End of delete.c **********************************************/
81578 /************** Begin file func.c ********************************************/
81579 /*
81580 ** 2002 February 23
81581 **
81582 ** The author disclaims copyright to this source code.  In place of
81583 ** a legal notice, here is a blessing:
81584 **
81585 **    May you do good and not evil.
81586 **    May you find forgiveness for yourself and forgive others.
81587 **    May you share freely, never taking more than you give.
81588 **
81589 *************************************************************************
81590 ** This file contains the C functions that implement various SQL
81591 ** functions of SQLite.  
81592 **
81593 ** There is only one exported symbol in this file - the function
81594 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
81595 ** All other code has file scope.
81596 */
81597
81598 /*
81599 ** Return the collating function associated with a function.
81600 */
81601 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
81602   return context->pColl;
81603 }
81604
81605 /*
81606 ** Implementation of the non-aggregate min() and max() functions
81607 */
81608 static void minmaxFunc(
81609   sqlite3_context *context,
81610   int argc,
81611   sqlite3_value **argv
81612 ){
81613   int i;
81614   int mask;    /* 0 for min() or 0xffffffff for max() */
81615   int iBest;
81616   CollSeq *pColl;
81617
81618   assert( argc>1 );
81619   mask = sqlite3_user_data(context)==0 ? 0 : -1;
81620   pColl = sqlite3GetFuncCollSeq(context);
81621   assert( pColl );
81622   assert( mask==-1 || mask==0 );
81623   iBest = 0;
81624   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81625   for(i=1; i<argc; i++){
81626     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
81627     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
81628       testcase( mask==0 );
81629       iBest = i;
81630     }
81631   }
81632   sqlite3_result_value(context, argv[iBest]);
81633 }
81634
81635 /*
81636 ** Return the type of the argument.
81637 */
81638 static void typeofFunc(
81639   sqlite3_context *context,
81640   int NotUsed,
81641   sqlite3_value **argv
81642 ){
81643   const char *z = 0;
81644   UNUSED_PARAMETER(NotUsed);
81645   switch( sqlite3_value_type(argv[0]) ){
81646     case SQLITE_INTEGER: z = "integer"; break;
81647     case SQLITE_TEXT:    z = "text";    break;
81648     case SQLITE_FLOAT:   z = "real";    break;
81649     case SQLITE_BLOB:    z = "blob";    break;
81650     default:             z = "null";    break;
81651   }
81652   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
81653 }
81654
81655
81656 /*
81657 ** Implementation of the length() function
81658 */
81659 static void lengthFunc(
81660   sqlite3_context *context,
81661   int argc,
81662   sqlite3_value **argv
81663 ){
81664   int len;
81665
81666   assert( argc==1 );
81667   UNUSED_PARAMETER(argc);
81668   switch( sqlite3_value_type(argv[0]) ){
81669     case SQLITE_BLOB:
81670     case SQLITE_INTEGER:
81671     case SQLITE_FLOAT: {
81672       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
81673       break;
81674     }
81675     case SQLITE_TEXT: {
81676       const unsigned char *z = sqlite3_value_text(argv[0]);
81677       if( z==0 ) return;
81678       len = 0;
81679       while( *z ){
81680         len++;
81681         SQLITE_SKIP_UTF8(z);
81682       }
81683       sqlite3_result_int(context, len);
81684       break;
81685     }
81686     default: {
81687       sqlite3_result_null(context);
81688       break;
81689     }
81690   }
81691 }
81692
81693 /*
81694 ** Implementation of the abs() function.
81695 **
81696 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
81697 ** the numeric argument X. 
81698 */
81699 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81700   assert( argc==1 );
81701   UNUSED_PARAMETER(argc);
81702   switch( sqlite3_value_type(argv[0]) ){
81703     case SQLITE_INTEGER: {
81704       i64 iVal = sqlite3_value_int64(argv[0]);
81705       if( iVal<0 ){
81706         if( (iVal<<1)==0 ){
81707           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
81708           ** abs(X) throws an integer overflow error since there is no
81709           ** equivalent positive 64-bit two complement value. */
81710           sqlite3_result_error(context, "integer overflow", -1);
81711           return;
81712         }
81713         iVal = -iVal;
81714       } 
81715       sqlite3_result_int64(context, iVal);
81716       break;
81717     }
81718     case SQLITE_NULL: {
81719       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
81720       sqlite3_result_null(context);
81721       break;
81722     }
81723     default: {
81724       /* Because sqlite3_value_double() returns 0.0 if the argument is not
81725       ** something that can be converted into a number, we have:
81726       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
81727       ** cannot be converted to a numeric value. 
81728       */
81729       double rVal = sqlite3_value_double(argv[0]);
81730       if( rVal<0 ) rVal = -rVal;
81731       sqlite3_result_double(context, rVal);
81732       break;
81733     }
81734   }
81735 }
81736
81737 /*
81738 ** Implementation of the substr() function.
81739 **
81740 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
81741 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
81742 ** of x.  If x is text, then we actually count UTF-8 characters.
81743 ** If x is a blob, then we count bytes.
81744 **
81745 ** If p1 is negative, then we begin abs(p1) from the end of x[].
81746 **
81747 ** If p2 is negative, return the p2 characters preceeding p1.
81748 */
81749 static void substrFunc(
81750   sqlite3_context *context,
81751   int argc,
81752   sqlite3_value **argv
81753 ){
81754   const unsigned char *z;
81755   const unsigned char *z2;
81756   int len;
81757   int p0type;
81758   i64 p1, p2;
81759   int negP2 = 0;
81760
81761   assert( argc==3 || argc==2 );
81762   if( sqlite3_value_type(argv[1])==SQLITE_NULL
81763    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
81764   ){
81765     return;
81766   }
81767   p0type = sqlite3_value_type(argv[0]);
81768   p1 = sqlite3_value_int(argv[1]);
81769   if( p0type==SQLITE_BLOB ){
81770     len = sqlite3_value_bytes(argv[0]);
81771     z = sqlite3_value_blob(argv[0]);
81772     if( z==0 ) return;
81773     assert( len==sqlite3_value_bytes(argv[0]) );
81774   }else{
81775     z = sqlite3_value_text(argv[0]);
81776     if( z==0 ) return;
81777     len = 0;
81778     if( p1<0 ){
81779       for(z2=z; *z2; len++){
81780         SQLITE_SKIP_UTF8(z2);
81781       }
81782     }
81783   }
81784   if( argc==3 ){
81785     p2 = sqlite3_value_int(argv[2]);
81786     if( p2<0 ){
81787       p2 = -p2;
81788       negP2 = 1;
81789     }
81790   }else{
81791     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
81792   }
81793   if( p1<0 ){
81794     p1 += len;
81795     if( p1<0 ){
81796       p2 += p1;
81797       if( p2<0 ) p2 = 0;
81798       p1 = 0;
81799     }
81800   }else if( p1>0 ){
81801     p1--;
81802   }else if( p2>0 ){
81803     p2--;
81804   }
81805   if( negP2 ){
81806     p1 -= p2;
81807     if( p1<0 ){
81808       p2 += p1;
81809       p1 = 0;
81810     }
81811   }
81812   assert( p1>=0 && p2>=0 );
81813   if( p0type!=SQLITE_BLOB ){
81814     while( *z && p1 ){
81815       SQLITE_SKIP_UTF8(z);
81816       p1--;
81817     }
81818     for(z2=z; *z2 && p2; p2--){
81819       SQLITE_SKIP_UTF8(z2);
81820     }
81821     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
81822   }else{
81823     if( p1+p2>len ){
81824       p2 = len-p1;
81825       if( p2<0 ) p2 = 0;
81826     }
81827     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
81828   }
81829 }
81830
81831 /*
81832 ** Implementation of the round() function
81833 */
81834 #ifndef SQLITE_OMIT_FLOATING_POINT
81835 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81836   int n = 0;
81837   double r;
81838   char *zBuf;
81839   assert( argc==1 || argc==2 );
81840   if( argc==2 ){
81841     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
81842     n = sqlite3_value_int(argv[1]);
81843     if( n>30 ) n = 30;
81844     if( n<0 ) n = 0;
81845   }
81846   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81847   r = sqlite3_value_double(argv[0]);
81848   /* If Y==0 and X will fit in a 64-bit int,
81849   ** handle the rounding directly,
81850   ** otherwise use printf.
81851   */
81852   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
81853     r = (double)((sqlite_int64)(r+0.5));
81854   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
81855     r = -(double)((sqlite_int64)((-r)+0.5));
81856   }else{
81857     zBuf = sqlite3_mprintf("%.*f",n,r);
81858     if( zBuf==0 ){
81859       sqlite3_result_error_nomem(context);
81860       return;
81861     }
81862     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
81863     sqlite3_free(zBuf);
81864   }
81865   sqlite3_result_double(context, r);
81866 }
81867 #endif
81868
81869 /*
81870 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
81871 ** allocation fails, call sqlite3_result_error_nomem() to notify
81872 ** the database handle that malloc() has failed and return NULL.
81873 ** If nByte is larger than the maximum string or blob length, then
81874 ** raise an SQLITE_TOOBIG exception and return NULL.
81875 */
81876 static void *contextMalloc(sqlite3_context *context, i64 nByte){
81877   char *z;
81878   sqlite3 *db = sqlite3_context_db_handle(context);
81879   assert( nByte>0 );
81880   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
81881   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
81882   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81883     sqlite3_result_error_toobig(context);
81884     z = 0;
81885   }else{
81886     z = sqlite3Malloc((int)nByte);
81887     if( !z ){
81888       sqlite3_result_error_nomem(context);
81889     }
81890   }
81891   return z;
81892 }
81893
81894 /*
81895 ** Implementation of the upper() and lower() SQL functions.
81896 */
81897 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81898   char *z1;
81899   const char *z2;
81900   int i, n;
81901   UNUSED_PARAMETER(argc);
81902   z2 = (char*)sqlite3_value_text(argv[0]);
81903   n = sqlite3_value_bytes(argv[0]);
81904   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
81905   assert( z2==(char*)sqlite3_value_text(argv[0]) );
81906   if( z2 ){
81907     z1 = contextMalloc(context, ((i64)n)+1);
81908     if( z1 ){
81909       memcpy(z1, z2, n+1);
81910       for(i=0; z1[i]; i++){
81911         z1[i] = (char)sqlite3Toupper(z1[i]);
81912       }
81913       sqlite3_result_text(context, z1, -1, sqlite3_free);
81914     }
81915   }
81916 }
81917 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
81918   u8 *z1;
81919   const char *z2;
81920   int i, n;
81921   UNUSED_PARAMETER(argc);
81922   z2 = (char*)sqlite3_value_text(argv[0]);
81923   n = sqlite3_value_bytes(argv[0]);
81924   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
81925   assert( z2==(char*)sqlite3_value_text(argv[0]) );
81926   if( z2 ){
81927     z1 = contextMalloc(context, ((i64)n)+1);
81928     if( z1 ){
81929       memcpy(z1, z2, n+1);
81930       for(i=0; z1[i]; i++){
81931         z1[i] = sqlite3Tolower(z1[i]);
81932       }
81933       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
81934     }
81935   }
81936 }
81937
81938
81939 #if 0  /* This function is never used. */
81940 /*
81941 ** The COALESCE() and IFNULL() functions used to be implemented as shown
81942 ** here.  But now they are implemented as VDBE code so that unused arguments
81943 ** do not have to be computed.  This legacy implementation is retained as
81944 ** comment.
81945 */
81946 /*
81947 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
81948 ** All three do the same thing.  They return the first non-NULL
81949 ** argument.
81950 */
81951 static void ifnullFunc(
81952   sqlite3_context *context,
81953   int argc,
81954   sqlite3_value **argv
81955 ){
81956   int i;
81957   for(i=0; i<argc; i++){
81958     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
81959       sqlite3_result_value(context, argv[i]);
81960       break;
81961     }
81962   }
81963 }
81964 #endif /* NOT USED */
81965 #define ifnullFunc versionFunc   /* Substitute function - never called */
81966
81967 /*
81968 ** Implementation of random().  Return a random integer.  
81969 */
81970 static void randomFunc(
81971   sqlite3_context *context,
81972   int NotUsed,
81973   sqlite3_value **NotUsed2
81974 ){
81975   sqlite_int64 r;
81976   UNUSED_PARAMETER2(NotUsed, NotUsed2);
81977   sqlite3_randomness(sizeof(r), &r);
81978   if( r<0 ){
81979     /* We need to prevent a random number of 0x8000000000000000 
81980     ** (or -9223372036854775808) since when you do abs() of that
81981     ** number of you get the same value back again.  To do this
81982     ** in a way that is testable, mask the sign bit off of negative
81983     ** values, resulting in a positive value.  Then take the 
81984     ** 2s complement of that positive value.  The end result can
81985     ** therefore be no less than -9223372036854775807.
81986     */
81987     r = -(r ^ (((sqlite3_int64)1)<<63));
81988   }
81989   sqlite3_result_int64(context, r);
81990 }
81991
81992 /*
81993 ** Implementation of randomblob(N).  Return a random blob
81994 ** that is N bytes long.
81995 */
81996 static void randomBlob(
81997   sqlite3_context *context,
81998   int argc,
81999   sqlite3_value **argv
82000 ){
82001   int n;
82002   unsigned char *p;
82003   assert( argc==1 );
82004   UNUSED_PARAMETER(argc);
82005   n = sqlite3_value_int(argv[0]);
82006   if( n<1 ){
82007     n = 1;
82008   }
82009   p = contextMalloc(context, n);
82010   if( p ){
82011     sqlite3_randomness(n, p);
82012     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82013   }
82014 }
82015
82016 /*
82017 ** Implementation of the last_insert_rowid() SQL function.  The return
82018 ** value is the same as the sqlite3_last_insert_rowid() API function.
82019 */
82020 static void last_insert_rowid(
82021   sqlite3_context *context, 
82022   int NotUsed, 
82023   sqlite3_value **NotUsed2
82024 ){
82025   sqlite3 *db = sqlite3_context_db_handle(context);
82026   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82027   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82028   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82029   ** function. */
82030   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82031 }
82032
82033 /*
82034 ** Implementation of the changes() SQL function.
82035 **
82036 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
82037 ** around the sqlite3_changes() C/C++ function and hence follows the same
82038 ** rules for counting changes.
82039 */
82040 static void changes(
82041   sqlite3_context *context,
82042   int NotUsed,
82043   sqlite3_value **NotUsed2
82044 ){
82045   sqlite3 *db = sqlite3_context_db_handle(context);
82046   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82047   sqlite3_result_int(context, sqlite3_changes(db));
82048 }
82049
82050 /*
82051 ** Implementation of the total_changes() SQL function.  The return value is
82052 ** the same as the sqlite3_total_changes() API function.
82053 */
82054 static void total_changes(
82055   sqlite3_context *context,
82056   int NotUsed,
82057   sqlite3_value **NotUsed2
82058 ){
82059   sqlite3 *db = sqlite3_context_db_handle(context);
82060   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82061   /* IMP: R-52756-41993 This function is a wrapper around the
82062   ** sqlite3_total_changes() C/C++ interface. */
82063   sqlite3_result_int(context, sqlite3_total_changes(db));
82064 }
82065
82066 /*
82067 ** A structure defining how to do GLOB-style comparisons.
82068 */
82069 struct compareInfo {
82070   u8 matchAll;
82071   u8 matchOne;
82072   u8 matchSet;
82073   u8 noCase;
82074 };
82075
82076 /*
82077 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
82078 ** character is exactly one byte in size.  Also, all characters are
82079 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
82080 ** whereas only characters less than 0x80 do in ASCII.
82081 */
82082 #if defined(SQLITE_EBCDIC)
82083 # define sqlite3Utf8Read(A,C)    (*(A++))
82084 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
82085 #else
82086 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
82087 #endif
82088
82089 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82090 /* The correct SQL-92 behavior is for the LIKE operator to ignore
82091 ** case.  Thus  'a' LIKE 'A' would be true. */
82092 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
82093 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82094 ** is case sensitive causing 'a' LIKE 'A' to be false */
82095 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
82096
82097 /*
82098 ** Compare two UTF-8 strings for equality where the first string can
82099 ** potentially be a "glob" expression.  Return true (1) if they
82100 ** are the same and false (0) if they are different.
82101 **
82102 ** Globbing rules:
82103 **
82104 **      '*'       Matches any sequence of zero or more characters.
82105 **
82106 **      '?'       Matches exactly one character.
82107 **
82108 **     [...]      Matches one character from the enclosed list of
82109 **                characters.
82110 **
82111 **     [^...]     Matches one character not in the enclosed list.
82112 **
82113 ** With the [...] and [^...] matching, a ']' character can be included
82114 ** in the list by making it the first character after '[' or '^'.  A
82115 ** range of characters can be specified using '-'.  Example:
82116 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
82117 ** it the last character in the list.
82118 **
82119 ** This routine is usually quick, but can be N**2 in the worst case.
82120 **
82121 ** Hints: to match '*' or '?', put them in "[]".  Like this:
82122 **
82123 **         abc[*]xyz        Matches "abc*xyz" only
82124 */
82125 static int patternCompare(
82126   const u8 *zPattern,              /* The glob pattern */
82127   const u8 *zString,               /* The string to compare against the glob */
82128   const struct compareInfo *pInfo, /* Information about how to do the compare */
82129   const int esc                    /* The escape character */
82130 ){
82131   int c, c2;
82132   int invert;
82133   int seen;
82134   u8 matchOne = pInfo->matchOne;
82135   u8 matchAll = pInfo->matchAll;
82136   u8 matchSet = pInfo->matchSet;
82137   u8 noCase = pInfo->noCase; 
82138   int prevEscape = 0;     /* True if the previous character was 'escape' */
82139
82140   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82141     if( !prevEscape && c==matchAll ){
82142       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82143                || c == matchOne ){
82144         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82145           return 0;
82146         }
82147       }
82148       if( c==0 ){
82149         return 1;
82150       }else if( c==esc ){
82151         c = sqlite3Utf8Read(zPattern, &zPattern);
82152         if( c==0 ){
82153           return 0;
82154         }
82155       }else if( c==matchSet ){
82156         assert( esc==0 );         /* This is GLOB, not LIKE */
82157         assert( matchSet<0x80 );  /* '[' is a single-byte character */
82158         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82159           SQLITE_SKIP_UTF8(zString);
82160         }
82161         return *zString!=0;
82162       }
82163       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82164         if( noCase ){
82165           GlogUpperToLower(c2);
82166           GlogUpperToLower(c);
82167           while( c2 != 0 && c2 != c ){
82168             c2 = sqlite3Utf8Read(zString, &zString);
82169             GlogUpperToLower(c2);
82170           }
82171         }else{
82172           while( c2 != 0 && c2 != c ){
82173             c2 = sqlite3Utf8Read(zString, &zString);
82174           }
82175         }
82176         if( c2==0 ) return 0;
82177         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82178       }
82179       return 0;
82180     }else if( !prevEscape && c==matchOne ){
82181       if( sqlite3Utf8Read(zString, &zString)==0 ){
82182         return 0;
82183       }
82184     }else if( c==matchSet ){
82185       int prior_c = 0;
82186       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
82187       seen = 0;
82188       invert = 0;
82189       c = sqlite3Utf8Read(zString, &zString);
82190       if( c==0 ) return 0;
82191       c2 = sqlite3Utf8Read(zPattern, &zPattern);
82192       if( c2=='^' ){
82193         invert = 1;
82194         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82195       }
82196       if( c2==']' ){
82197         if( c==']' ) seen = 1;
82198         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82199       }
82200       while( c2 && c2!=']' ){
82201         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82202           c2 = sqlite3Utf8Read(zPattern, &zPattern);
82203           if( c>=prior_c && c<=c2 ) seen = 1;
82204           prior_c = 0;
82205         }else{
82206           if( c==c2 ){
82207             seen = 1;
82208           }
82209           prior_c = c2;
82210         }
82211         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82212       }
82213       if( c2==0 || (seen ^ invert)==0 ){
82214         return 0;
82215       }
82216     }else if( esc==c && !prevEscape ){
82217       prevEscape = 1;
82218     }else{
82219       c2 = sqlite3Utf8Read(zString, &zString);
82220       if( noCase ){
82221         GlogUpperToLower(c);
82222         GlogUpperToLower(c2);
82223       }
82224       if( c!=c2 ){
82225         return 0;
82226       }
82227       prevEscape = 0;
82228     }
82229   }
82230   return *zString==0;
82231 }
82232
82233 /*
82234 ** Count the number of times that the LIKE operator (or GLOB which is
82235 ** just a variation of LIKE) gets called.  This is used for testing
82236 ** only.
82237 */
82238 #ifdef SQLITE_TEST
82239 SQLITE_API int sqlite3_like_count = 0;
82240 #endif
82241
82242
82243 /*
82244 ** Implementation of the like() SQL function.  This function implements
82245 ** the build-in LIKE operator.  The first argument to the function is the
82246 ** pattern and the second argument is the string.  So, the SQL statements:
82247 **
82248 **       A LIKE B
82249 **
82250 ** is implemented as like(B,A).
82251 **
82252 ** This same function (with a different compareInfo structure) computes
82253 ** the GLOB operator.
82254 */
82255 static void likeFunc(
82256   sqlite3_context *context, 
82257   int argc, 
82258   sqlite3_value **argv
82259 ){
82260   const unsigned char *zA, *zB;
82261   int escape = 0;
82262   int nPat;
82263   sqlite3 *db = sqlite3_context_db_handle(context);
82264
82265   zB = sqlite3_value_text(argv[0]);
82266   zA = sqlite3_value_text(argv[1]);
82267
82268   /* Limit the length of the LIKE or GLOB pattern to avoid problems
82269   ** of deep recursion and N*N behavior in patternCompare().
82270   */
82271   nPat = sqlite3_value_bytes(argv[0]);
82272   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82273   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82274   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82275     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82276     return;
82277   }
82278   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
82279
82280   if( argc==3 ){
82281     /* The escape character string must consist of a single UTF-8 character.
82282     ** Otherwise, return an error.
82283     */
82284     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82285     if( zEsc==0 ) return;
82286     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82287       sqlite3_result_error(context, 
82288           "ESCAPE expression must be a single character", -1);
82289       return;
82290     }
82291     escape = sqlite3Utf8Read(zEsc, &zEsc);
82292   }
82293   if( zA && zB ){
82294     struct compareInfo *pInfo = sqlite3_user_data(context);
82295 #ifdef SQLITE_TEST
82296     sqlite3_like_count++;
82297 #endif
82298     
82299     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82300   }
82301 }
82302
82303 /*
82304 ** Implementation of the NULLIF(x,y) function.  The result is the first
82305 ** argument if the arguments are different.  The result is NULL if the
82306 ** arguments are equal to each other.
82307 */
82308 static void nullifFunc(
82309   sqlite3_context *context,
82310   int NotUsed,
82311   sqlite3_value **argv
82312 ){
82313   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82314   UNUSED_PARAMETER(NotUsed);
82315   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82316     sqlite3_result_value(context, argv[0]);
82317   }
82318 }
82319
82320 /*
82321 ** Implementation of the sqlite_version() function.  The result is the version
82322 ** of the SQLite library that is running.
82323 */
82324 static void versionFunc(
82325   sqlite3_context *context,
82326   int NotUsed,
82327   sqlite3_value **NotUsed2
82328 ){
82329   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82330   /* IMP: R-48699-48617 This function is an SQL wrapper around the
82331   ** sqlite3_libversion() C-interface. */
82332   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82333 }
82334
82335 /*
82336 ** Implementation of the sqlite_source_id() function. The result is a string
82337 ** that identifies the particular version of the source code used to build
82338 ** SQLite.
82339 */
82340 static void sourceidFunc(
82341   sqlite3_context *context,
82342   int NotUsed,
82343   sqlite3_value **NotUsed2
82344 ){
82345   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82346   /* IMP: R-24470-31136 This function is an SQL wrapper around the
82347   ** sqlite3_sourceid() C interface. */
82348   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82349 }
82350
82351 /*
82352 ** Implementation of the sqlite_compileoption_used() function.
82353 ** The result is an integer that identifies if the compiler option
82354 ** was used to build SQLite.
82355 */
82356 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82357 static void compileoptionusedFunc(
82358   sqlite3_context *context,
82359   int argc,
82360   sqlite3_value **argv
82361 ){
82362   const char *zOptName;
82363   assert( argc==1 );
82364   UNUSED_PARAMETER(argc);
82365   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
82366   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
82367   ** function.
82368   */
82369   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
82370     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
82371   }
82372 }
82373 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82374
82375 /*
82376 ** Implementation of the sqlite_compileoption_get() function. 
82377 ** The result is a string that identifies the compiler options 
82378 ** used to build SQLite.
82379 */
82380 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82381 static void compileoptiongetFunc(
82382   sqlite3_context *context,
82383   int argc,
82384   sqlite3_value **argv
82385 ){
82386   int n;
82387   assert( argc==1 );
82388   UNUSED_PARAMETER(argc);
82389   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
82390   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
82391   */
82392   n = sqlite3_value_int(argv[0]);
82393   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
82394 }
82395 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82396
82397 /* Array for converting from half-bytes (nybbles) into ASCII hex
82398 ** digits. */
82399 static const char hexdigits[] = {
82400   '0', '1', '2', '3', '4', '5', '6', '7',
82401   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
82402 };
82403
82404 /*
82405 ** EXPERIMENTAL - This is not an official function.  The interface may
82406 ** change.  This function may disappear.  Do not write code that depends
82407 ** on this function.
82408 **
82409 ** Implementation of the QUOTE() function.  This function takes a single
82410 ** argument.  If the argument is numeric, the return value is the same as
82411 ** the argument.  If the argument is NULL, the return value is the string
82412 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
82413 ** single-quote escapes.
82414 */
82415 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82416   assert( argc==1 );
82417   UNUSED_PARAMETER(argc);
82418   switch( sqlite3_value_type(argv[0]) ){
82419     case SQLITE_INTEGER:
82420     case SQLITE_FLOAT: {
82421       sqlite3_result_value(context, argv[0]);
82422       break;
82423     }
82424     case SQLITE_BLOB: {
82425       char *zText = 0;
82426       char const *zBlob = sqlite3_value_blob(argv[0]);
82427       int nBlob = sqlite3_value_bytes(argv[0]);
82428       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82429       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
82430       if( zText ){
82431         int i;
82432         for(i=0; i<nBlob; i++){
82433           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
82434           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
82435         }
82436         zText[(nBlob*2)+2] = '\'';
82437         zText[(nBlob*2)+3] = '\0';
82438         zText[0] = 'X';
82439         zText[1] = '\'';
82440         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
82441         sqlite3_free(zText);
82442       }
82443       break;
82444     }
82445     case SQLITE_TEXT: {
82446       int i,j;
82447       u64 n;
82448       const unsigned char *zArg = sqlite3_value_text(argv[0]);
82449       char *z;
82450
82451       if( zArg==0 ) return;
82452       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
82453       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
82454       if( z ){
82455         z[0] = '\'';
82456         for(i=0, j=1; zArg[i]; i++){
82457           z[j++] = zArg[i];
82458           if( zArg[i]=='\'' ){
82459             z[j++] = '\'';
82460           }
82461         }
82462         z[j++] = '\'';
82463         z[j] = 0;
82464         sqlite3_result_text(context, z, j, sqlite3_free);
82465       }
82466       break;
82467     }
82468     default: {
82469       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
82470       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
82471       break;
82472     }
82473   }
82474 }
82475
82476 /*
82477 ** The hex() function.  Interpret the argument as a blob.  Return
82478 ** a hexadecimal rendering as text.
82479 */
82480 static void hexFunc(
82481   sqlite3_context *context,
82482   int argc,
82483   sqlite3_value **argv
82484 ){
82485   int i, n;
82486   const unsigned char *pBlob;
82487   char *zHex, *z;
82488   assert( argc==1 );
82489   UNUSED_PARAMETER(argc);
82490   pBlob = sqlite3_value_blob(argv[0]);
82491   n = sqlite3_value_bytes(argv[0]);
82492   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
82493   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
82494   if( zHex ){
82495     for(i=0; i<n; i++, pBlob++){
82496       unsigned char c = *pBlob;
82497       *(z++) = hexdigits[(c>>4)&0xf];
82498       *(z++) = hexdigits[c&0xf];
82499     }
82500     *z = 0;
82501     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
82502   }
82503 }
82504
82505 /*
82506 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
82507 */
82508 static void zeroblobFunc(
82509   sqlite3_context *context,
82510   int argc,
82511   sqlite3_value **argv
82512 ){
82513   i64 n;
82514   sqlite3 *db = sqlite3_context_db_handle(context);
82515   assert( argc==1 );
82516   UNUSED_PARAMETER(argc);
82517   n = sqlite3_value_int64(argv[0]);
82518   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
82519   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82520   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82521     sqlite3_result_error_toobig(context);
82522   }else{
82523     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
82524   }
82525 }
82526
82527 /*
82528 ** The replace() function.  Three arguments are all strings: call
82529 ** them A, B, and C. The result is also a string which is derived
82530 ** from A by replacing every occurance of B with C.  The match
82531 ** must be exact.  Collating sequences are not used.
82532 */
82533 static void replaceFunc(
82534   sqlite3_context *context,
82535   int argc,
82536   sqlite3_value **argv
82537 ){
82538   const unsigned char *zStr;        /* The input string A */
82539   const unsigned char *zPattern;    /* The pattern string B */
82540   const unsigned char *zRep;        /* The replacement string C */
82541   unsigned char *zOut;              /* The output */
82542   int nStr;                /* Size of zStr */
82543   int nPattern;            /* Size of zPattern */
82544   int nRep;                /* Size of zRep */
82545   i64 nOut;                /* Maximum size of zOut */
82546   int loopLimit;           /* Last zStr[] that might match zPattern[] */
82547   int i, j;                /* Loop counters */
82548
82549   assert( argc==3 );
82550   UNUSED_PARAMETER(argc);
82551   zStr = sqlite3_value_text(argv[0]);
82552   if( zStr==0 ) return;
82553   nStr = sqlite3_value_bytes(argv[0]);
82554   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
82555   zPattern = sqlite3_value_text(argv[1]);
82556   if( zPattern==0 ){
82557     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
82558             || sqlite3_context_db_handle(context)->mallocFailed );
82559     return;
82560   }
82561   if( zPattern[0]==0 ){
82562     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
82563     sqlite3_result_value(context, argv[0]);
82564     return;
82565   }
82566   nPattern = sqlite3_value_bytes(argv[1]);
82567   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
82568   zRep = sqlite3_value_text(argv[2]);
82569   if( zRep==0 ) return;
82570   nRep = sqlite3_value_bytes(argv[2]);
82571   assert( zRep==sqlite3_value_text(argv[2]) );
82572   nOut = nStr + 1;
82573   assert( nOut<SQLITE_MAX_LENGTH );
82574   zOut = contextMalloc(context, (i64)nOut);
82575   if( zOut==0 ){
82576     return;
82577   }
82578   loopLimit = nStr - nPattern;  
82579   for(i=j=0; i<=loopLimit; i++){
82580     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
82581       zOut[j++] = zStr[i];
82582     }else{
82583       u8 *zOld;
82584       sqlite3 *db = sqlite3_context_db_handle(context);
82585       nOut += nRep - nPattern;
82586       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
82587       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
82588       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82589         sqlite3_result_error_toobig(context);
82590         sqlite3_free(zOut);
82591         return;
82592       }
82593       zOld = zOut;
82594       zOut = sqlite3_realloc(zOut, (int)nOut);
82595       if( zOut==0 ){
82596         sqlite3_result_error_nomem(context);
82597         sqlite3_free(zOld);
82598         return;
82599       }
82600       memcpy(&zOut[j], zRep, nRep);
82601       j += nRep;
82602       i += nPattern-1;
82603     }
82604   }
82605   assert( j+nStr-i+1==nOut );
82606   memcpy(&zOut[j], &zStr[i], nStr-i);
82607   j += nStr - i;
82608   assert( j<=nOut );
82609   zOut[j] = 0;
82610   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
82611 }
82612
82613 /*
82614 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
82615 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
82616 */
82617 static void trimFunc(
82618   sqlite3_context *context,
82619   int argc,
82620   sqlite3_value **argv
82621 ){
82622   const unsigned char *zIn;         /* Input string */
82623   const unsigned char *zCharSet;    /* Set of characters to trim */
82624   int nIn;                          /* Number of bytes in input */
82625   int flags;                        /* 1: trimleft  2: trimright  3: trim */
82626   int i;                            /* Loop counter */
82627   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
82628   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
82629   int nChar;                        /* Number of characters in zCharSet */
82630
82631   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
82632     return;
82633   }
82634   zIn = sqlite3_value_text(argv[0]);
82635   if( zIn==0 ) return;
82636   nIn = sqlite3_value_bytes(argv[0]);
82637   assert( zIn==sqlite3_value_text(argv[0]) );
82638   if( argc==1 ){
82639     static const unsigned char lenOne[] = { 1 };
82640     static unsigned char * const azOne[] = { (u8*)" " };
82641     nChar = 1;
82642     aLen = (u8*)lenOne;
82643     azChar = (unsigned char **)azOne;
82644     zCharSet = 0;
82645   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
82646     return;
82647   }else{
82648     const unsigned char *z;
82649     for(z=zCharSet, nChar=0; *z; nChar++){
82650       SQLITE_SKIP_UTF8(z);
82651     }
82652     if( nChar>0 ){
82653       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
82654       if( azChar==0 ){
82655         return;
82656       }
82657       aLen = (unsigned char*)&azChar[nChar];
82658       for(z=zCharSet, nChar=0; *z; nChar++){
82659         azChar[nChar] = (unsigned char *)z;
82660         SQLITE_SKIP_UTF8(z);
82661         aLen[nChar] = (u8)(z - azChar[nChar]);
82662       }
82663     }
82664   }
82665   if( nChar>0 ){
82666     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
82667     if( flags & 1 ){
82668       while( nIn>0 ){
82669         int len = 0;
82670         for(i=0; i<nChar; i++){
82671           len = aLen[i];
82672           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
82673         }
82674         if( i>=nChar ) break;
82675         zIn += len;
82676         nIn -= len;
82677       }
82678     }
82679     if( flags & 2 ){
82680       while( nIn>0 ){
82681         int len = 0;
82682         for(i=0; i<nChar; i++){
82683           len = aLen[i];
82684           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
82685         }
82686         if( i>=nChar ) break;
82687         nIn -= len;
82688       }
82689     }
82690     if( zCharSet ){
82691       sqlite3_free(azChar);
82692     }
82693   }
82694   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
82695 }
82696
82697
82698 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
82699 ** is only available if the SQLITE_SOUNDEX compile-time option is used
82700 ** when SQLite is built.
82701 */
82702 #ifdef SQLITE_SOUNDEX
82703 /*
82704 ** Compute the soundex encoding of a word.
82705 **
82706 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
82707 ** soundex encoding of the string X. 
82708 */
82709 static void soundexFunc(
82710   sqlite3_context *context,
82711   int argc,
82712   sqlite3_value **argv
82713 ){
82714   char zResult[8];
82715   const u8 *zIn;
82716   int i, j;
82717   static const unsigned char iCode[] = {
82718     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82719     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82720     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82721     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82722     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82723     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82724     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
82725     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
82726   };
82727   assert( argc==1 );
82728   zIn = (u8*)sqlite3_value_text(argv[0]);
82729   if( zIn==0 ) zIn = (u8*)"";
82730   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
82731   if( zIn[i] ){
82732     u8 prevcode = iCode[zIn[i]&0x7f];
82733     zResult[0] = sqlite3Toupper(zIn[i]);
82734     for(j=1; j<4 && zIn[i]; i++){
82735       int code = iCode[zIn[i]&0x7f];
82736       if( code>0 ){
82737         if( code!=prevcode ){
82738           prevcode = code;
82739           zResult[j++] = code + '0';
82740         }
82741       }else{
82742         prevcode = 0;
82743       }
82744     }
82745     while( j<4 ){
82746       zResult[j++] = '0';
82747     }
82748     zResult[j] = 0;
82749     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
82750   }else{
82751     /* IMP: R-64894-50321 The string "?000" is returned if the argument
82752     ** is NULL or contains no ASCII alphabetic characters. */
82753     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
82754   }
82755 }
82756 #endif /* SQLITE_SOUNDEX */
82757
82758 #ifndef SQLITE_OMIT_LOAD_EXTENSION
82759 /*
82760 ** A function that loads a shared-library extension then returns NULL.
82761 */
82762 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
82763   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
82764   const char *zProc;
82765   sqlite3 *db = sqlite3_context_db_handle(context);
82766   char *zErrMsg = 0;
82767
82768   if( argc==2 ){
82769     zProc = (const char *)sqlite3_value_text(argv[1]);
82770   }else{
82771     zProc = 0;
82772   }
82773   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
82774     sqlite3_result_error(context, zErrMsg, -1);
82775     sqlite3_free(zErrMsg);
82776   }
82777 }
82778 #endif
82779
82780
82781 /*
82782 ** An instance of the following structure holds the context of a
82783 ** sum() or avg() aggregate computation.
82784 */
82785 typedef struct SumCtx SumCtx;
82786 struct SumCtx {
82787   double rSum;      /* Floating point sum */
82788   i64 iSum;         /* Integer sum */   
82789   i64 cnt;          /* Number of elements summed */
82790   u8 overflow;      /* True if integer overflow seen */
82791   u8 approx;        /* True if non-integer value was input to the sum */
82792 };
82793
82794 /*
82795 ** Routines used to compute the sum, average, and total.
82796 **
82797 ** The SUM() function follows the (broken) SQL standard which means
82798 ** that it returns NULL if it sums over no inputs.  TOTAL returns
82799 ** 0.0 in that case.  In addition, TOTAL always returns a float where
82800 ** SUM might return an integer if it never encounters a floating point
82801 ** value.  TOTAL never fails, but SUM might through an exception if
82802 ** it overflows an integer.
82803 */
82804 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82805   SumCtx *p;
82806   int type;
82807   assert( argc==1 );
82808   UNUSED_PARAMETER(argc);
82809   p = sqlite3_aggregate_context(context, sizeof(*p));
82810   type = sqlite3_value_numeric_type(argv[0]);
82811   if( p && type!=SQLITE_NULL ){
82812     p->cnt++;
82813     if( type==SQLITE_INTEGER ){
82814       i64 v = sqlite3_value_int64(argv[0]);
82815       p->rSum += v;
82816       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
82817         p->overflow = 1;
82818       }
82819     }else{
82820       p->rSum += sqlite3_value_double(argv[0]);
82821       p->approx = 1;
82822     }
82823   }
82824 }
82825 static void sumFinalize(sqlite3_context *context){
82826   SumCtx *p;
82827   p = sqlite3_aggregate_context(context, 0);
82828   if( p && p->cnt>0 ){
82829     if( p->overflow ){
82830       sqlite3_result_error(context,"integer overflow",-1);
82831     }else if( p->approx ){
82832       sqlite3_result_double(context, p->rSum);
82833     }else{
82834       sqlite3_result_int64(context, p->iSum);
82835     }
82836   }
82837 }
82838 static void avgFinalize(sqlite3_context *context){
82839   SumCtx *p;
82840   p = sqlite3_aggregate_context(context, 0);
82841   if( p && p->cnt>0 ){
82842     sqlite3_result_double(context, p->rSum/(double)p->cnt);
82843   }
82844 }
82845 static void totalFinalize(sqlite3_context *context){
82846   SumCtx *p;
82847   p = sqlite3_aggregate_context(context, 0);
82848   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82849   sqlite3_result_double(context, p ? p->rSum : (double)0);
82850 }
82851
82852 /*
82853 ** The following structure keeps track of state information for the
82854 ** count() aggregate function.
82855 */
82856 typedef struct CountCtx CountCtx;
82857 struct CountCtx {
82858   i64 n;
82859 };
82860
82861 /*
82862 ** Routines to implement the count() aggregate function.
82863 */
82864 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
82865   CountCtx *p;
82866   p = sqlite3_aggregate_context(context, sizeof(*p));
82867   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
82868     p->n++;
82869   }
82870
82871 #ifndef SQLITE_OMIT_DEPRECATED
82872   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
82873   ** sure it still operates correctly, verify that its count agrees with our 
82874   ** internal count when using count(*) and when the total count can be
82875   ** expressed as a 32-bit integer. */
82876   assert( argc==1 || p==0 || p->n>0x7fffffff
82877           || p->n==sqlite3_aggregate_count(context) );
82878 #endif
82879 }   
82880 static void countFinalize(sqlite3_context *context){
82881   CountCtx *p;
82882   p = sqlite3_aggregate_context(context, 0);
82883   sqlite3_result_int64(context, p ? p->n : 0);
82884 }
82885
82886 /*
82887 ** Routines to implement min() and max() aggregate functions.
82888 */
82889 static void minmaxStep(
82890   sqlite3_context *context, 
82891   int NotUsed, 
82892   sqlite3_value **argv
82893 ){
82894   Mem *pArg  = (Mem *)argv[0];
82895   Mem *pBest;
82896   UNUSED_PARAMETER(NotUsed);
82897
82898   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82899   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
82900   if( !pBest ) return;
82901
82902   if( pBest->flags ){
82903     int max;
82904     int cmp;
82905     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82906     /* This step function is used for both the min() and max() aggregates,
82907     ** the only difference between the two being that the sense of the
82908     ** comparison is inverted. For the max() aggregate, the
82909     ** sqlite3_user_data() function returns (void *)-1. For min() it
82910     ** returns (void *)db, where db is the sqlite3* database pointer.
82911     ** Therefore the next statement sets variable 'max' to 1 for the max()
82912     ** aggregate, or 0 for min().
82913     */
82914     max = sqlite3_user_data(context)!=0;
82915     cmp = sqlite3MemCompare(pBest, pArg, pColl);
82916     if( (max && cmp<0) || (!max && cmp>0) ){
82917       sqlite3VdbeMemCopy(pBest, pArg);
82918     }
82919   }else{
82920     sqlite3VdbeMemCopy(pBest, pArg);
82921   }
82922 }
82923 static void minMaxFinalize(sqlite3_context *context){
82924   sqlite3_value *pRes;
82925   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
82926   if( pRes ){
82927     if( ALWAYS(pRes->flags) ){
82928       sqlite3_result_value(context, pRes);
82929     }
82930     sqlite3VdbeMemRelease(pRes);
82931   }
82932 }
82933
82934 /*
82935 ** group_concat(EXPR, ?SEPARATOR?)
82936 */
82937 static void groupConcatStep(
82938   sqlite3_context *context,
82939   int argc,
82940   sqlite3_value **argv
82941 ){
82942   const char *zVal;
82943   StrAccum *pAccum;
82944   const char *zSep;
82945   int nVal, nSep;
82946   assert( argc==1 || argc==2 );
82947   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82948   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
82949
82950   if( pAccum ){
82951     sqlite3 *db = sqlite3_context_db_handle(context);
82952     int firstTerm = pAccum->useMalloc==0;
82953     pAccum->useMalloc = 2;
82954     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
82955     if( !firstTerm ){
82956       if( argc==2 ){
82957         zSep = (char*)sqlite3_value_text(argv[1]);
82958         nSep = sqlite3_value_bytes(argv[1]);
82959       }else{
82960         zSep = ",";
82961         nSep = 1;
82962       }
82963       sqlite3StrAccumAppend(pAccum, zSep, nSep);
82964     }
82965     zVal = (char*)sqlite3_value_text(argv[0]);
82966     nVal = sqlite3_value_bytes(argv[0]);
82967     sqlite3StrAccumAppend(pAccum, zVal, nVal);
82968   }
82969 }
82970 static void groupConcatFinalize(sqlite3_context *context){
82971   StrAccum *pAccum;
82972   pAccum = sqlite3_aggregate_context(context, 0);
82973   if( pAccum ){
82974     if( pAccum->tooBig ){
82975       sqlite3_result_error_toobig(context);
82976     }else if( pAccum->mallocFailed ){
82977       sqlite3_result_error_nomem(context);
82978     }else{    
82979       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
82980                           sqlite3_free);
82981     }
82982   }
82983 }
82984
82985 /*
82986 ** This routine does per-connection function registration.  Most
82987 ** of the built-in functions above are part of the global function set.
82988 ** This routine only deals with those that are not global.
82989 */
82990 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
82991   int rc = sqlite3_overload_function(db, "MATCH", 2);
82992   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
82993   if( rc==SQLITE_NOMEM ){
82994     db->mallocFailed = 1;
82995   }
82996 }
82997
82998 /*
82999 ** Set the LIKEOPT flag on the 2-argument function with the given name.
83000 */
83001 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
83002   FuncDef *pDef;
83003   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
83004                              2, SQLITE_UTF8, 0);
83005   if( ALWAYS(pDef) ){
83006     pDef->flags = flagVal;
83007   }
83008 }
83009
83010 /*
83011 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
83012 ** parameter determines whether or not the LIKE operator is case
83013 ** sensitive.  GLOB is always case sensitive.
83014 */
83015 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83016   struct compareInfo *pInfo;
83017   if( caseSensitive ){
83018     pInfo = (struct compareInfo*)&likeInfoAlt;
83019   }else{
83020     pInfo = (struct compareInfo*)&likeInfoNorm;
83021   }
83022   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83023   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83024   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
83025       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83026   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83027   setLikeOptFlag(db, "like", 
83028       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83029 }
83030
83031 /*
83032 ** pExpr points to an expression which implements a function.  If
83033 ** it is appropriate to apply the LIKE optimization to that function
83034 ** then set aWc[0] through aWc[2] to the wildcard characters and
83035 ** return TRUE.  If the function is not a LIKE-style function then
83036 ** return FALSE.
83037 */
83038 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83039   FuncDef *pDef;
83040   if( pExpr->op!=TK_FUNCTION 
83041    || !pExpr->x.pList 
83042    || pExpr->x.pList->nExpr!=2
83043   ){
83044     return 0;
83045   }
83046   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83047   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
83048                              sqlite3Strlen30(pExpr->u.zToken),
83049                              2, SQLITE_UTF8, 0);
83050   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83051     return 0;
83052   }
83053
83054   /* The memcpy() statement assumes that the wildcard characters are
83055   ** the first three statements in the compareInfo structure.  The
83056   ** asserts() that follow verify that assumption
83057   */
83058   memcpy(aWc, pDef->pUserData, 3);
83059   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83060   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83061   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83062   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83063   return 1;
83064 }
83065
83066 /*
83067 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
83068 ** to the global function hash table.  This occurs at start-time (as
83069 ** a consequence of calling sqlite3_initialize()).
83070 **
83071 ** After this routine runs
83072 */
83073 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83074   /*
83075   ** The following array holds FuncDef structures for all of the functions
83076   ** defined in this file.
83077   **
83078   ** The array cannot be constant since changes are made to the
83079   ** FuncDef.pHash elements at start-time.  The elements of this array
83080   ** are read-only after initialization is complete.
83081   */
83082   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83083     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
83084     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
83085     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
83086     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
83087     FUNCTION(trim,               1, 3, 0, trimFunc         ),
83088     FUNCTION(trim,               2, 3, 0, trimFunc         ),
83089     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
83090     FUNCTION(min,                0, 0, 1, 0                ),
83091     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
83092     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
83093     FUNCTION(max,                0, 1, 1, 0                ),
83094     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
83095     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
83096     FUNCTION(length,             1, 0, 0, lengthFunc       ),
83097     FUNCTION(substr,             2, 0, 0, substrFunc       ),
83098     FUNCTION(substr,             3, 0, 0, substrFunc       ),
83099     FUNCTION(abs,                1, 0, 0, absFunc          ),
83100 #ifndef SQLITE_OMIT_FLOATING_POINT
83101     FUNCTION(round,              1, 0, 0, roundFunc        ),
83102     FUNCTION(round,              2, 0, 0, roundFunc        ),
83103 #endif
83104     FUNCTION(upper,              1, 0, 0, upperFunc        ),
83105     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
83106     FUNCTION(coalesce,           1, 0, 0, 0                ),
83107     FUNCTION(coalesce,           0, 0, 0, 0                ),
83108 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
83109     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83110     FUNCTION(hex,                1, 0, 0, hexFunc          ),
83111 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
83112     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83113     FUNCTION(random,             0, 0, 0, randomFunc       ),
83114     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
83115     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
83116     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
83117     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
83118 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83119     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
83120     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
83121 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83122     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
83123     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
83124     FUNCTION(changes,            0, 0, 0, changes          ),
83125     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
83126     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
83127     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
83128   #ifdef SQLITE_SOUNDEX
83129     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
83130   #endif
83131   #ifndef SQLITE_OMIT_LOAD_EXTENSION
83132     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
83133     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
83134   #endif
83135     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
83136     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
83137     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
83138  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
83139     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83140     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
83141     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
83142     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
83143   
83144     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83145   #ifdef SQLITE_CASE_SENSITIVE_LIKE
83146     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83147     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83148   #else
83149     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83150     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83151   #endif
83152   };
83153
83154   int i;
83155   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83156   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83157
83158   for(i=0; i<ArraySize(aBuiltinFunc); i++){
83159     sqlite3FuncDefInsert(pHash, &aFunc[i]);
83160   }
83161   sqlite3RegisterDateTimeFunctions();
83162 #ifndef SQLITE_OMIT_ALTERTABLE
83163   sqlite3AlterFunctions();
83164 #endif
83165 }
83166
83167 /************** End of func.c ************************************************/
83168 /************** Begin file fkey.c ********************************************/
83169 /*
83170 **
83171 ** The author disclaims copyright to this source code.  In place of
83172 ** a legal notice, here is a blessing:
83173 **
83174 **    May you do good and not evil.
83175 **    May you find forgiveness for yourself and forgive others.
83176 **    May you share freely, never taking more than you give.
83177 **
83178 *************************************************************************
83179 ** This file contains code used by the compiler to add foreign key
83180 ** support to compiled SQL statements.
83181 */
83182
83183 #ifndef SQLITE_OMIT_FOREIGN_KEY
83184 #ifndef SQLITE_OMIT_TRIGGER
83185
83186 /*
83187 ** Deferred and Immediate FKs
83188 ** --------------------------
83189 **
83190 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
83191 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83192 ** is returned and the current statement transaction rolled back. If a 
83193 ** deferred foreign key constraint is violated, no action is taken 
83194 ** immediately. However if the application attempts to commit the 
83195 ** transaction before fixing the constraint violation, the attempt fails.
83196 **
83197 ** Deferred constraints are implemented using a simple counter associated
83198 ** with the database handle. The counter is set to zero each time a 
83199 ** database transaction is opened. Each time a statement is executed 
83200 ** that causes a foreign key violation, the counter is incremented. Each
83201 ** time a statement is executed that removes an existing violation from
83202 ** the database, the counter is decremented. When the transaction is
83203 ** committed, the commit fails if the current value of the counter is
83204 ** greater than zero. This scheme has two big drawbacks:
83205 **
83206 **   * When a commit fails due to a deferred foreign key constraint, 
83207 **     there is no way to tell which foreign constraint is not satisfied,
83208 **     or which row it is not satisfied for.
83209 **
83210 **   * If the database contains foreign key violations when the 
83211 **     transaction is opened, this may cause the mechanism to malfunction.
83212 **
83213 ** Despite these problems, this approach is adopted as it seems simpler
83214 ** than the alternatives.
83215 **
83216 ** INSERT operations:
83217 **
83218 **   I.1) For each FK for which the table is the child table, search
83219 **        the parent table for a match. If none is found increment the
83220 **        constraint counter.
83221 **
83222 **   I.2) For each FK for which the table is the parent table, 
83223 **        search the child table for rows that correspond to the new
83224 **        row in the parent table. Decrement the counter for each row
83225 **        found (as the constraint is now satisfied).
83226 **
83227 ** DELETE operations:
83228 **
83229 **   D.1) For each FK for which the table is the child table, 
83230 **        search the parent table for a row that corresponds to the 
83231 **        deleted row in the child table. If such a row is not found, 
83232 **        decrement the counter.
83233 **
83234 **   D.2) For each FK for which the table is the parent table, search 
83235 **        the child table for rows that correspond to the deleted row 
83236 **        in the parent table. For each found increment the counter.
83237 **
83238 ** UPDATE operations:
83239 **
83240 **   An UPDATE command requires that all 4 steps above are taken, but only
83241 **   for FK constraints for which the affected columns are actually 
83242 **   modified (values must be compared at runtime).
83243 **
83244 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83245 ** This simplifies the implementation a bit.
83246 **
83247 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
83248 ** resolution is considered to delete rows before the new row is inserted.
83249 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83250 ** is thrown, even if the FK constraint would be satisfied after the new 
83251 ** row is inserted.
83252 **
83253 ** Immediate constraints are usually handled similarly. The only difference 
83254 ** is that the counter used is stored as part of each individual statement
83255 ** object (struct Vdbe). If, after the statement has run, its immediate
83256 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83257 ** and the statement transaction is rolled back. An exception is an INSERT
83258 ** statement that inserts a single row only (no triggers). In this case,
83259 ** instead of using a counter, an exception is thrown immediately if the
83260 ** INSERT violates a foreign key constraint. This is necessary as such
83261 ** an INSERT does not open a statement transaction.
83262 **
83263 ** TODO: How should dropping a table be handled? How should renaming a 
83264 ** table be handled?
83265 **
83266 **
83267 ** Query API Notes
83268 ** ---------------
83269 **
83270 ** Before coding an UPDATE or DELETE row operation, the code-generator
83271 ** for those two operations needs to know whether or not the operation
83272 ** requires any FK processing and, if so, which columns of the original
83273 ** row are required by the FK processing VDBE code (i.e. if FKs were
83274 ** implemented using triggers, which of the old.* columns would be 
83275 ** accessed). No information is required by the code-generator before
83276 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
83277 ** generation code to query for this information are:
83278 **
83279 **   sqlite3FkRequired() - Test to see if FK processing is required.
83280 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
83281 **
83282 **
83283 ** Externally accessible module functions
83284 ** --------------------------------------
83285 **
83286 **   sqlite3FkCheck()    - Check for foreign key violations.
83287 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
83288 **   sqlite3FkDelete()   - Delete an FKey structure.
83289 */
83290
83291 /*
83292 ** VDBE Calling Convention
83293 ** -----------------------
83294 **
83295 ** Example:
83296 **
83297 **   For the following INSERT statement:
83298 **
83299 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83300 **     INSERT INTO t1 VALUES(1, 2, 3.1);
83301 **
83302 **   Register (x):        2    (type integer)
83303 **   Register (x+1):      1    (type integer)
83304 **   Register (x+2):      NULL (type NULL)
83305 **   Register (x+3):      3.1  (type real)
83306 */
83307
83308 /*
83309 ** A foreign key constraint requires that the key columns in the parent
83310 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83311 ** Given that pParent is the parent table for foreign key constraint pFKey, 
83312 ** search the schema a unique index on the parent key columns. 
83313 **
83314 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
83315 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
83316 ** is set to point to the unique index. 
83317 ** 
83318 ** If the parent key consists of a single column (the foreign key constraint
83319 ** is not a composite foreign key), output variable *paiCol is set to NULL.
83320 ** Otherwise, it is set to point to an allocated array of size N, where
83321 ** N is the number of columns in the parent key. The first element of the
83322 ** array is the index of the child table column that is mapped by the FK
83323 ** constraint to the parent table column stored in the left-most column
83324 ** of index *ppIdx. The second element of the array is the index of the
83325 ** child table column that corresponds to the second left-most column of
83326 ** *ppIdx, and so on.
83327 **
83328 ** If the required index cannot be found, either because:
83329 **
83330 **   1) The named parent key columns do not exist, or
83331 **
83332 **   2) The named parent key columns do exist, but are not subject to a
83333 **      UNIQUE or PRIMARY KEY constraint, or
83334 **
83335 **   3) No parent key columns were provided explicitly as part of the
83336 **      foreign key definition, and the parent table does not have a
83337 **      PRIMARY KEY, or
83338 **
83339 **   4) No parent key columns were provided explicitly as part of the
83340 **      foreign key definition, and the PRIMARY KEY of the parent table 
83341 **      consists of a a different number of columns to the child key in 
83342 **      the child table.
83343 **
83344 ** then non-zero is returned, and a "foreign key mismatch" error loaded
83345 ** into pParse. If an OOM error occurs, non-zero is returned and the
83346 ** pParse->db->mallocFailed flag is set.
83347 */
83348 static int locateFkeyIndex(
83349   Parse *pParse,                  /* Parse context to store any error in */
83350   Table *pParent,                 /* Parent table of FK constraint pFKey */
83351   FKey *pFKey,                    /* Foreign key to find index for */
83352   Index **ppIdx,                  /* OUT: Unique index on parent table */
83353   int **paiCol                    /* OUT: Map of index columns in pFKey */
83354 ){
83355   Index *pIdx = 0;                    /* Value to return via *ppIdx */
83356   int *aiCol = 0;                     /* Value to return via *paiCol */
83357   int nCol = pFKey->nCol;             /* Number of columns in parent key */
83358   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
83359
83360   /* The caller is responsible for zeroing output parameters. */
83361   assert( ppIdx && *ppIdx==0 );
83362   assert( !paiCol || *paiCol==0 );
83363   assert( pParse );
83364
83365   /* If this is a non-composite (single column) foreign key, check if it 
83366   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
83367   ** and *paiCol set to zero and return early. 
83368   **
83369   ** Otherwise, for a composite foreign key (more than one column), allocate
83370   ** space for the aiCol array (returned via output parameter *paiCol).
83371   ** Non-composite foreign keys do not require the aiCol array.
83372   */
83373   if( nCol==1 ){
83374     /* The FK maps to the IPK if any of the following are true:
83375     **
83376     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
83377     **      mapped to the primary key of table pParent, or
83378     **   2) The FK is explicitly mapped to a column declared as INTEGER
83379     **      PRIMARY KEY.
83380     */
83381     if( pParent->iPKey>=0 ){
83382       if( !zKey ) return 0;
83383       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
83384     }
83385   }else if( paiCol ){
83386     assert( nCol>1 );
83387     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
83388     if( !aiCol ) return 1;
83389     *paiCol = aiCol;
83390   }
83391
83392   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
83393     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
83394       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
83395       ** of columns. If each indexed column corresponds to a foreign key
83396       ** column of pFKey, then this index is a winner.  */
83397
83398       if( zKey==0 ){
83399         /* If zKey is NULL, then this foreign key is implicitly mapped to 
83400         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
83401         ** identified by the test (Index.autoIndex==2).  */
83402         if( pIdx->autoIndex==2 ){
83403           if( aiCol ){
83404             int i;
83405             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
83406           }
83407           break;
83408         }
83409       }else{
83410         /* If zKey is non-NULL, then this foreign key was declared to
83411         ** map to an explicit list of columns in table pParent. Check if this
83412         ** index matches those columns. Also, check that the index uses
83413         ** the default collation sequences for each column. */
83414         int i, j;
83415         for(i=0; i<nCol; i++){
83416           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
83417           char *zDfltColl;                  /* Def. collation for column */
83418           char *zIdxCol;                    /* Name of indexed column */
83419
83420           /* If the index uses a collation sequence that is different from
83421           ** the default collation sequence for the column, this index is
83422           ** unusable. Bail out early in this case.  */
83423           zDfltColl = pParent->aCol[iCol].zColl;
83424           if( !zDfltColl ){
83425             zDfltColl = "BINARY";
83426           }
83427           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
83428
83429           zIdxCol = pParent->aCol[iCol].zName;
83430           for(j=0; j<nCol; j++){
83431             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
83432               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
83433               break;
83434             }
83435           }
83436           if( j==nCol ) break;
83437         }
83438         if( i==nCol ) break;      /* pIdx is usable */
83439       }
83440     }
83441   }
83442
83443   if( !pIdx ){
83444     if( !pParse->disableTriggers ){
83445       sqlite3ErrorMsg(pParse, "foreign key mismatch");
83446     }
83447     sqlite3DbFree(pParse->db, aiCol);
83448     return 1;
83449   }
83450
83451   *ppIdx = pIdx;
83452   return 0;
83453 }
83454
83455 /*
83456 ** This function is called when a row is inserted into or deleted from the 
83457 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
83458 ** on the child table of pFKey, this function is invoked twice for each row
83459 ** affected - once to "delete" the old row, and then again to "insert" the
83460 ** new row.
83461 **
83462 ** Each time it is called, this function generates VDBE code to locate the
83463 ** row in the parent table that corresponds to the row being inserted into 
83464 ** or deleted from the child table. If the parent row can be found, no 
83465 ** special action is taken. Otherwise, if the parent row can *not* be
83466 ** found in the parent table:
83467 **
83468 **   Operation | FK type   | Action taken
83469 **   --------------------------------------------------------------------------
83470 **   INSERT      immediate   Increment the "immediate constraint counter".
83471 **
83472 **   DELETE      immediate   Decrement the "immediate constraint counter".
83473 **
83474 **   INSERT      deferred    Increment the "deferred constraint counter".
83475 **
83476 **   DELETE      deferred    Decrement the "deferred constraint counter".
83477 **
83478 ** These operations are identified in the comment at the top of this file 
83479 ** (fkey.c) as "I.1" and "D.1".
83480 */
83481 static void fkLookupParent(
83482   Parse *pParse,        /* Parse context */
83483   int iDb,              /* Index of database housing pTab */
83484   Table *pTab,          /* Parent table of FK pFKey */
83485   Index *pIdx,          /* Unique index on parent key columns in pTab */
83486   FKey *pFKey,          /* Foreign key constraint */
83487   int *aiCol,           /* Map from parent key columns to child table columns */
83488   int regData,          /* Address of array containing child table row */
83489   int nIncr,            /* Increment constraint counter by this */
83490   int isIgnore          /* If true, pretend pTab contains all NULL values */
83491 ){
83492   int i;                                    /* Iterator variable */
83493   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
83494   int iCur = pParse->nTab - 1;              /* Cursor number to use */
83495   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
83496
83497   /* If nIncr is less than zero, then check at runtime if there are any
83498   ** outstanding constraints to resolve. If there are not, there is no need
83499   ** to check if deleting this row resolves any outstanding violations.
83500   **
83501   ** Check if any of the key columns in the child table row are NULL. If 
83502   ** any are, then the constraint is considered satisfied. No need to 
83503   ** search for a matching row in the parent table.  */
83504   if( nIncr<0 ){
83505     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
83506   }
83507   for(i=0; i<pFKey->nCol; i++){
83508     int iReg = aiCol[i] + regData + 1;
83509     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
83510   }
83511
83512   if( isIgnore==0 ){
83513     if( pIdx==0 ){
83514       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
83515       ** column of the parent table (table pTab).  */
83516       int iMustBeInt;               /* Address of MustBeInt instruction */
83517       int regTemp = sqlite3GetTempReg(pParse);
83518   
83519       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
83520       ** apply the affinity of the parent key). If this fails, then there
83521       ** is no matching parent key. Before using MustBeInt, make a copy of
83522       ** the value. Otherwise, the value inserted into the child key column
83523       ** will have INTEGER affinity applied to it, which may not be correct.  */
83524       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
83525       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
83526   
83527       /* If the parent table is the same as the child table, and we are about
83528       ** to increment the constraint-counter (i.e. this is an INSERT operation),
83529       ** then check if the row being inserted matches itself. If so, do not
83530       ** increment the constraint-counter.  */
83531       if( pTab==pFKey->pFrom && nIncr==1 ){
83532         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
83533       }
83534   
83535       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
83536       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
83537       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83538       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
83539       sqlite3VdbeJumpHere(v, iMustBeInt);
83540       sqlite3ReleaseTempReg(pParse, regTemp);
83541     }else{
83542       int nCol = pFKey->nCol;
83543       int regTemp = sqlite3GetTempRange(pParse, nCol);
83544       int regRec = sqlite3GetTempReg(pParse);
83545       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83546   
83547       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
83548       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
83549       for(i=0; i<nCol; i++){
83550         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
83551       }
83552   
83553       /* If the parent table is the same as the child table, and we are about
83554       ** to increment the constraint-counter (i.e. this is an INSERT operation),
83555       ** then check if the row being inserted matches itself. If so, do not
83556       ** increment the constraint-counter.  */
83557       if( pTab==pFKey->pFrom && nIncr==1 ){
83558         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
83559         for(i=0; i<nCol; i++){
83560           int iChild = aiCol[i]+1+regData;
83561           int iParent = pIdx->aiColumn[i]+1+regData;
83562           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
83563         }
83564         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83565       }
83566   
83567       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
83568       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
83569       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
83570   
83571       sqlite3ReleaseTempReg(pParse, regRec);
83572       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
83573     }
83574   }
83575
83576   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83577     /* Special case: If this is an INSERT statement that will insert exactly
83578     ** one row into the table, raise a constraint immediately instead of
83579     ** incrementing a counter. This is necessary as the VM code is being
83580     ** generated for will not open a statement transaction.  */
83581     assert( nIncr==1 );
83582     sqlite3HaltConstraint(
83583         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83584     );
83585   }else{
83586     if( nIncr>0 && pFKey->isDeferred==0 ){
83587       sqlite3ParseToplevel(pParse)->mayAbort = 1;
83588     }
83589     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83590   }
83591
83592   sqlite3VdbeResolveLabel(v, iOk);
83593   sqlite3VdbeAddOp1(v, OP_Close, iCur);
83594 }
83595
83596 /*
83597 ** This function is called to generate code executed when a row is deleted
83598 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
83599 ** deferred, when a row is inserted into the same table. When generating
83600 ** code for an SQL UPDATE operation, this function may be called twice -
83601 ** once to "delete" the old row and once to "insert" the new row.
83602 **
83603 ** The code generated by this function scans through the rows in the child
83604 ** table that correspond to the parent table row being deleted or inserted.
83605 ** For each child row found, one of the following actions is taken:
83606 **
83607 **   Operation | FK type   | Action taken
83608 **   --------------------------------------------------------------------------
83609 **   DELETE      immediate   Increment the "immediate constraint counter".
83610 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83611 **                           throw a "foreign key constraint failed" exception.
83612 **
83613 **   INSERT      immediate   Decrement the "immediate constraint counter".
83614 **
83615 **   DELETE      deferred    Increment the "deferred constraint counter".
83616 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83617 **                           throw a "foreign key constraint failed" exception.
83618 **
83619 **   INSERT      deferred    Decrement the "deferred constraint counter".
83620 **
83621 ** These operations are identified in the comment at the top of this file 
83622 ** (fkey.c) as "I.2" and "D.2".
83623 */
83624 static void fkScanChildren(
83625   Parse *pParse,                  /* Parse context */
83626   SrcList *pSrc,                  /* SrcList containing the table to scan */
83627   Table *pTab,
83628   Index *pIdx,                    /* Foreign key index */
83629   FKey *pFKey,                    /* Foreign key relationship */
83630   int *aiCol,                     /* Map from pIdx cols to child table cols */
83631   int regData,                    /* Referenced table data starts here */
83632   int nIncr                       /* Amount to increment deferred counter by */
83633 ){
83634   sqlite3 *db = pParse->db;       /* Database handle */
83635   int i;                          /* Iterator variable */
83636   Expr *pWhere = 0;               /* WHERE clause to scan with */
83637   NameContext sNameContext;       /* Context used to resolve WHERE clause */
83638   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
83639   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
83640   Vdbe *v = sqlite3GetVdbe(pParse);
83641
83642   assert( !pIdx || pIdx->pTable==pTab );
83643
83644   if( nIncr<0 ){
83645     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
83646   }
83647
83648   /* Create an Expr object representing an SQL expression like:
83649   **
83650   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
83651   **
83652   ** The collation sequence used for the comparison should be that of
83653   ** the parent key columns. The affinity of the parent key column should
83654   ** be applied to each child key value before the comparison takes place.
83655   */
83656   for(i=0; i<pFKey->nCol; i++){
83657     Expr *pLeft;                  /* Value from parent table row */
83658     Expr *pRight;                 /* Column ref to child table */
83659     Expr *pEq;                    /* Expression (pLeft = pRight) */
83660     int iCol;                     /* Index of column in child table */ 
83661     const char *zCol;             /* Name of column in child table */
83662
83663     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83664     if( pLeft ){
83665       /* Set the collation sequence and affinity of the LHS of each TK_EQ
83666       ** expression to the parent key column defaults.  */
83667       if( pIdx ){
83668         Column *pCol;
83669         iCol = pIdx->aiColumn[i];
83670         pCol = &pTab->aCol[iCol];
83671         if( pTab->iPKey==iCol ) iCol = -1;
83672         pLeft->iTable = regData+iCol+1;
83673         pLeft->affinity = pCol->affinity;
83674         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
83675       }else{
83676         pLeft->iTable = regData;
83677         pLeft->affinity = SQLITE_AFF_INTEGER;
83678       }
83679     }
83680     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
83681     assert( iCol>=0 );
83682     zCol = pFKey->pFrom->aCol[iCol].zName;
83683     pRight = sqlite3Expr(db, TK_ID, zCol);
83684     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
83685     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83686   }
83687
83688   /* If the child table is the same as the parent table, and this scan
83689   ** is taking place as part of a DELETE operation (operation D.2), omit the
83690   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
83691   ** clause, where $rowid is the rowid of the row being deleted.  */
83692   if( pTab==pFKey->pFrom && nIncr>0 ){
83693     Expr *pEq;                    /* Expression (pLeft = pRight) */
83694     Expr *pLeft;                  /* Value from parent table row */
83695     Expr *pRight;                 /* Column ref to child table */
83696     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83697     pRight = sqlite3Expr(db, TK_COLUMN, 0);
83698     if( pLeft && pRight ){
83699       pLeft->iTable = regData;
83700       pLeft->affinity = SQLITE_AFF_INTEGER;
83701       pRight->iTable = pSrc->a[0].iCursor;
83702       pRight->iColumn = -1;
83703     }
83704     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
83705     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
83706   }
83707
83708   /* Resolve the references in the WHERE clause. */
83709   memset(&sNameContext, 0, sizeof(NameContext));
83710   sNameContext.pSrcList = pSrc;
83711   sNameContext.pParse = pParse;
83712   sqlite3ResolveExprNames(&sNameContext, pWhere);
83713
83714   /* Create VDBE to loop through the entries in pSrc that match the WHERE
83715   ** clause. If the constraint is not deferred, throw an exception for
83716   ** each row found. Otherwise, for deferred constraints, increment the
83717   ** deferred constraint counter by nIncr for each row selected.  */
83718   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
83719   if( nIncr>0 && pFKey->isDeferred==0 ){
83720     sqlite3ParseToplevel(pParse)->mayAbort = 1;
83721   }
83722   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83723   if( pWInfo ){
83724     sqlite3WhereEnd(pWInfo);
83725   }
83726
83727   /* Clean up the WHERE clause constructed above. */
83728   sqlite3ExprDelete(db, pWhere);
83729   if( iFkIfZero ){
83730     sqlite3VdbeJumpHere(v, iFkIfZero);
83731   }
83732 }
83733
83734 /*
83735 ** This function returns a pointer to the head of a linked list of FK
83736 ** constraints for which table pTab is the parent table. For example,
83737 ** given the following schema:
83738 **
83739 **   CREATE TABLE t1(a PRIMARY KEY);
83740 **   CREATE TABLE t2(b REFERENCES t1(a);
83741 **
83742 ** Calling this function with table "t1" as an argument returns a pointer
83743 ** to the FKey structure representing the foreign key constraint on table
83744 ** "t2". Calling this function with "t2" as the argument would return a
83745 ** NULL pointer (as there are no FK constraints for which t2 is the parent
83746 ** table).
83747 */
83748 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
83749   int nName = sqlite3Strlen30(pTab->zName);
83750   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
83751 }
83752
83753 /*
83754 ** The second argument is a Trigger structure allocated by the 
83755 ** fkActionTrigger() routine. This function deletes the Trigger structure
83756 ** and all of its sub-components.
83757 **
83758 ** The Trigger structure or any of its sub-components may be allocated from
83759 ** the lookaside buffer belonging to database handle dbMem.
83760 */
83761 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
83762   if( p ){
83763     TriggerStep *pStep = p->step_list;
83764     sqlite3ExprDelete(dbMem, pStep->pWhere);
83765     sqlite3ExprListDelete(dbMem, pStep->pExprList);
83766     sqlite3SelectDelete(dbMem, pStep->pSelect);
83767     sqlite3ExprDelete(dbMem, p->pWhen);
83768     sqlite3DbFree(dbMem, p);
83769   }
83770 }
83771
83772 /*
83773 ** This function is called to generate code that runs when table pTab is
83774 ** being dropped from the database. The SrcList passed as the second argument
83775 ** to this function contains a single entry guaranteed to resolve to
83776 ** table pTab.
83777 **
83778 ** Normally, no code is required. However, if either
83779 **
83780 **   (a) The table is the parent table of a FK constraint, or
83781 **   (b) The table is the child table of a deferred FK constraint and it is
83782 **       determined at runtime that there are outstanding deferred FK 
83783 **       constraint violations in the database,
83784 **
83785 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
83786 ** the table from the database. Triggers are disabled while running this
83787 ** DELETE, but foreign key actions are not.
83788 */
83789 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
83790   sqlite3 *db = pParse->db;
83791   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
83792     int iSkip = 0;
83793     Vdbe *v = sqlite3GetVdbe(pParse);
83794
83795     assert( v );                  /* VDBE has already been allocated */
83796     if( sqlite3FkReferences(pTab)==0 ){
83797       /* Search for a deferred foreign key constraint for which this table
83798       ** is the child table. If one cannot be found, return without 
83799       ** generating any VDBE code. If one can be found, then jump over
83800       ** the entire DELETE if there are no outstanding deferred constraints
83801       ** when this statement is run.  */
83802       FKey *p;
83803       for(p=pTab->pFKey; p; p=p->pNextFrom){
83804         if( p->isDeferred ) break;
83805       }
83806       if( !p ) return;
83807       iSkip = sqlite3VdbeMakeLabel(v);
83808       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
83809     }
83810
83811     pParse->disableTriggers = 1;
83812     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
83813     pParse->disableTriggers = 0;
83814
83815     /* If the DELETE has generated immediate foreign key constraint 
83816     ** violations, halt the VDBE and return an error at this point, before
83817     ** any modifications to the schema are made. This is because statement
83818     ** transactions are not able to rollback schema changes.  */
83819     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
83820     sqlite3HaltConstraint(
83821         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83822     );
83823
83824     if( iSkip ){
83825       sqlite3VdbeResolveLabel(v, iSkip);
83826     }
83827   }
83828 }
83829
83830 /*
83831 ** This function is called when inserting, deleting or updating a row of
83832 ** table pTab to generate VDBE code to perform foreign key constraint 
83833 ** processing for the operation.
83834 **
83835 ** For a DELETE operation, parameter regOld is passed the index of the
83836 ** first register in an array of (pTab->nCol+1) registers containing the
83837 ** rowid of the row being deleted, followed by each of the column values
83838 ** of the row being deleted, from left to right. Parameter regNew is passed
83839 ** zero in this case.
83840 **
83841 ** For an INSERT operation, regOld is passed zero and regNew is passed the
83842 ** first register of an array of (pTab->nCol+1) registers containing the new
83843 ** row data.
83844 **
83845 ** For an UPDATE operation, this function is called twice. Once before
83846 ** the original record is deleted from the table using the calling convention
83847 ** described for DELETE. Then again after the original record is deleted
83848 ** but before the new record is inserted using the INSERT convention. 
83849 */
83850 SQLITE_PRIVATE void sqlite3FkCheck(
83851   Parse *pParse,                  /* Parse context */
83852   Table *pTab,                    /* Row is being deleted from this table */ 
83853   int regOld,                     /* Previous row data is stored here */
83854   int regNew                      /* New row data is stored here */
83855 ){
83856   sqlite3 *db = pParse->db;       /* Database handle */
83857   FKey *pFKey;                    /* Used to iterate through FKs */
83858   int iDb;                        /* Index of database containing pTab */
83859   const char *zDb;                /* Name of database containing pTab */
83860   int isIgnoreErrors = pParse->disableTriggers;
83861
83862   /* Exactly one of regOld and regNew should be non-zero. */
83863   assert( (regOld==0)!=(regNew==0) );
83864
83865   /* If foreign-keys are disabled, this function is a no-op. */
83866   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
83867
83868   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83869   zDb = db->aDb[iDb].zName;
83870
83871   /* Loop through all the foreign key constraints for which pTab is the
83872   ** child table (the table that the foreign key definition is part of).  */
83873   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
83874     Table *pTo;                   /* Parent table of foreign key pFKey */
83875     Index *pIdx = 0;              /* Index on key columns in pTo */
83876     int *aiFree = 0;
83877     int *aiCol;
83878     int iCol;
83879     int i;
83880     int isIgnore = 0;
83881
83882     /* Find the parent table of this foreign key. Also find a unique index 
83883     ** on the parent key columns in the parent table. If either of these 
83884     ** schema items cannot be located, set an error in pParse and return 
83885     ** early.  */
83886     if( pParse->disableTriggers ){
83887       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
83888     }else{
83889       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
83890     }
83891     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
83892       if( !isIgnoreErrors || db->mallocFailed ) return;
83893       continue;
83894     }
83895     assert( pFKey->nCol==1 || (aiFree && pIdx) );
83896
83897     if( aiFree ){
83898       aiCol = aiFree;
83899     }else{
83900       iCol = pFKey->aCol[0].iFrom;
83901       aiCol = &iCol;
83902     }
83903     for(i=0; i<pFKey->nCol; i++){
83904       if( aiCol[i]==pTab->iPKey ){
83905         aiCol[i] = -1;
83906       }
83907 #ifndef SQLITE_OMIT_AUTHORIZATION
83908       /* Request permission to read the parent key columns. If the 
83909       ** authorization callback returns SQLITE_IGNORE, behave as if any
83910       ** values read from the parent table are NULL. */
83911       if( db->xAuth ){
83912         int rcauth;
83913         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
83914         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
83915         isIgnore = (rcauth==SQLITE_IGNORE);
83916       }
83917 #endif
83918     }
83919
83920     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
83921     ** a cursor to use to search the unique index on the parent key columns 
83922     ** in the parent table.  */
83923     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
83924     pParse->nTab++;
83925
83926     if( regOld!=0 ){
83927       /* A row is being removed from the child table. Search for the parent.
83928       ** If the parent does not exist, removing the child row resolves an 
83929       ** outstanding foreign key constraint violation. */
83930       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
83931     }
83932     if( regNew!=0 ){
83933       /* A row is being added to the child table. If a parent row cannot
83934       ** be found, adding the child row has violated the FK constraint. */ 
83935       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
83936     }
83937
83938     sqlite3DbFree(db, aiFree);
83939   }
83940
83941   /* Loop through all the foreign key constraints that refer to this table */
83942   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
83943     Index *pIdx = 0;              /* Foreign key index for pFKey */
83944     SrcList *pSrc;
83945     int *aiCol = 0;
83946
83947     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83948       assert( regOld==0 && regNew!=0 );
83949       /* Inserting a single row into a parent table cannot cause an immediate
83950       ** foreign key violation. So do nothing in this case.  */
83951       continue;
83952     }
83953
83954     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
83955       if( !isIgnoreErrors || db->mallocFailed ) return;
83956       continue;
83957     }
83958     assert( aiCol || pFKey->nCol==1 );
83959
83960     /* Create a SrcList structure containing a single table (the table 
83961     ** the foreign key that refers to this table is attached to). This
83962     ** is required for the sqlite3WhereXXX() interface.  */
83963     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
83964     if( pSrc ){
83965       struct SrcList_item *pItem = pSrc->a;
83966       pItem->pTab = pFKey->pFrom;
83967       pItem->zName = pFKey->pFrom->zName;
83968       pItem->pTab->nRef++;
83969       pItem->iCursor = pParse->nTab++;
83970   
83971       if( regNew!=0 ){
83972         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
83973       }
83974       if( regOld!=0 ){
83975         /* If there is a RESTRICT action configured for the current operation
83976         ** on the parent table of this FK, then throw an exception 
83977         ** immediately if the FK constraint is violated, even if this is a
83978         ** deferred trigger. That's what RESTRICT means. To defer checking
83979         ** the constraint, the FK should specify NO ACTION (represented
83980         ** using OE_None). NO ACTION is the default.  */
83981         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
83982       }
83983       pItem->zName = 0;
83984       sqlite3SrcListDelete(db, pSrc);
83985     }
83986     sqlite3DbFree(db, aiCol);
83987   }
83988 }
83989
83990 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
83991
83992 /*
83993 ** This function is called before generating code to update or delete a 
83994 ** row contained in table pTab.
83995 */
83996 SQLITE_PRIVATE u32 sqlite3FkOldmask(
83997   Parse *pParse,                  /* Parse context */
83998   Table *pTab                     /* Table being modified */
83999 ){
84000   u32 mask = 0;
84001   if( pParse->db->flags&SQLITE_ForeignKeys ){
84002     FKey *p;
84003     int i;
84004     for(p=pTab->pFKey; p; p=p->pNextFrom){
84005       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
84006     }
84007     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84008       Index *pIdx = 0;
84009       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84010       if( pIdx ){
84011         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84012       }
84013     }
84014   }
84015   return mask;
84016 }
84017
84018 /*
84019 ** This function is called before generating code to update or delete a 
84020 ** row contained in table pTab. If the operation is a DELETE, then
84021 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84022 ** to an array of size N, where N is the number of columns in table pTab.
84023 ** If the i'th column is not modified by the UPDATE, then the corresponding 
84024 ** entry in the aChange[] array is set to -1. If the column is modified,
84025 ** the value is 0 or greater. Parameter chngRowid is set to true if the
84026 ** UPDATE statement modifies the rowid fields of the table.
84027 **
84028 ** If any foreign key processing will be required, this function returns
84029 ** true. If there is no foreign key related processing, this function 
84030 ** returns false.
84031 */
84032 SQLITE_PRIVATE int sqlite3FkRequired(
84033   Parse *pParse,                  /* Parse context */
84034   Table *pTab,                    /* Table being modified */
84035   int *aChange,                   /* Non-NULL for UPDATE operations */
84036   int chngRowid                   /* True for UPDATE that affects rowid */
84037 ){
84038   if( pParse->db->flags&SQLITE_ForeignKeys ){
84039     if( !aChange ){
84040       /* A DELETE operation. Foreign key processing is required if the 
84041       ** table in question is either the child or parent table for any 
84042       ** foreign key constraint.  */
84043       return (sqlite3FkReferences(pTab) || pTab->pFKey);
84044     }else{
84045       /* This is an UPDATE. Foreign key processing is only required if the
84046       ** operation modifies one or more child or parent key columns. */
84047       int i;
84048       FKey *p;
84049
84050       /* Check if any child key columns are being modified. */
84051       for(p=pTab->pFKey; p; p=p->pNextFrom){
84052         for(i=0; i<p->nCol; i++){
84053           int iChildKey = p->aCol[i].iFrom;
84054           if( aChange[iChildKey]>=0 ) return 1;
84055           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84056         }
84057       }
84058
84059       /* Check if any parent key columns are being modified. */
84060       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84061         for(i=0; i<p->nCol; i++){
84062           char *zKey = p->aCol[i].zCol;
84063           int iKey;
84064           for(iKey=0; iKey<pTab->nCol; iKey++){
84065             Column *pCol = &pTab->aCol[iKey];
84066             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84067               if( aChange[iKey]>=0 ) return 1;
84068               if( iKey==pTab->iPKey && chngRowid ) return 1;
84069             }
84070           }
84071         }
84072       }
84073     }
84074   }
84075   return 0;
84076 }
84077
84078 /*
84079 ** This function is called when an UPDATE or DELETE operation is being 
84080 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
84081 ** If the current operation is an UPDATE, then the pChanges parameter is
84082 ** passed a pointer to the list of columns being modified. If it is a
84083 ** DELETE, pChanges is passed a NULL pointer.
84084 **
84085 ** It returns a pointer to a Trigger structure containing a trigger
84086 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84087 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84088 ** returned (these actions require no special handling by the triggers
84089 ** sub-system, code for them is created by fkScanChildren()).
84090 **
84091 ** For example, if pFKey is the foreign key and pTab is table "p" in 
84092 ** the following schema:
84093 **
84094 **   CREATE TABLE p(pk PRIMARY KEY);
84095 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84096 **
84097 ** then the returned trigger structure is equivalent to:
84098 **
84099 **   CREATE TRIGGER ... DELETE ON p BEGIN
84100 **     DELETE FROM c WHERE ck = old.pk;
84101 **   END;
84102 **
84103 ** The returned pointer is cached as part of the foreign key object. It
84104 ** is eventually freed along with the rest of the foreign key object by 
84105 ** sqlite3FkDelete().
84106 */
84107 static Trigger *fkActionTrigger(
84108   Parse *pParse,                  /* Parse context */
84109   Table *pTab,                    /* Table being updated or deleted from */
84110   FKey *pFKey,                    /* Foreign key to get action for */
84111   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
84112 ){
84113   sqlite3 *db = pParse->db;       /* Database handle */
84114   int action;                     /* One of OE_None, OE_Cascade etc. */
84115   Trigger *pTrigger;              /* Trigger definition to return */
84116   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
84117
84118   action = pFKey->aAction[iAction];
84119   pTrigger = pFKey->apTrigger[iAction];
84120
84121   if( action!=OE_None && !pTrigger ){
84122     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
84123     char const *zFrom;            /* Name of child table */
84124     int nFrom;                    /* Length in bytes of zFrom */
84125     Index *pIdx = 0;              /* Parent key index for this FK */
84126     int *aiCol = 0;               /* child table cols -> parent key cols */
84127     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
84128     Expr *pWhere = 0;             /* WHERE clause of trigger step */
84129     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
84130     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
84131     int i;                        /* Iterator variable */
84132     Expr *pWhen = 0;              /* WHEN clause for the trigger */
84133
84134     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84135     assert( aiCol || pFKey->nCol==1 );
84136
84137     for(i=0; i<pFKey->nCol; i++){
84138       Token tOld = { "old", 3 };  /* Literal "old" token */
84139       Token tNew = { "new", 3 };  /* Literal "new" token */
84140       Token tFromCol;             /* Name of column in child table */
84141       Token tToCol;               /* Name of column in parent table */
84142       int iFromCol;               /* Idx of column in child table */
84143       Expr *pEq;                  /* tFromCol = OLD.tToCol */
84144
84145       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84146       assert( iFromCol>=0 );
84147       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84148       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84149
84150       tToCol.n = sqlite3Strlen30(tToCol.z);
84151       tFromCol.n = sqlite3Strlen30(tFromCol.z);
84152
84153       /* Create the expression "OLD.zToCol = zFromCol". It is important
84154       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84155       ** that the affinity and collation sequence associated with the
84156       ** parent table are used for the comparison. */
84157       pEq = sqlite3PExpr(pParse, TK_EQ,
84158           sqlite3PExpr(pParse, TK_DOT, 
84159             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84160             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84161           , 0),
84162           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84163       , 0);
84164       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84165
84166       /* For ON UPDATE, construct the next term of the WHEN clause.
84167       ** The final WHEN clause will be like this:
84168       **
84169       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84170       */
84171       if( pChanges ){
84172         pEq = sqlite3PExpr(pParse, TK_IS,
84173             sqlite3PExpr(pParse, TK_DOT, 
84174               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84175               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84176               0),
84177             sqlite3PExpr(pParse, TK_DOT, 
84178               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84179               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84180               0),
84181             0);
84182         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84183       }
84184   
84185       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84186         Expr *pNew;
84187         if( action==OE_Cascade ){
84188           pNew = sqlite3PExpr(pParse, TK_DOT, 
84189             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84190             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84191           , 0);
84192         }else if( action==OE_SetDflt ){
84193           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84194           if( pDflt ){
84195             pNew = sqlite3ExprDup(db, pDflt, 0);
84196           }else{
84197             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84198           }
84199         }else{
84200           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84201         }
84202         pList = sqlite3ExprListAppend(pParse, pList, pNew);
84203         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84204       }
84205     }
84206     sqlite3DbFree(db, aiCol);
84207
84208     zFrom = pFKey->pFrom->zName;
84209     nFrom = sqlite3Strlen30(zFrom);
84210
84211     if( action==OE_Restrict ){
84212       Token tFrom;
84213       Expr *pRaise; 
84214
84215       tFrom.z = zFrom;
84216       tFrom.n = nFrom;
84217       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84218       if( pRaise ){
84219         pRaise->affinity = OE_Abort;
84220       }
84221       pSelect = sqlite3SelectNew(pParse, 
84222           sqlite3ExprListAppend(pParse, 0, pRaise),
84223           sqlite3SrcListAppend(db, 0, &tFrom, 0),
84224           pWhere,
84225           0, 0, 0, 0, 0, 0
84226       );
84227       pWhere = 0;
84228     }
84229
84230     /* Disable lookaside memory allocation */
84231     enableLookaside = db->lookaside.bEnabled;
84232     db->lookaside.bEnabled = 0;
84233
84234     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
84235         sizeof(Trigger) +         /* struct Trigger */
84236         sizeof(TriggerStep) +     /* Single step in trigger program */
84237         nFrom + 1                 /* Space for pStep->target.z */
84238     );
84239     if( pTrigger ){
84240       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84241       pStep->target.z = (char *)&pStep[1];
84242       pStep->target.n = nFrom;
84243       memcpy((char *)pStep->target.z, zFrom, nFrom);
84244   
84245       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84246       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84247       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84248       if( pWhen ){
84249         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84250         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84251       }
84252     }
84253
84254     /* Re-enable the lookaside buffer, if it was disabled earlier. */
84255     db->lookaside.bEnabled = enableLookaside;
84256
84257     sqlite3ExprDelete(db, pWhere);
84258     sqlite3ExprDelete(db, pWhen);
84259     sqlite3ExprListDelete(db, pList);
84260     sqlite3SelectDelete(db, pSelect);
84261     if( db->mallocFailed==1 ){
84262       fkTriggerDelete(db, pTrigger);
84263       return 0;
84264     }
84265
84266     switch( action ){
84267       case OE_Restrict:
84268         pStep->op = TK_SELECT; 
84269         break;
84270       case OE_Cascade: 
84271         if( !pChanges ){ 
84272           pStep->op = TK_DELETE; 
84273           break; 
84274         }
84275       default:
84276         pStep->op = TK_UPDATE;
84277     }
84278     pStep->pTrig = pTrigger;
84279     pTrigger->pSchema = pTab->pSchema;
84280     pTrigger->pTabSchema = pTab->pSchema;
84281     pFKey->apTrigger[iAction] = pTrigger;
84282     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84283   }
84284
84285   return pTrigger;
84286 }
84287
84288 /*
84289 ** This function is called when deleting or updating a row to implement
84290 ** any required CASCADE, SET NULL or SET DEFAULT actions.
84291 */
84292 SQLITE_PRIVATE void sqlite3FkActions(
84293   Parse *pParse,                  /* Parse context */
84294   Table *pTab,                    /* Table being updated or deleted from */
84295   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
84296   int regOld                      /* Address of array containing old row */
84297 ){
84298   /* If foreign-key support is enabled, iterate through all FKs that 
84299   ** refer to table pTab. If there is an action associated with the FK 
84300   ** for this operation (either update or delete), invoke the associated 
84301   ** trigger sub-program.  */
84302   if( pParse->db->flags&SQLITE_ForeignKeys ){
84303     FKey *pFKey;                  /* Iterator variable */
84304     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84305       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84306       if( pAction ){
84307         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84308       }
84309     }
84310   }
84311 }
84312
84313 #endif /* ifndef SQLITE_OMIT_TRIGGER */
84314
84315 /*
84316 ** Free all memory associated with foreign key definitions attached to
84317 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84318 ** hash table.
84319 */
84320 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84321   FKey *pFKey;                    /* Iterator variable */
84322   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
84323
84324   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84325   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84326
84327     /* Remove the FK from the fkeyHash hash table. */
84328     if( !db || db->pnBytesFreed==0 ){
84329       if( pFKey->pPrevTo ){
84330         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84331       }else{
84332         void *p = (void *)pFKey->pNextTo;
84333         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84334         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84335       }
84336       if( pFKey->pNextTo ){
84337         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84338       }
84339     }
84340
84341     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84342     ** classified as either immediate or deferred.
84343     */
84344     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84345
84346     /* Delete any triggers created to implement actions for this FK. */
84347 #ifndef SQLITE_OMIT_TRIGGER
84348     fkTriggerDelete(db, pFKey->apTrigger[0]);
84349     fkTriggerDelete(db, pFKey->apTrigger[1]);
84350 #endif
84351
84352     pNext = pFKey->pNextFrom;
84353     sqlite3DbFree(db, pFKey);
84354   }
84355 }
84356 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
84357
84358 /************** End of fkey.c ************************************************/
84359 /************** Begin file insert.c ******************************************/
84360 /*
84361 ** 2001 September 15
84362 **
84363 ** The author disclaims copyright to this source code.  In place of
84364 ** a legal notice, here is a blessing:
84365 **
84366 **    May you do good and not evil.
84367 **    May you find forgiveness for yourself and forgive others.
84368 **    May you share freely, never taking more than you give.
84369 **
84370 *************************************************************************
84371 ** This file contains C code routines that are called by the parser
84372 ** to handle INSERT statements in SQLite.
84373 */
84374
84375 /*
84376 ** Generate code that will open a table for reading.
84377 */
84378 SQLITE_PRIVATE void sqlite3OpenTable(
84379   Parse *p,       /* Generate code into this VDBE */
84380   int iCur,       /* The cursor number of the table */
84381   int iDb,        /* The database index in sqlite3.aDb[] */
84382   Table *pTab,    /* The table to be opened */
84383   int opcode      /* OP_OpenRead or OP_OpenWrite */
84384 ){
84385   Vdbe *v;
84386   if( IsVirtual(pTab) ) return;
84387   v = sqlite3GetVdbe(p);
84388   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
84389   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
84390   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
84391   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
84392   VdbeComment((v, "%s", pTab->zName));
84393 }
84394
84395 /*
84396 ** Return a pointer to the column affinity string associated with index
84397 ** pIdx. A column affinity string has one character for each column in 
84398 ** the table, according to the affinity of the column:
84399 **
84400 **  Character      Column affinity
84401 **  ------------------------------
84402 **  'a'            TEXT
84403 **  'b'            NONE
84404 **  'c'            NUMERIC
84405 **  'd'            INTEGER
84406 **  'e'            REAL
84407 **
84408 ** An extra 'b' is appended to the end of the string to cover the
84409 ** rowid that appears as the last column in every index.
84410 **
84411 ** Memory for the buffer containing the column index affinity string
84412 ** is managed along with the rest of the Index structure. It will be
84413 ** released when sqlite3DeleteIndex() is called.
84414 */
84415 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
84416   if( !pIdx->zColAff ){
84417     /* The first time a column affinity string for a particular index is
84418     ** required, it is allocated and populated here. It is then stored as
84419     ** a member of the Index structure for subsequent use.
84420     **
84421     ** The column affinity string will eventually be deleted by
84422     ** sqliteDeleteIndex() when the Index structure itself is cleaned
84423     ** up.
84424     */
84425     int n;
84426     Table *pTab = pIdx->pTable;
84427     sqlite3 *db = sqlite3VdbeDb(v);
84428     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
84429     if( !pIdx->zColAff ){
84430       db->mallocFailed = 1;
84431       return 0;
84432     }
84433     for(n=0; n<pIdx->nColumn; n++){
84434       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
84435     }
84436     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
84437     pIdx->zColAff[n] = 0;
84438   }
84439  
84440   return pIdx->zColAff;
84441 }
84442
84443 /*
84444 ** Set P4 of the most recently inserted opcode to a column affinity
84445 ** string for table pTab. A column affinity string has one character
84446 ** for each column indexed by the index, according to the affinity of the
84447 ** column:
84448 **
84449 **  Character      Column affinity
84450 **  ------------------------------
84451 **  'a'            TEXT
84452 **  'b'            NONE
84453 **  'c'            NUMERIC
84454 **  'd'            INTEGER
84455 **  'e'            REAL
84456 */
84457 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
84458   /* The first time a column affinity string for a particular table
84459   ** is required, it is allocated and populated here. It is then 
84460   ** stored as a member of the Table structure for subsequent use.
84461   **
84462   ** The column affinity string will eventually be deleted by
84463   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84464   */
84465   if( !pTab->zColAff ){
84466     char *zColAff;
84467     int i;
84468     sqlite3 *db = sqlite3VdbeDb(v);
84469
84470     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
84471     if( !zColAff ){
84472       db->mallocFailed = 1;
84473       return;
84474     }
84475
84476     for(i=0; i<pTab->nCol; i++){
84477       zColAff[i] = pTab->aCol[i].affinity;
84478     }
84479     zColAff[pTab->nCol] = '\0';
84480
84481     pTab->zColAff = zColAff;
84482   }
84483
84484   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
84485 }
84486
84487 /*
84488 ** Return non-zero if the table pTab in database iDb or any of its indices
84489 ** have been opened at any point in the VDBE program beginning at location
84490 ** iStartAddr throught the end of the program.  This is used to see if 
84491 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
84492 ** run without using temporary table for the results of the SELECT. 
84493 */
84494 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
84495   Vdbe *v = sqlite3GetVdbe(p);
84496   int i;
84497   int iEnd = sqlite3VdbeCurrentAddr(v);
84498 #ifndef SQLITE_OMIT_VIRTUALTABLE
84499   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
84500 #endif
84501
84502   for(i=iStartAddr; i<iEnd; i++){
84503     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
84504     assert( pOp!=0 );
84505     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
84506       Index *pIndex;
84507       int tnum = pOp->p2;
84508       if( tnum==pTab->tnum ){
84509         return 1;
84510       }
84511       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84512         if( tnum==pIndex->tnum ){
84513           return 1;
84514         }
84515       }
84516     }
84517 #ifndef SQLITE_OMIT_VIRTUALTABLE
84518     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
84519       assert( pOp->p4.pVtab!=0 );
84520       assert( pOp->p4type==P4_VTAB );
84521       return 1;
84522     }
84523 #endif
84524   }
84525   return 0;
84526 }
84527
84528 #ifndef SQLITE_OMIT_AUTOINCREMENT
84529 /*
84530 ** Locate or create an AutoincInfo structure associated with table pTab
84531 ** which is in database iDb.  Return the register number for the register
84532 ** that holds the maximum rowid.
84533 **
84534 ** There is at most one AutoincInfo structure per table even if the
84535 ** same table is autoincremented multiple times due to inserts within
84536 ** triggers.  A new AutoincInfo structure is created if this is the
84537 ** first use of table pTab.  On 2nd and subsequent uses, the original
84538 ** AutoincInfo structure is used.
84539 **
84540 ** Three memory locations are allocated:
84541 **
84542 **   (1)  Register to hold the name of the pTab table.
84543 **   (2)  Register to hold the maximum ROWID of pTab.
84544 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
84545 **
84546 ** The 2nd register is the one that is returned.  That is all the
84547 ** insert routine needs to know about.
84548 */
84549 static int autoIncBegin(
84550   Parse *pParse,      /* Parsing context */
84551   int iDb,            /* Index of the database holding pTab */
84552   Table *pTab         /* The table we are writing to */
84553 ){
84554   int memId = 0;      /* Register holding maximum rowid */
84555   if( pTab->tabFlags & TF_Autoincrement ){
84556     Parse *pToplevel = sqlite3ParseToplevel(pParse);
84557     AutoincInfo *pInfo;
84558
84559     pInfo = pToplevel->pAinc;
84560     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
84561     if( pInfo==0 ){
84562       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
84563       if( pInfo==0 ) return 0;
84564       pInfo->pNext = pToplevel->pAinc;
84565       pToplevel->pAinc = pInfo;
84566       pInfo->pTab = pTab;
84567       pInfo->iDb = iDb;
84568       pToplevel->nMem++;                  /* Register to hold name of table */
84569       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
84570       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
84571     }
84572     memId = pInfo->regCtr;
84573   }
84574   return memId;
84575 }
84576
84577 /*
84578 ** This routine generates code that will initialize all of the
84579 ** register used by the autoincrement tracker.  
84580 */
84581 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
84582   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
84583   sqlite3 *db = pParse->db;  /* The database connection */
84584   Db *pDb;                   /* Database only autoinc table */
84585   int memId;                 /* Register holding max rowid */
84586   int addr;                  /* A VDBE address */
84587   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
84588
84589   /* This routine is never called during trigger-generation.  It is
84590   ** only called from the top-level */
84591   assert( pParse->pTriggerTab==0 );
84592   assert( pParse==sqlite3ParseToplevel(pParse) );
84593
84594   assert( v );   /* We failed long ago if this is not so */
84595   for(p = pParse->pAinc; p; p = p->pNext){
84596     pDb = &db->aDb[p->iDb];
84597     memId = p->regCtr;
84598     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84599     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
84600     addr = sqlite3VdbeCurrentAddr(v);
84601     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
84602     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
84603     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
84604     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
84605     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84606     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84607     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
84608     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
84609     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
84610     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
84611     sqlite3VdbeAddOp0(v, OP_Close);
84612   }
84613 }
84614
84615 /*
84616 ** Update the maximum rowid for an autoincrement calculation.
84617 **
84618 ** This routine should be called when the top of the stack holds a
84619 ** new rowid that is about to be inserted.  If that new rowid is
84620 ** larger than the maximum rowid in the memId memory cell, then the
84621 ** memory cell is updated.  The stack is unchanged.
84622 */
84623 static void autoIncStep(Parse *pParse, int memId, int regRowid){
84624   if( memId>0 ){
84625     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
84626   }
84627 }
84628
84629 /*
84630 ** This routine generates the code needed to write autoincrement
84631 ** maximum rowid values back into the sqlite_sequence register.
84632 ** Every statement that might do an INSERT into an autoincrement
84633 ** table (either directly or through triggers) needs to call this
84634 ** routine just before the "exit" code.
84635 */
84636 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
84637   AutoincInfo *p;
84638   Vdbe *v = pParse->pVdbe;
84639   sqlite3 *db = pParse->db;
84640
84641   assert( v );
84642   for(p = pParse->pAinc; p; p = p->pNext){
84643     Db *pDb = &db->aDb[p->iDb];
84644     int j1, j2, j3, j4, j5;
84645     int iRec;
84646     int memId = p->regCtr;
84647
84648     iRec = sqlite3GetTempReg(pParse);
84649     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84650     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
84651     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
84652     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
84653     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
84654     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
84655     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
84656     sqlite3VdbeJumpHere(v, j2);
84657     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
84658     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
84659     sqlite3VdbeJumpHere(v, j4);
84660     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84661     sqlite3VdbeJumpHere(v, j1);
84662     sqlite3VdbeJumpHere(v, j5);
84663     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
84664     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
84665     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
84666     sqlite3VdbeAddOp0(v, OP_Close);
84667     sqlite3ReleaseTempReg(pParse, iRec);
84668   }
84669 }
84670 #else
84671 /*
84672 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
84673 ** above are all no-ops
84674 */
84675 # define autoIncBegin(A,B,C) (0)
84676 # define autoIncStep(A,B,C)
84677 #endif /* SQLITE_OMIT_AUTOINCREMENT */
84678
84679
84680 /* Forward declaration */
84681 static int xferOptimization(
84682   Parse *pParse,        /* Parser context */
84683   Table *pDest,         /* The table we are inserting into */
84684   Select *pSelect,      /* A SELECT statement to use as the data source */
84685   int onError,          /* How to handle constraint errors */
84686   int iDbDest           /* The database of pDest */
84687 );
84688
84689 /*
84690 ** This routine is call to handle SQL of the following forms:
84691 **
84692 **    insert into TABLE (IDLIST) values(EXPRLIST)
84693 **    insert into TABLE (IDLIST) select
84694 **
84695 ** The IDLIST following the table name is always optional.  If omitted,
84696 ** then a list of all columns for the table is substituted.  The IDLIST
84697 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
84698 **
84699 ** The pList parameter holds EXPRLIST in the first form of the INSERT
84700 ** statement above, and pSelect is NULL.  For the second form, pList is
84701 ** NULL and pSelect is a pointer to the select statement used to generate
84702 ** data for the insert.
84703 **
84704 ** The code generated follows one of four templates.  For a simple
84705 ** select with data coming from a VALUES clause, the code executes
84706 ** once straight down through.  Pseudo-code follows (we call this
84707 ** the "1st template"):
84708 **
84709 **         open write cursor to <table> and its indices
84710 **         puts VALUES clause expressions onto the stack
84711 **         write the resulting record into <table>
84712 **         cleanup
84713 **
84714 ** The three remaining templates assume the statement is of the form
84715 **
84716 **   INSERT INTO <table> SELECT ...
84717 **
84718 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
84719 ** in other words if the SELECT pulls all columns from a single table
84720 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
84721 ** if <table2> and <table1> are distinct tables but have identical
84722 ** schemas, including all the same indices, then a special optimization
84723 ** is invoked that copies raw records from <table2> over to <table1>.
84724 ** See the xferOptimization() function for the implementation of this
84725 ** template.  This is the 2nd template.
84726 **
84727 **         open a write cursor to <table>
84728 **         open read cursor on <table2>
84729 **         transfer all records in <table2> over to <table>
84730 **         close cursors
84731 **         foreach index on <table>
84732 **           open a write cursor on the <table> index
84733 **           open a read cursor on the corresponding <table2> index
84734 **           transfer all records from the read to the write cursors
84735 **           close cursors
84736 **         end foreach
84737 **
84738 ** The 3rd template is for when the second template does not apply
84739 ** and the SELECT clause does not read from <table> at any time.
84740 ** The generated code follows this template:
84741 **
84742 **         EOF <- 0
84743 **         X <- A
84744 **         goto B
84745 **      A: setup for the SELECT
84746 **         loop over the rows in the SELECT
84747 **           load values into registers R..R+n
84748 **           yield X
84749 **         end loop
84750 **         cleanup after the SELECT
84751 **         EOF <- 1
84752 **         yield X
84753 **         goto A
84754 **      B: open write cursor to <table> and its indices
84755 **      C: yield X
84756 **         if EOF goto D
84757 **         insert the select result into <table> from R..R+n
84758 **         goto C
84759 **      D: cleanup
84760 **
84761 ** The 4th template is used if the insert statement takes its
84762 ** values from a SELECT but the data is being inserted into a table
84763 ** that is also read as part of the SELECT.  In the third form,
84764 ** we have to use a intermediate table to store the results of
84765 ** the select.  The template is like this:
84766 **
84767 **         EOF <- 0
84768 **         X <- A
84769 **         goto B
84770 **      A: setup for the SELECT
84771 **         loop over the tables in the SELECT
84772 **           load value into register R..R+n
84773 **           yield X
84774 **         end loop
84775 **         cleanup after the SELECT
84776 **         EOF <- 1
84777 **         yield X
84778 **         halt-error
84779 **      B: open temp table
84780 **      L: yield X
84781 **         if EOF goto M
84782 **         insert row from R..R+n into temp table
84783 **         goto L
84784 **      M: open write cursor to <table> and its indices
84785 **         rewind temp table
84786 **      C: loop over rows of intermediate table
84787 **           transfer values form intermediate table into <table>
84788 **         end loop
84789 **      D: cleanup
84790 */
84791 SQLITE_PRIVATE void sqlite3Insert(
84792   Parse *pParse,        /* Parser context */
84793   SrcList *pTabList,    /* Name of table into which we are inserting */
84794   ExprList *pList,      /* List of values to be inserted */
84795   Select *pSelect,      /* A SELECT statement to use as the data source */
84796   IdList *pColumn,      /* Column names corresponding to IDLIST. */
84797   int onError           /* How to handle constraint errors */
84798 ){
84799   sqlite3 *db;          /* The main database structure */
84800   Table *pTab;          /* The table to insert into.  aka TABLE */
84801   char *zTab;           /* Name of the table into which we are inserting */
84802   const char *zDb;      /* Name of the database holding this table */
84803   int i, j, idx;        /* Loop counters */
84804   Vdbe *v;              /* Generate code into this virtual machine */
84805   Index *pIdx;          /* For looping over indices of the table */
84806   int nColumn;          /* Number of columns in the data */
84807   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
84808   int baseCur = 0;      /* VDBE Cursor number for pTab */
84809   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
84810   int endOfLoop;        /* Label for the end of the insertion loop */
84811   int useTempTable = 0; /* Store SELECT results in intermediate table */
84812   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
84813   int addrInsTop = 0;   /* Jump to label "D" */
84814   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
84815   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
84816   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
84817   int iDb;              /* Index of database holding TABLE */
84818   Db *pDb;              /* The database containing table being inserted into */
84819   int appendFlag = 0;   /* True if the insert is likely to be an append */
84820
84821   /* Register allocations */
84822   int regFromSelect = 0;/* Base register for data coming from SELECT */
84823   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
84824   int regRowCount = 0;  /* Memory cell used for the row counter */
84825   int regIns;           /* Block of regs holding rowid+data being inserted */
84826   int regRowid;         /* registers holding insert rowid */
84827   int regData;          /* register holding first column to insert */
84828   int regEof = 0;       /* Register recording end of SELECT data */
84829   int *aRegIdx = 0;     /* One register allocated to each index */
84830
84831 #ifndef SQLITE_OMIT_TRIGGER
84832   int isView;                 /* True if attempting to insert into a view */
84833   Trigger *pTrigger;          /* List of triggers on pTab, if required */
84834   int tmask;                  /* Mask of trigger times */
84835 #endif
84836
84837   db = pParse->db;
84838   memset(&dest, 0, sizeof(dest));
84839   if( pParse->nErr || db->mallocFailed ){
84840     goto insert_cleanup;
84841   }
84842
84843   /* Locate the table into which we will be inserting new information.
84844   */
84845   assert( pTabList->nSrc==1 );
84846   zTab = pTabList->a[0].zName;
84847   if( NEVER(zTab==0) ) goto insert_cleanup;
84848   pTab = sqlite3SrcListLookup(pParse, pTabList);
84849   if( pTab==0 ){
84850     goto insert_cleanup;
84851   }
84852   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84853   assert( iDb<db->nDb );
84854   pDb = &db->aDb[iDb];
84855   zDb = pDb->zName;
84856   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
84857     goto insert_cleanup;
84858   }
84859
84860   /* Figure out if we have any triggers and if the table being
84861   ** inserted into is a view
84862   */
84863 #ifndef SQLITE_OMIT_TRIGGER
84864   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
84865   isView = pTab->pSelect!=0;
84866 #else
84867 # define pTrigger 0
84868 # define tmask 0
84869 # define isView 0
84870 #endif
84871 #ifdef SQLITE_OMIT_VIEW
84872 # undef isView
84873 # define isView 0
84874 #endif
84875   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
84876
84877   /* If pTab is really a view, make sure it has been initialized.
84878   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
84879   ** module table).
84880   */
84881   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84882     goto insert_cleanup;
84883   }
84884
84885   /* Ensure that:
84886   *  (a) the table is not read-only, 
84887   *  (b) that if it is a view then ON INSERT triggers exist
84888   */
84889   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84890     goto insert_cleanup;
84891   }
84892
84893   /* Allocate a VDBE
84894   */
84895   v = sqlite3GetVdbe(pParse);
84896   if( v==0 ) goto insert_cleanup;
84897   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84898   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
84899
84900 #ifndef SQLITE_OMIT_XFER_OPT
84901   /* If the statement is of the form
84902   **
84903   **       INSERT INTO <table1> SELECT * FROM <table2>;
84904   **
84905   ** Then special optimizations can be applied that make the transfer
84906   ** very fast and which reduce fragmentation of indices.
84907   **
84908   ** This is the 2nd template.
84909   */
84910   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
84911     assert( !pTrigger );
84912     assert( pList==0 );
84913     goto insert_end;
84914   }
84915 #endif /* SQLITE_OMIT_XFER_OPT */
84916
84917   /* If this is an AUTOINCREMENT table, look up the sequence number in the
84918   ** sqlite_sequence table and store it in memory cell regAutoinc.
84919   */
84920   regAutoinc = autoIncBegin(pParse, iDb, pTab);
84921
84922   /* Figure out how many columns of data are supplied.  If the data
84923   ** is coming from a SELECT statement, then generate a co-routine that
84924   ** produces a single row of the SELECT on each invocation.  The
84925   ** co-routine is the common header to the 3rd and 4th templates.
84926   */
84927   if( pSelect ){
84928     /* Data is coming from a SELECT.  Generate code to implement that SELECT
84929     ** as a co-routine.  The code is common to both the 3rd and 4th
84930     ** templates:
84931     **
84932     **         EOF <- 0
84933     **         X <- A
84934     **         goto B
84935     **      A: setup for the SELECT
84936     **         loop over the tables in the SELECT
84937     **           load value into register R..R+n
84938     **           yield X
84939     **         end loop
84940     **         cleanup after the SELECT
84941     **         EOF <- 1
84942     **         yield X
84943     **         halt-error
84944     **
84945     ** On each invocation of the co-routine, it puts a single row of the
84946     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
84947     ** (These output registers are allocated by sqlite3Select().)  When
84948     ** the SELECT completes, it sets the EOF flag stored in regEof.
84949     */
84950     int rc, j1;
84951
84952     regEof = ++pParse->nMem;
84953     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
84954     VdbeComment((v, "SELECT eof flag"));
84955     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
84956     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
84957     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
84958     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
84959     VdbeComment((v, "Jump over SELECT coroutine"));
84960
84961     /* Resolve the expressions in the SELECT statement and execute it. */
84962     rc = sqlite3Select(pParse, pSelect, &dest);
84963     assert( pParse->nErr==0 || rc );
84964     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
84965       goto insert_cleanup;
84966     }
84967     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
84968     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
84969     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
84970     VdbeComment((v, "End of SELECT coroutine"));
84971     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
84972
84973     regFromSelect = dest.iMem;
84974     assert( pSelect->pEList );
84975     nColumn = pSelect->pEList->nExpr;
84976     assert( dest.nMem==nColumn );
84977
84978     /* Set useTempTable to TRUE if the result of the SELECT statement
84979     ** should be written into a temporary table (template 4).  Set to
84980     ** FALSE if each* row of the SELECT can be written directly into
84981     ** the destination table (template 3).
84982     **
84983     ** A temp table must be used if the table being updated is also one
84984     ** of the tables being read by the SELECT statement.  Also use a 
84985     ** temp table in the case of row triggers.
84986     */
84987     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
84988       useTempTable = 1;
84989     }
84990
84991     if( useTempTable ){
84992       /* Invoke the coroutine to extract information from the SELECT
84993       ** and add it to a transient table srcTab.  The code generated
84994       ** here is from the 4th template:
84995       **
84996       **      B: open temp table
84997       **      L: yield X
84998       **         if EOF goto M
84999       **         insert row from R..R+n into temp table
85000       **         goto L
85001       **      M: ...
85002       */
85003       int regRec;          /* Register to hold packed record */
85004       int regTempRowid;    /* Register to hold temp table ROWID */
85005       int addrTop;         /* Label "L" */
85006       int addrIf;          /* Address of jump to M */
85007
85008       srcTab = pParse->nTab++;
85009       regRec = sqlite3GetTempReg(pParse);
85010       regTempRowid = sqlite3GetTempReg(pParse);
85011       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85012       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85013       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85014       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85015       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85016       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85017       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85018       sqlite3VdbeJumpHere(v, addrIf);
85019       sqlite3ReleaseTempReg(pParse, regRec);
85020       sqlite3ReleaseTempReg(pParse, regTempRowid);
85021     }
85022   }else{
85023     /* This is the case if the data for the INSERT is coming from a VALUES
85024     ** clause
85025     */
85026     NameContext sNC;
85027     memset(&sNC, 0, sizeof(sNC));
85028     sNC.pParse = pParse;
85029     srcTab = -1;
85030     assert( useTempTable==0 );
85031     nColumn = pList ? pList->nExpr : 0;
85032     for(i=0; i<nColumn; i++){
85033       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85034         goto insert_cleanup;
85035       }
85036     }
85037   }
85038
85039   /* Make sure the number of columns in the source data matches the number
85040   ** of columns to be inserted into the table.
85041   */
85042   if( IsVirtual(pTab) ){
85043     for(i=0; i<pTab->nCol; i++){
85044       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85045     }
85046   }
85047   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85048     sqlite3ErrorMsg(pParse, 
85049        "table %S has %d columns but %d values were supplied",
85050        pTabList, 0, pTab->nCol-nHidden, nColumn);
85051     goto insert_cleanup;
85052   }
85053   if( pColumn!=0 && nColumn!=pColumn->nId ){
85054     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85055     goto insert_cleanup;
85056   }
85057
85058   /* If the INSERT statement included an IDLIST term, then make sure
85059   ** all elements of the IDLIST really are columns of the table and 
85060   ** remember the column indices.
85061   **
85062   ** If the table has an INTEGER PRIMARY KEY column and that column
85063   ** is named in the IDLIST, then record in the keyColumn variable
85064   ** the index into IDLIST of the primary key column.  keyColumn is
85065   ** the index of the primary key as it appears in IDLIST, not as
85066   ** is appears in the original table.  (The index of the primary
85067   ** key in the original table is pTab->iPKey.)
85068   */
85069   if( pColumn ){
85070     for(i=0; i<pColumn->nId; i++){
85071       pColumn->a[i].idx = -1;
85072     }
85073     for(i=0; i<pColumn->nId; i++){
85074       for(j=0; j<pTab->nCol; j++){
85075         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85076           pColumn->a[i].idx = j;
85077           if( j==pTab->iPKey ){
85078             keyColumn = i;
85079           }
85080           break;
85081         }
85082       }
85083       if( j>=pTab->nCol ){
85084         if( sqlite3IsRowid(pColumn->a[i].zName) ){
85085           keyColumn = i;
85086         }else{
85087           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85088               pTabList, 0, pColumn->a[i].zName);
85089           pParse->checkSchema = 1;
85090           goto insert_cleanup;
85091         }
85092       }
85093     }
85094   }
85095
85096   /* If there is no IDLIST term but the table has an integer primary
85097   ** key, the set the keyColumn variable to the primary key column index
85098   ** in the original table definition.
85099   */
85100   if( pColumn==0 && nColumn>0 ){
85101     keyColumn = pTab->iPKey;
85102   }
85103     
85104   /* Initialize the count of rows to be inserted
85105   */
85106   if( db->flags & SQLITE_CountRows ){
85107     regRowCount = ++pParse->nMem;
85108     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85109   }
85110
85111   /* If this is not a view, open the table and and all indices */
85112   if( !isView ){
85113     int nIdx;
85114
85115     baseCur = pParse->nTab;
85116     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85117     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85118     if( aRegIdx==0 ){
85119       goto insert_cleanup;
85120     }
85121     for(i=0; i<nIdx; i++){
85122       aRegIdx[i] = ++pParse->nMem;
85123     }
85124   }
85125
85126   /* This is the top of the main insertion loop */
85127   if( useTempTable ){
85128     /* This block codes the top of loop only.  The complete loop is the
85129     ** following pseudocode (template 4):
85130     **
85131     **         rewind temp table
85132     **      C: loop over rows of intermediate table
85133     **           transfer values form intermediate table into <table>
85134     **         end loop
85135     **      D: ...
85136     */
85137     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85138     addrCont = sqlite3VdbeCurrentAddr(v);
85139   }else if( pSelect ){
85140     /* This block codes the top of loop only.  The complete loop is the
85141     ** following pseudocode (template 3):
85142     **
85143     **      C: yield X
85144     **         if EOF goto D
85145     **         insert the select result into <table> from R..R+n
85146     **         goto C
85147     **      D: ...
85148     */
85149     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85150     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85151   }
85152
85153   /* Allocate registers for holding the rowid of the new row,
85154   ** the content of the new row, and the assemblied row record.
85155   */
85156   regRowid = regIns = pParse->nMem+1;
85157   pParse->nMem += pTab->nCol + 1;
85158   if( IsVirtual(pTab) ){
85159     regRowid++;
85160     pParse->nMem++;
85161   }
85162   regData = regRowid+1;
85163
85164   /* Run the BEFORE and INSTEAD OF triggers, if there are any
85165   */
85166   endOfLoop = sqlite3VdbeMakeLabel(v);
85167   if( tmask & TRIGGER_BEFORE ){
85168     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85169
85170     /* build the NEW.* reference row.  Note that if there is an INTEGER
85171     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85172     ** translated into a unique ID for the row.  But on a BEFORE trigger,
85173     ** we do not know what the unique ID will be (because the insert has
85174     ** not happened yet) so we substitute a rowid of -1
85175     */
85176     if( keyColumn<0 ){
85177       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85178     }else{
85179       int j1;
85180       if( useTempTable ){
85181         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85182       }else{
85183         assert( pSelect==0 );  /* Otherwise useTempTable is true */
85184         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85185       }
85186       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85187       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85188       sqlite3VdbeJumpHere(v, j1);
85189       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85190     }
85191
85192     /* Cannot have triggers on a virtual table. If it were possible,
85193     ** this block would have to account for hidden column.
85194     */
85195     assert( !IsVirtual(pTab) );
85196
85197     /* Create the new column data
85198     */
85199     for(i=0; i<pTab->nCol; i++){
85200       if( pColumn==0 ){
85201         j = i;
85202       }else{
85203         for(j=0; j<pColumn->nId; j++){
85204           if( pColumn->a[j].idx==i ) break;
85205         }
85206       }
85207       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85208         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85209       }else if( useTempTable ){
85210         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
85211       }else{
85212         assert( pSelect==0 ); /* Otherwise useTempTable is true */
85213         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85214       }
85215     }
85216
85217     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85218     ** do not attempt any conversions before assembling the record.
85219     ** If this is a real table, attempt conversions as required by the
85220     ** table column affinities.
85221     */
85222     if( !isView ){
85223       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85224       sqlite3TableAffinityStr(v, pTab);
85225     }
85226
85227     /* Fire BEFORE or INSTEAD OF triggers */
85228     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
85229         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85230
85231     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85232   }
85233
85234   /* Push the record number for the new entry onto the stack.  The
85235   ** record number is a randomly generate integer created by NewRowid
85236   ** except when the table has an INTEGER PRIMARY KEY column, in which
85237   ** case the record number is the same as that column. 
85238   */
85239   if( !isView ){
85240     if( IsVirtual(pTab) ){
85241       /* The row that the VUpdate opcode will delete: none */
85242       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85243     }
85244     if( keyColumn>=0 ){
85245       if( useTempTable ){
85246         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85247       }else if( pSelect ){
85248         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85249       }else{
85250         VdbeOp *pOp;
85251         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85252         pOp = sqlite3VdbeGetOp(v, -1);
85253         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85254           appendFlag = 1;
85255           pOp->opcode = OP_NewRowid;
85256           pOp->p1 = baseCur;
85257           pOp->p2 = regRowid;
85258           pOp->p3 = regAutoinc;
85259         }
85260       }
85261       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85262       ** to generate a unique primary key value.
85263       */
85264       if( !appendFlag ){
85265         int j1;
85266         if( !IsVirtual(pTab) ){
85267           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85268           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85269           sqlite3VdbeJumpHere(v, j1);
85270         }else{
85271           j1 = sqlite3VdbeCurrentAddr(v);
85272           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85273         }
85274         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85275       }
85276     }else if( IsVirtual(pTab) ){
85277       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85278     }else{
85279       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85280       appendFlag = 1;
85281     }
85282     autoIncStep(pParse, regAutoinc, regRowid);
85283
85284     /* Push onto the stack, data for all columns of the new entry, beginning
85285     ** with the first column.
85286     */
85287     nHidden = 0;
85288     for(i=0; i<pTab->nCol; i++){
85289       int iRegStore = regRowid+1+i;
85290       if( i==pTab->iPKey ){
85291         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85292         ** Whenever this column is read, the record number will be substituted
85293         ** in its place.  So will fill this column with a NULL to avoid
85294         ** taking up data space with information that will never be used. */
85295         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85296         continue;
85297       }
85298       if( pColumn==0 ){
85299         if( IsHiddenColumn(&pTab->aCol[i]) ){
85300           assert( IsVirtual(pTab) );
85301           j = -1;
85302           nHidden++;
85303         }else{
85304           j = i - nHidden;
85305         }
85306       }else{
85307         for(j=0; j<pColumn->nId; j++){
85308           if( pColumn->a[j].idx==i ) break;
85309         }
85310       }
85311       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85312         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85313       }else if( useTempTable ){
85314         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
85315       }else if( pSelect ){
85316         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85317       }else{
85318         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85319       }
85320     }
85321
85322     /* Generate code to check constraints and generate index keys and
85323     ** do the insertion.
85324     */
85325 #ifndef SQLITE_OMIT_VIRTUALTABLE
85326     if( IsVirtual(pTab) ){
85327       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85328       sqlite3VtabMakeWritable(pParse, pTab);
85329       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85330       sqlite3MayAbort(pParse);
85331     }else
85332 #endif
85333     {
85334       int isReplace;    /* Set to true if constraints may cause a replace */
85335       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85336           keyColumn>=0, 0, onError, endOfLoop, &isReplace
85337       );
85338       sqlite3FkCheck(pParse, pTab, 0, regIns);
85339       sqlite3CompleteInsertion(
85340           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85341       );
85342     }
85343   }
85344
85345   /* Update the count of rows that are inserted
85346   */
85347   if( (db->flags & SQLITE_CountRows)!=0 ){
85348     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85349   }
85350
85351   if( pTrigger ){
85352     /* Code AFTER triggers */
85353     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
85354         pTab, regData-2-pTab->nCol, onError, endOfLoop);
85355   }
85356
85357   /* The bottom of the main insertion loop, if the data source
85358   ** is a SELECT statement.
85359   */
85360   sqlite3VdbeResolveLabel(v, endOfLoop);
85361   if( useTempTable ){
85362     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
85363     sqlite3VdbeJumpHere(v, addrInsTop);
85364     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
85365   }else if( pSelect ){
85366     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
85367     sqlite3VdbeJumpHere(v, addrInsTop);
85368   }
85369
85370   if( !IsVirtual(pTab) && !isView ){
85371     /* Close all tables opened */
85372     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
85373     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85374       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
85375     }
85376   }
85377
85378 insert_end:
85379   /* Update the sqlite_sequence table by storing the content of the
85380   ** maximum rowid counter values recorded while inserting into
85381   ** autoincrement tables.
85382   */
85383   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85384     sqlite3AutoincrementEnd(pParse);
85385   }
85386
85387   /*
85388   ** Return the number of rows inserted. If this routine is 
85389   ** generating code because of a call to sqlite3NestedParse(), do not
85390   ** invoke the callback function.
85391   */
85392   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85393     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85394     sqlite3VdbeSetNumCols(v, 1);
85395     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
85396   }
85397
85398 insert_cleanup:
85399   sqlite3SrcListDelete(db, pTabList);
85400   sqlite3ExprListDelete(db, pList);
85401   sqlite3SelectDelete(db, pSelect);
85402   sqlite3IdListDelete(db, pColumn);
85403   sqlite3DbFree(db, aRegIdx);
85404 }
85405
85406 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85407 ** thely may interfere with compilation of other functions in this file
85408 ** (or in another file, if this file becomes part of the amalgamation).  */
85409 #ifdef isView
85410  #undef isView
85411 #endif
85412 #ifdef pTrigger
85413  #undef pTrigger
85414 #endif
85415 #ifdef tmask
85416  #undef tmask
85417 #endif
85418
85419
85420 /*
85421 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
85422 **
85423 ** The input is a range of consecutive registers as follows:
85424 **
85425 **    1.  The rowid of the row after the update.
85426 **
85427 **    2.  The data in the first column of the entry after the update.
85428 **
85429 **    i.  Data from middle columns...
85430 **
85431 **    N.  The data in the last column of the entry after the update.
85432 **
85433 ** The regRowid parameter is the index of the register containing (1).
85434 **
85435 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
85436 ** the address of a register containing the rowid before the update takes
85437 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
85438 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
85439 ** indicates that the rowid was explicitly specified as part of the
85440 ** INSERT statement. If rowidChng is false, it means that  the rowid is
85441 ** computed automatically in an insert or that the rowid value is not 
85442 ** modified by an update.
85443 **
85444 ** The code generated by this routine store new index entries into
85445 ** registers identified by aRegIdx[].  No index entry is created for
85446 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
85447 ** the same as the order of indices on the linked list of indices
85448 ** attached to the table.
85449 **
85450 ** This routine also generates code to check constraints.  NOT NULL,
85451 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
85452 ** then the appropriate action is performed.  There are five possible
85453 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
85454 **
85455 **  Constraint type  Action       What Happens
85456 **  ---------------  ----------   ----------------------------------------
85457 **  any              ROLLBACK     The current transaction is rolled back and
85458 **                                sqlite3_exec() returns immediately with a
85459 **                                return code of SQLITE_CONSTRAINT.
85460 **
85461 **  any              ABORT        Back out changes from the current command
85462 **                                only (do not do a complete rollback) then
85463 **                                cause sqlite3_exec() to return immediately
85464 **                                with SQLITE_CONSTRAINT.
85465 **
85466 **  any              FAIL         Sqlite_exec() returns immediately with a
85467 **                                return code of SQLITE_CONSTRAINT.  The
85468 **                                transaction is not rolled back and any
85469 **                                prior changes are retained.
85470 **
85471 **  any              IGNORE       The record number and data is popped from
85472 **                                the stack and there is an immediate jump
85473 **                                to label ignoreDest.
85474 **
85475 **  NOT NULL         REPLACE      The NULL value is replace by the default
85476 **                                value for that column.  If the default value
85477 **                                is NULL, the action is the same as ABORT.
85478 **
85479 **  UNIQUE           REPLACE      The other row that conflicts with the row
85480 **                                being inserted is removed.
85481 **
85482 **  CHECK            REPLACE      Illegal.  The results in an exception.
85483 **
85484 ** Which action to take is determined by the overrideError parameter.
85485 ** Or if overrideError==OE_Default, then the pParse->onError parameter
85486 ** is used.  Or if pParse->onError==OE_Default then the onError value
85487 ** for the constraint is used.
85488 **
85489 ** The calling routine must open a read/write cursor for pTab with
85490 ** cursor number "baseCur".  All indices of pTab must also have open
85491 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
85492 ** Except, if there is no possibility of a REPLACE action then
85493 ** cursors do not need to be open for indices where aRegIdx[i]==0.
85494 */
85495 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
85496   Parse *pParse,      /* The parser context */
85497   Table *pTab,        /* the table into which we are inserting */
85498   int baseCur,        /* Index of a read/write cursor pointing at pTab */
85499   int regRowid,       /* Index of the range of input registers */
85500   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85501   int rowidChng,      /* True if the rowid might collide with existing entry */
85502   int isUpdate,       /* True for UPDATE, False for INSERT */
85503   int overrideError,  /* Override onError to this if not OE_Default */
85504   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
85505   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
85506 ){
85507   int i;              /* loop counter */
85508   Vdbe *v;            /* VDBE under constrution */
85509   int nCol;           /* Number of columns */
85510   int onError;        /* Conflict resolution strategy */
85511   int j1;             /* Addresss of jump instruction */
85512   int j2 = 0, j3;     /* Addresses of jump instructions */
85513   int regData;        /* Register containing first data column */
85514   int iCur;           /* Table cursor number */
85515   Index *pIdx;         /* Pointer to one of the indices */
85516   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
85517   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
85518
85519   v = sqlite3GetVdbe(pParse);
85520   assert( v!=0 );
85521   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85522   nCol = pTab->nCol;
85523   regData = regRowid + 1;
85524
85525   /* Test all NOT NULL constraints.
85526   */
85527   for(i=0; i<nCol; i++){
85528     if( i==pTab->iPKey ){
85529       continue;
85530     }
85531     onError = pTab->aCol[i].notNull;
85532     if( onError==OE_None ) continue;
85533     if( overrideError!=OE_Default ){
85534       onError = overrideError;
85535     }else if( onError==OE_Default ){
85536       onError = OE_Abort;
85537     }
85538     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
85539       onError = OE_Abort;
85540     }
85541     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85542         || onError==OE_Ignore || onError==OE_Replace );
85543     switch( onError ){
85544       case OE_Abort:
85545         sqlite3MayAbort(pParse);
85546       case OE_Rollback:
85547       case OE_Fail: {
85548         char *zMsg;
85549         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
85550                                   SQLITE_CONSTRAINT, onError, regData+i);
85551         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
85552                               pTab->zName, pTab->aCol[i].zName);
85553         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
85554         break;
85555       }
85556       case OE_Ignore: {
85557         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
85558         break;
85559       }
85560       default: {
85561         assert( onError==OE_Replace );
85562         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
85563         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
85564         sqlite3VdbeJumpHere(v, j1);
85565         break;
85566       }
85567     }
85568   }
85569
85570   /* Test all CHECK constraints
85571   */
85572 #ifndef SQLITE_OMIT_CHECK
85573   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
85574     int allOk = sqlite3VdbeMakeLabel(v);
85575     pParse->ckBase = regData;
85576     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
85577     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
85578     if( onError==OE_Ignore ){
85579       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85580     }else{
85581       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
85582       sqlite3HaltConstraint(pParse, onError, 0, 0);
85583     }
85584     sqlite3VdbeResolveLabel(v, allOk);
85585   }
85586 #endif /* !defined(SQLITE_OMIT_CHECK) */
85587
85588   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
85589   ** of the new record does not previously exist.  Except, if this
85590   ** is an UPDATE and the primary key is not changing, that is OK.
85591   */
85592   if( rowidChng ){
85593     onError = pTab->keyConf;
85594     if( overrideError!=OE_Default ){
85595       onError = overrideError;
85596     }else if( onError==OE_Default ){
85597       onError = OE_Abort;
85598     }
85599     
85600     if( isUpdate ){
85601       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
85602     }
85603     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
85604     switch( onError ){
85605       default: {
85606         onError = OE_Abort;
85607         /* Fall thru into the next case */
85608       }
85609       case OE_Rollback:
85610       case OE_Abort:
85611       case OE_Fail: {
85612         sqlite3HaltConstraint(
85613           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
85614         break;
85615       }
85616       case OE_Replace: {
85617         /* If there are DELETE triggers on this table and the
85618         ** recursive-triggers flag is set, call GenerateRowDelete() to
85619         ** remove the conflicting row from the the table. This will fire
85620         ** the triggers and remove both the table and index b-tree entries.
85621         **
85622         ** Otherwise, if there are no triggers or the recursive-triggers
85623         ** flag is not set, but the table has one or more indexes, call 
85624         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
85625         ** only. The table b-tree entry will be replaced by the new entry 
85626         ** when it is inserted.  
85627         **
85628         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
85629         ** also invoke MultiWrite() to indicate that this VDBE may require
85630         ** statement rollback (if the statement is aborted after the delete
85631         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
85632         ** but being more selective here allows statements like:
85633         **
85634         **   REPLACE INTO t(rowid) VALUES($newrowid)
85635         **
85636         ** to run without a statement journal if there are no indexes on the
85637         ** table.
85638         */
85639         Trigger *pTrigger = 0;
85640         if( pParse->db->flags&SQLITE_RecTriggers ){
85641           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85642         }
85643         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
85644           sqlite3MultiWrite(pParse);
85645           sqlite3GenerateRowDelete(
85646               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
85647           );
85648         }else if( pTab->pIndex ){
85649           sqlite3MultiWrite(pParse);
85650           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
85651         }
85652         seenReplace = 1;
85653         break;
85654       }
85655       case OE_Ignore: {
85656         assert( seenReplace==0 );
85657         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85658         break;
85659       }
85660     }
85661     sqlite3VdbeJumpHere(v, j3);
85662     if( isUpdate ){
85663       sqlite3VdbeJumpHere(v, j2);
85664     }
85665   }
85666
85667   /* Test all UNIQUE constraints by creating entries for each UNIQUE
85668   ** index and making sure that duplicate entries do not already exist.
85669   ** Add the new records to the indices as we go.
85670   */
85671   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
85672     int regIdx;
85673     int regR;
85674
85675     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
85676
85677     /* Create a key for accessing the index entry */
85678     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
85679     for(i=0; i<pIdx->nColumn; i++){
85680       int idx = pIdx->aiColumn[i];
85681       if( idx==pTab->iPKey ){
85682         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85683       }else{
85684         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
85685       }
85686     }
85687     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
85688     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
85689     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
85690     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
85691
85692     /* Find out what action to take in case there is an indexing conflict */
85693     onError = pIdx->onError;
85694     if( onError==OE_None ){ 
85695       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85696       continue;  /* pIdx is not a UNIQUE index */
85697     }
85698     if( overrideError!=OE_Default ){
85699       onError = overrideError;
85700     }else if( onError==OE_Default ){
85701       onError = OE_Abort;
85702     }
85703     if( seenReplace ){
85704       if( onError==OE_Ignore ) onError = OE_Replace;
85705       else if( onError==OE_Fail ) onError = OE_Abort;
85706     }
85707     
85708     /* Check to see if the new index entry will be unique */
85709     regR = sqlite3GetTempReg(pParse);
85710     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
85711     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
85712                            regR, SQLITE_INT_TO_PTR(regIdx),
85713                            P4_INT32);
85714     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
85715
85716     /* Generate code that executes if the new index entry is not unique */
85717     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85718         || onError==OE_Ignore || onError==OE_Replace );
85719     switch( onError ){
85720       case OE_Rollback:
85721       case OE_Abort:
85722       case OE_Fail: {
85723         int j;
85724         StrAccum errMsg;
85725         const char *zSep;
85726         char *zErr;
85727
85728         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
85729         errMsg.db = pParse->db;
85730         zSep = pIdx->nColumn>1 ? "columns " : "column ";
85731         for(j=0; j<pIdx->nColumn; j++){
85732           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
85733           sqlite3StrAccumAppend(&errMsg, zSep, -1);
85734           zSep = ", ";
85735           sqlite3StrAccumAppend(&errMsg, zCol, -1);
85736         }
85737         sqlite3StrAccumAppend(&errMsg,
85738             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
85739         zErr = sqlite3StrAccumFinish(&errMsg);
85740         sqlite3HaltConstraint(pParse, onError, zErr, 0);
85741         sqlite3DbFree(errMsg.db, zErr);
85742         break;
85743       }
85744       case OE_Ignore: {
85745         assert( seenReplace==0 );
85746         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85747         break;
85748       }
85749       default: {
85750         Trigger *pTrigger = 0;
85751         assert( onError==OE_Replace );
85752         sqlite3MultiWrite(pParse);
85753         if( pParse->db->flags&SQLITE_RecTriggers ){
85754           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85755         }
85756         sqlite3GenerateRowDelete(
85757             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
85758         );
85759         seenReplace = 1;
85760         break;
85761       }
85762     }
85763     sqlite3VdbeJumpHere(v, j3);
85764     sqlite3ReleaseTempReg(pParse, regR);
85765   }
85766   
85767   if( pbMayReplace ){
85768     *pbMayReplace = seenReplace;
85769   }
85770 }
85771
85772 /*
85773 ** This routine generates code to finish the INSERT or UPDATE operation
85774 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
85775 ** A consecutive range of registers starting at regRowid contains the
85776 ** rowid and the content to be inserted.
85777 **
85778 ** The arguments to this routine should be the same as the first six
85779 ** arguments to sqlite3GenerateConstraintChecks.
85780 */
85781 SQLITE_PRIVATE void sqlite3CompleteInsertion(
85782   Parse *pParse,      /* The parser context */
85783   Table *pTab,        /* the table into which we are inserting */
85784   int baseCur,        /* Index of a read/write cursor pointing at pTab */
85785   int regRowid,       /* Range of content */
85786   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
85787   int isUpdate,       /* True for UPDATE, False for INSERT */
85788   int appendBias,     /* True if this is likely to be an append */
85789   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
85790 ){
85791   int i;
85792   Vdbe *v;
85793   int nIdx;
85794   Index *pIdx;
85795   u8 pik_flags;
85796   int regData;
85797   int regRec;
85798
85799   v = sqlite3GetVdbe(pParse);
85800   assert( v!=0 );
85801   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
85802   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
85803   for(i=nIdx-1; i>=0; i--){
85804     if( aRegIdx[i]==0 ) continue;
85805     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
85806     if( useSeekResult ){
85807       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
85808     }
85809   }
85810   regData = regRowid + 1;
85811   regRec = sqlite3GetTempReg(pParse);
85812   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
85813   sqlite3TableAffinityStr(v, pTab);
85814   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
85815   if( pParse->nested ){
85816     pik_flags = 0;
85817   }else{
85818     pik_flags = OPFLAG_NCHANGE;
85819     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
85820   }
85821   if( appendBias ){
85822     pik_flags |= OPFLAG_APPEND;
85823   }
85824   if( useSeekResult ){
85825     pik_flags |= OPFLAG_USESEEKRESULT;
85826   }
85827   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
85828   if( !pParse->nested ){
85829     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85830   }
85831   sqlite3VdbeChangeP5(v, pik_flags);
85832 }
85833
85834 /*
85835 ** Generate code that will open cursors for a table and for all
85836 ** indices of that table.  The "baseCur" parameter is the cursor number used
85837 ** for the table.  Indices are opened on subsequent cursors.
85838 **
85839 ** Return the number of indices on the table.
85840 */
85841 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
85842   Parse *pParse,   /* Parsing context */
85843   Table *pTab,     /* Table to be opened */
85844   int baseCur,     /* Cursor number assigned to the table */
85845   int op           /* OP_OpenRead or OP_OpenWrite */
85846 ){
85847   int i;
85848   int iDb;
85849   Index *pIdx;
85850   Vdbe *v;
85851
85852   if( IsVirtual(pTab) ) return 0;
85853   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85854   v = sqlite3GetVdbe(pParse);
85855   assert( v!=0 );
85856   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
85857   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85858     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85859     assert( pIdx->pSchema==pTab->pSchema );
85860     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
85861                       (char*)pKey, P4_KEYINFO_HANDOFF);
85862     VdbeComment((v, "%s", pIdx->zName));
85863   }
85864   if( pParse->nTab<baseCur+i ){
85865     pParse->nTab = baseCur+i;
85866   }
85867   return i-1;
85868 }
85869
85870
85871 #ifdef SQLITE_TEST
85872 /*
85873 ** The following global variable is incremented whenever the
85874 ** transfer optimization is used.  This is used for testing
85875 ** purposes only - to make sure the transfer optimization really
85876 ** is happening when it is suppose to.
85877 */
85878 SQLITE_API int sqlite3_xferopt_count;
85879 #endif /* SQLITE_TEST */
85880
85881
85882 #ifndef SQLITE_OMIT_XFER_OPT
85883 /*
85884 ** Check to collation names to see if they are compatible.
85885 */
85886 static int xferCompatibleCollation(const char *z1, const char *z2){
85887   if( z1==0 ){
85888     return z2==0;
85889   }
85890   if( z2==0 ){
85891     return 0;
85892   }
85893   return sqlite3StrICmp(z1, z2)==0;
85894 }
85895
85896
85897 /*
85898 ** Check to see if index pSrc is compatible as a source of data
85899 ** for index pDest in an insert transfer optimization.  The rules
85900 ** for a compatible index:
85901 **
85902 **    *   The index is over the same set of columns
85903 **    *   The same DESC and ASC markings occurs on all columns
85904 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
85905 **    *   The same collating sequence on each column
85906 */
85907 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
85908   int i;
85909   assert( pDest && pSrc );
85910   assert( pDest->pTable!=pSrc->pTable );
85911   if( pDest->nColumn!=pSrc->nColumn ){
85912     return 0;   /* Different number of columns */
85913   }
85914   if( pDest->onError!=pSrc->onError ){
85915     return 0;   /* Different conflict resolution strategies */
85916   }
85917   for(i=0; i<pSrc->nColumn; i++){
85918     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
85919       return 0;   /* Different columns indexed */
85920     }
85921     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
85922       return 0;   /* Different sort orders */
85923     }
85924     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
85925       return 0;   /* Different collating sequences */
85926     }
85927   }
85928
85929   /* If no test above fails then the indices must be compatible */
85930   return 1;
85931 }
85932
85933 /*
85934 ** Attempt the transfer optimization on INSERTs of the form
85935 **
85936 **     INSERT INTO tab1 SELECT * FROM tab2;
85937 **
85938 ** This optimization is only attempted if
85939 **
85940 **    (1)  tab1 and tab2 have identical schemas including all the
85941 **         same indices and constraints
85942 **
85943 **    (2)  tab1 and tab2 are different tables
85944 **
85945 **    (3)  There must be no triggers on tab1
85946 **
85947 **    (4)  The result set of the SELECT statement is "*"
85948 **
85949 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
85950 **         or LIMIT clause.
85951 **
85952 **    (6)  The SELECT statement is a simple (not a compound) select that
85953 **         contains only tab2 in its FROM clause
85954 **
85955 ** This method for implementing the INSERT transfers raw records from
85956 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
85957 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
85958 ** the resulting tab1 has much less fragmentation.
85959 **
85960 ** This routine returns TRUE if the optimization is attempted.  If any
85961 ** of the conditions above fail so that the optimization should not
85962 ** be attempted, then this routine returns FALSE.
85963 */
85964 static int xferOptimization(
85965   Parse *pParse,        /* Parser context */
85966   Table *pDest,         /* The table we are inserting into */
85967   Select *pSelect,      /* A SELECT statement to use as the data source */
85968   int onError,          /* How to handle constraint errors */
85969   int iDbDest           /* The database of pDest */
85970 ){
85971   ExprList *pEList;                /* The result set of the SELECT */
85972   Table *pSrc;                     /* The table in the FROM clause of SELECT */
85973   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
85974   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
85975   int i;                           /* Loop counter */
85976   int iDbSrc;                      /* The database of pSrc */
85977   int iSrc, iDest;                 /* Cursors from source and destination */
85978   int addr1, addr2;                /* Loop addresses */
85979   int emptyDestTest;               /* Address of test for empty pDest */
85980   int emptySrcTest;                /* Address of test for empty pSrc */
85981   Vdbe *v;                         /* The VDBE we are building */
85982   KeyInfo *pKey;                   /* Key information for an index */
85983   int regAutoinc;                  /* Memory register used by AUTOINC */
85984   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
85985   int regData, regRowid;           /* Registers holding data and rowid */
85986
85987   if( pSelect==0 ){
85988     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
85989   }
85990   if( sqlite3TriggerList(pParse, pDest) ){
85991     return 0;   /* tab1 must not have triggers */
85992   }
85993 #ifndef SQLITE_OMIT_VIRTUALTABLE
85994   if( pDest->tabFlags & TF_Virtual ){
85995     return 0;   /* tab1 must not be a virtual table */
85996   }
85997 #endif
85998   if( onError==OE_Default ){
85999     onError = OE_Abort;
86000   }
86001   if( onError!=OE_Abort && onError!=OE_Rollback ){
86002     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
86003   }
86004   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
86005   if( pSelect->pSrc->nSrc!=1 ){
86006     return 0;   /* FROM clause must have exactly one term */
86007   }
86008   if( pSelect->pSrc->a[0].pSelect ){
86009     return 0;   /* FROM clause cannot contain a subquery */
86010   }
86011   if( pSelect->pWhere ){
86012     return 0;   /* SELECT may not have a WHERE clause */
86013   }
86014   if( pSelect->pOrderBy ){
86015     return 0;   /* SELECT may not have an ORDER BY clause */
86016   }
86017   /* Do not need to test for a HAVING clause.  If HAVING is present but
86018   ** there is no ORDER BY, we will get an error. */
86019   if( pSelect->pGroupBy ){
86020     return 0;   /* SELECT may not have a GROUP BY clause */
86021   }
86022   if( pSelect->pLimit ){
86023     return 0;   /* SELECT may not have a LIMIT clause */
86024   }
86025   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
86026   if( pSelect->pPrior ){
86027     return 0;   /* SELECT may not be a compound query */
86028   }
86029   if( pSelect->selFlags & SF_Distinct ){
86030     return 0;   /* SELECT may not be DISTINCT */
86031   }
86032   pEList = pSelect->pEList;
86033   assert( pEList!=0 );
86034   if( pEList->nExpr!=1 ){
86035     return 0;   /* The result set must have exactly one column */
86036   }
86037   assert( pEList->a[0].pExpr );
86038   if( pEList->a[0].pExpr->op!=TK_ALL ){
86039     return 0;   /* The result set must be the special operator "*" */
86040   }
86041
86042   /* At this point we have established that the statement is of the
86043   ** correct syntactic form to participate in this optimization.  Now
86044   ** we have to check the semantics.
86045   */
86046   pItem = pSelect->pSrc->a;
86047   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86048   if( pSrc==0 ){
86049     return 0;   /* FROM clause does not contain a real table */
86050   }
86051   if( pSrc==pDest ){
86052     return 0;   /* tab1 and tab2 may not be the same table */
86053   }
86054 #ifndef SQLITE_OMIT_VIRTUALTABLE
86055   if( pSrc->tabFlags & TF_Virtual ){
86056     return 0;   /* tab2 must not be a virtual table */
86057   }
86058 #endif
86059   if( pSrc->pSelect ){
86060     return 0;   /* tab2 may not be a view */
86061   }
86062   if( pDest->nCol!=pSrc->nCol ){
86063     return 0;   /* Number of columns must be the same in tab1 and tab2 */
86064   }
86065   if( pDest->iPKey!=pSrc->iPKey ){
86066     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
86067   }
86068   for(i=0; i<pDest->nCol; i++){
86069     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86070       return 0;    /* Affinity must be the same on all columns */
86071     }
86072     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86073       return 0;    /* Collating sequence must be the same on all columns */
86074     }
86075     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86076       return 0;    /* tab2 must be NOT NULL if tab1 is */
86077     }
86078   }
86079   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86080     if( pDestIdx->onError!=OE_None ){
86081       destHasUniqueIdx = 1;
86082     }
86083     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86084       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86085     }
86086     if( pSrcIdx==0 ){
86087       return 0;    /* pDestIdx has no corresponding index in pSrc */
86088     }
86089   }
86090 #ifndef SQLITE_OMIT_CHECK
86091   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86092     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
86093   }
86094 #endif
86095
86096   /* If we get this far, it means either:
86097   **
86098   **    *   We can always do the transfer if the table contains an
86099   **        an integer primary key
86100   **
86101   **    *   We can conditionally do the transfer if the destination
86102   **        table is empty.
86103   */
86104 #ifdef SQLITE_TEST
86105   sqlite3_xferopt_count++;
86106 #endif
86107   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86108   v = sqlite3GetVdbe(pParse);
86109   sqlite3CodeVerifySchema(pParse, iDbSrc);
86110   iSrc = pParse->nTab++;
86111   iDest = pParse->nTab++;
86112   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86113   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86114   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86115     /* If tables do not have an INTEGER PRIMARY KEY and there
86116     ** are indices to be copied and the destination is not empty,
86117     ** we have to disallow the transfer optimization because the
86118     ** the rowids might change which will mess up indexing.
86119     **
86120     ** Or if the destination has a UNIQUE index and is not empty,
86121     ** we also disallow the transfer optimization because we cannot
86122     ** insure that all entries in the union of DEST and SRC will be
86123     ** unique.
86124     */
86125     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86126     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86127     sqlite3VdbeJumpHere(v, addr1);
86128   }else{
86129     emptyDestTest = 0;
86130   }
86131   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86132   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86133   regData = sqlite3GetTempReg(pParse);
86134   regRowid = sqlite3GetTempReg(pParse);
86135   if( pDest->iPKey>=0 ){
86136     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86137     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86138     sqlite3HaltConstraint(
86139         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86140     sqlite3VdbeJumpHere(v, addr2);
86141     autoIncStep(pParse, regAutoinc, regRowid);
86142   }else if( pDest->pIndex==0 ){
86143     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86144   }else{
86145     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86146     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86147   }
86148   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86149   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86150   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86151   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86152   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86153   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86154     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86155       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86156     }
86157     assert( pSrcIdx );
86158     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86159     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86160     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86161     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86162                       (char*)pKey, P4_KEYINFO_HANDOFF);
86163     VdbeComment((v, "%s", pSrcIdx->zName));
86164     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86165     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86166                       (char*)pKey, P4_KEYINFO_HANDOFF);
86167     VdbeComment((v, "%s", pDestIdx->zName));
86168     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86169     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86170     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86171     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86172     sqlite3VdbeJumpHere(v, addr1);
86173   }
86174   sqlite3VdbeJumpHere(v, emptySrcTest);
86175   sqlite3ReleaseTempReg(pParse, regRowid);
86176   sqlite3ReleaseTempReg(pParse, regData);
86177   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86178   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86179   if( emptyDestTest ){
86180     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86181     sqlite3VdbeJumpHere(v, emptyDestTest);
86182     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86183     return 0;
86184   }else{
86185     return 1;
86186   }
86187 }
86188 #endif /* SQLITE_OMIT_XFER_OPT */
86189
86190 /************** End of insert.c **********************************************/
86191 /************** Begin file legacy.c ******************************************/
86192 /*
86193 ** 2001 September 15
86194 **
86195 ** The author disclaims copyright to this source code.  In place of
86196 ** a legal notice, here is a blessing:
86197 **
86198 **    May you do good and not evil.
86199 **    May you find forgiveness for yourself and forgive others.
86200 **    May you share freely, never taking more than you give.
86201 **
86202 *************************************************************************
86203 ** Main file for the SQLite library.  The routines in this file
86204 ** implement the programmer interface to the library.  Routines in
86205 ** other files are for internal use by SQLite and should not be
86206 ** accessed by users of the library.
86207 */
86208
86209
86210 /*
86211 ** Execute SQL code.  Return one of the SQLITE_ success/failure
86212 ** codes.  Also write an error message into memory obtained from
86213 ** malloc() and make *pzErrMsg point to that message.
86214 **
86215 ** If the SQL is a query, then for each row in the query result
86216 ** the xCallback() function is called.  pArg becomes the first
86217 ** argument to xCallback().  If xCallback=NULL then no callback
86218 ** is invoked, even for queries.
86219 */
86220 SQLITE_API int sqlite3_exec(
86221   sqlite3 *db,                /* The database on which the SQL executes */
86222   const char *zSql,           /* The SQL to be executed */
86223   sqlite3_callback xCallback, /* Invoke this callback routine */
86224   void *pArg,                 /* First argument to xCallback() */
86225   char **pzErrMsg             /* Write error messages here */
86226 ){
86227   int rc = SQLITE_OK;         /* Return code */
86228   const char *zLeftover;      /* Tail of unprocessed SQL */
86229   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
86230   char **azCols = 0;          /* Names of result columns */
86231   int nRetry = 0;             /* Number of retry attempts */
86232   int callbackIsInit;         /* True if callback data is initialized */
86233
86234   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86235   if( zSql==0 ) zSql = "";
86236
86237   sqlite3_mutex_enter(db->mutex);
86238   sqlite3Error(db, SQLITE_OK, 0);
86239   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86240     int nCol;
86241     char **azVals = 0;
86242
86243     pStmt = 0;
86244     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86245     assert( rc==SQLITE_OK || pStmt==0 );
86246     if( rc!=SQLITE_OK ){
86247       continue;
86248     }
86249     if( !pStmt ){
86250       /* this happens for a comment or white-space */
86251       zSql = zLeftover;
86252       continue;
86253     }
86254
86255     callbackIsInit = 0;
86256     nCol = sqlite3_column_count(pStmt);
86257
86258     while( 1 ){
86259       int i;
86260       rc = sqlite3_step(pStmt);
86261
86262       /* Invoke the callback function if required */
86263       if( xCallback && (SQLITE_ROW==rc || 
86264           (SQLITE_DONE==rc && !callbackIsInit
86265                            && db->flags&SQLITE_NullCallback)) ){
86266         if( !callbackIsInit ){
86267           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86268           if( azCols==0 ){
86269             goto exec_out;
86270           }
86271           for(i=0; i<nCol; i++){
86272             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86273             /* sqlite3VdbeSetColName() installs column names as UTF8
86274             ** strings so there is no way for sqlite3_column_name() to fail. */
86275             assert( azCols[i]!=0 );
86276           }
86277           callbackIsInit = 1;
86278         }
86279         if( rc==SQLITE_ROW ){
86280           azVals = &azCols[nCol];
86281           for(i=0; i<nCol; i++){
86282             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86283             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86284               db->mallocFailed = 1;
86285               goto exec_out;
86286             }
86287           }
86288         }
86289         if( xCallback(pArg, nCol, azVals, azCols) ){
86290           rc = SQLITE_ABORT;
86291           sqlite3VdbeFinalize((Vdbe *)pStmt);
86292           pStmt = 0;
86293           sqlite3Error(db, SQLITE_ABORT, 0);
86294           goto exec_out;
86295         }
86296       }
86297
86298       if( rc!=SQLITE_ROW ){
86299         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86300         pStmt = 0;
86301         if( rc!=SQLITE_SCHEMA ){
86302           nRetry = 0;
86303           zSql = zLeftover;
86304           while( sqlite3Isspace(zSql[0]) ) zSql++;
86305         }
86306         break;
86307       }
86308     }
86309
86310     sqlite3DbFree(db, azCols);
86311     azCols = 0;
86312   }
86313
86314 exec_out:
86315   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86316   sqlite3DbFree(db, azCols);
86317
86318   rc = sqlite3ApiExit(db, rc);
86319   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86320     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86321     *pzErrMsg = sqlite3Malloc(nErrMsg);
86322     if( *pzErrMsg ){
86323       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86324     }else{
86325       rc = SQLITE_NOMEM;
86326       sqlite3Error(db, SQLITE_NOMEM, 0);
86327     }
86328   }else if( pzErrMsg ){
86329     *pzErrMsg = 0;
86330   }
86331
86332   assert( (rc&db->errMask)==rc );
86333   sqlite3_mutex_leave(db->mutex);
86334   return rc;
86335 }
86336
86337 /************** End of legacy.c **********************************************/
86338 /************** Begin file loadext.c *****************************************/
86339 /*
86340 ** 2006 June 7
86341 **
86342 ** The author disclaims copyright to this source code.  In place of
86343 ** a legal notice, here is a blessing:
86344 **
86345 **    May you do good and not evil.
86346 **    May you find forgiveness for yourself and forgive others.
86347 **    May you share freely, never taking more than you give.
86348 **
86349 *************************************************************************
86350 ** This file contains code used to dynamically load extensions into
86351 ** the SQLite library.
86352 */
86353
86354 #ifndef SQLITE_CORE
86355   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
86356 #endif
86357 /************** Include sqlite3ext.h in the middle of loadext.c **************/
86358 /************** Begin file sqlite3ext.h **************************************/
86359 /*
86360 ** 2006 June 7
86361 **
86362 ** The author disclaims copyright to this source code.  In place of
86363 ** a legal notice, here is a blessing:
86364 **
86365 **    May you do good and not evil.
86366 **    May you find forgiveness for yourself and forgive others.
86367 **    May you share freely, never taking more than you give.
86368 **
86369 *************************************************************************
86370 ** This header file defines the SQLite interface for use by
86371 ** shared libraries that want to be imported as extensions into
86372 ** an SQLite instance.  Shared libraries that intend to be loaded
86373 ** as extensions by SQLite should #include this file instead of 
86374 ** sqlite3.h.
86375 */
86376 #ifndef _SQLITE3EXT_H_
86377 #define _SQLITE3EXT_H_
86378
86379 typedef struct sqlite3_api_routines sqlite3_api_routines;
86380
86381 /*
86382 ** The following structure holds pointers to all of the SQLite API
86383 ** routines.
86384 **
86385 ** WARNING:  In order to maintain backwards compatibility, add new
86386 ** interfaces to the end of this structure only.  If you insert new
86387 ** interfaces in the middle of this structure, then older different
86388 ** versions of SQLite will not be able to load each others' shared
86389 ** libraries!
86390 */
86391 struct sqlite3_api_routines {
86392   void * (*aggregate_context)(sqlite3_context*,int nBytes);
86393   int  (*aggregate_count)(sqlite3_context*);
86394   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
86395   int  (*bind_double)(sqlite3_stmt*,int,double);
86396   int  (*bind_int)(sqlite3_stmt*,int,int);
86397   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
86398   int  (*bind_null)(sqlite3_stmt*,int);
86399   int  (*bind_parameter_count)(sqlite3_stmt*);
86400   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
86401   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
86402   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
86403   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
86404   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
86405   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
86406   int  (*busy_timeout)(sqlite3*,int ms);
86407   int  (*changes)(sqlite3*);
86408   int  (*close)(sqlite3*);
86409   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
86410   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
86411   const void * (*column_blob)(sqlite3_stmt*,int iCol);
86412   int  (*column_bytes)(sqlite3_stmt*,int iCol);
86413   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
86414   int  (*column_count)(sqlite3_stmt*pStmt);
86415   const char * (*column_database_name)(sqlite3_stmt*,int);
86416   const void * (*column_database_name16)(sqlite3_stmt*,int);
86417   const char * (*column_decltype)(sqlite3_stmt*,int i);
86418   const void * (*column_decltype16)(sqlite3_stmt*,int);
86419   double  (*column_double)(sqlite3_stmt*,int iCol);
86420   int  (*column_int)(sqlite3_stmt*,int iCol);
86421   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
86422   const char * (*column_name)(sqlite3_stmt*,int);
86423   const void * (*column_name16)(sqlite3_stmt*,int);
86424   const char * (*column_origin_name)(sqlite3_stmt*,int);
86425   const void * (*column_origin_name16)(sqlite3_stmt*,int);
86426   const char * (*column_table_name)(sqlite3_stmt*,int);
86427   const void * (*column_table_name16)(sqlite3_stmt*,int);
86428   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
86429   const void * (*column_text16)(sqlite3_stmt*,int iCol);
86430   int  (*column_type)(sqlite3_stmt*,int iCol);
86431   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
86432   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
86433   int  (*complete)(const char*sql);
86434   int  (*complete16)(const void*sql);
86435   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
86436   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
86437   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*));
86438   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*));
86439   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
86440   int  (*data_count)(sqlite3_stmt*pStmt);
86441   sqlite3 * (*db_handle)(sqlite3_stmt*);
86442   int (*declare_vtab)(sqlite3*,const char*);
86443   int  (*enable_shared_cache)(int);
86444   int  (*errcode)(sqlite3*db);
86445   const char * (*errmsg)(sqlite3*);
86446   const void * (*errmsg16)(sqlite3*);
86447   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
86448   int  (*expired)(sqlite3_stmt*);
86449   int  (*finalize)(sqlite3_stmt*pStmt);
86450   void  (*free)(void*);
86451   void  (*free_table)(char**result);
86452   int  (*get_autocommit)(sqlite3*);
86453   void * (*get_auxdata)(sqlite3_context*,int);
86454   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
86455   int  (*global_recover)(void);
86456   void  (*interruptx)(sqlite3*);
86457   sqlite_int64  (*last_insert_rowid)(sqlite3*);
86458   const char * (*libversion)(void);
86459   int  (*libversion_number)(void);
86460   void *(*malloc)(int);
86461   char * (*mprintf)(const char*,...);
86462   int  (*open)(const char*,sqlite3**);
86463   int  (*open16)(const void*,sqlite3**);
86464   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86465   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86466   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
86467   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
86468   void *(*realloc)(void*,int);
86469   int  (*reset)(sqlite3_stmt*pStmt);
86470   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
86471   void  (*result_double)(sqlite3_context*,double);
86472   void  (*result_error)(sqlite3_context*,const char*,int);
86473   void  (*result_error16)(sqlite3_context*,const void*,int);
86474   void  (*result_int)(sqlite3_context*,int);
86475   void  (*result_int64)(sqlite3_context*,sqlite_int64);
86476   void  (*result_null)(sqlite3_context*);
86477   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
86478   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
86479   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
86480   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
86481   void  (*result_value)(sqlite3_context*,sqlite3_value*);
86482   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
86483   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
86484   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
86485   char * (*snprintf)(int,char*,const char*,...);
86486   int  (*step)(sqlite3_stmt*);
86487   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
86488   void  (*thread_cleanup)(void);
86489   int  (*total_changes)(sqlite3*);
86490   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
86491   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
86492   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
86493   void * (*user_data)(sqlite3_context*);
86494   const void * (*value_blob)(sqlite3_value*);
86495   int  (*value_bytes)(sqlite3_value*);
86496   int  (*value_bytes16)(sqlite3_value*);
86497   double  (*value_double)(sqlite3_value*);
86498   int  (*value_int)(sqlite3_value*);
86499   sqlite_int64  (*value_int64)(sqlite3_value*);
86500   int  (*value_numeric_type)(sqlite3_value*);
86501   const unsigned char * (*value_text)(sqlite3_value*);
86502   const void * (*value_text16)(sqlite3_value*);
86503   const void * (*value_text16be)(sqlite3_value*);
86504   const void * (*value_text16le)(sqlite3_value*);
86505   int  (*value_type)(sqlite3_value*);
86506   char *(*vmprintf)(const char*,va_list);
86507   /* Added ??? */
86508   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
86509   /* Added by 3.3.13 */
86510   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86511   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86512   int (*clear_bindings)(sqlite3_stmt*);
86513   /* Added by 3.4.1 */
86514   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
86515   /* Added by 3.5.0 */
86516   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
86517   int (*blob_bytes)(sqlite3_blob*);
86518   int (*blob_close)(sqlite3_blob*);
86519   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
86520   int (*blob_read)(sqlite3_blob*,void*,int,int);
86521   int (*blob_write)(sqlite3_blob*,const void*,int,int);
86522   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
86523   int (*file_control)(sqlite3*,const char*,int,void*);
86524   sqlite3_int64 (*memory_highwater)(int);
86525   sqlite3_int64 (*memory_used)(void);
86526   sqlite3_mutex *(*mutex_alloc)(int);
86527   void (*mutex_enter)(sqlite3_mutex*);
86528   void (*mutex_free)(sqlite3_mutex*);
86529   void (*mutex_leave)(sqlite3_mutex*);
86530   int (*mutex_try)(sqlite3_mutex*);
86531   int (*open_v2)(const char*,sqlite3**,int,const char*);
86532   int (*release_memory)(int);
86533   void (*result_error_nomem)(sqlite3_context*);
86534   void (*result_error_toobig)(sqlite3_context*);
86535   int (*sleep)(int);
86536   void (*soft_heap_limit)(int);
86537   sqlite3_vfs *(*vfs_find)(const char*);
86538   int (*vfs_register)(sqlite3_vfs*,int);
86539   int (*vfs_unregister)(sqlite3_vfs*);
86540   int (*xthreadsafe)(void);
86541   void (*result_zeroblob)(sqlite3_context*,int);
86542   void (*result_error_code)(sqlite3_context*,int);
86543   int (*test_control)(int, ...);
86544   void (*randomness)(int,void*);
86545   sqlite3 *(*context_db_handle)(sqlite3_context*);
86546   int (*extended_result_codes)(sqlite3*,int);
86547   int (*limit)(sqlite3*,int,int);
86548   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
86549   const char *(*sql)(sqlite3_stmt*);
86550   int (*status)(int,int*,int*,int);
86551   int (*backup_finish)(sqlite3_backup*);
86552   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
86553   int (*backup_pagecount)(sqlite3_backup*);
86554   int (*backup_remaining)(sqlite3_backup*);
86555   int (*backup_step)(sqlite3_backup*,int);
86556   const char *(*compileoption_get)(int);
86557   int (*compileoption_used)(const char*);
86558   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*));
86559   int (*db_config)(sqlite3*,int,...);
86560   sqlite3_mutex *(*db_mutex)(sqlite3*);
86561   int (*db_status)(sqlite3*,int,int*,int*,int);
86562   int (*extended_errcode)(sqlite3*);
86563   void (*log)(int,const char*,...);
86564   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
86565   const char *(*sourceid)(void);
86566   int (*stmt_status)(sqlite3_stmt*,int,int);
86567   int (*strnicmp)(const char*,const char*,int);
86568   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
86569   int (*wal_autocheckpoint)(sqlite3*,int);
86570   int (*wal_checkpoint)(sqlite3*,const char*);
86571   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
86572 };
86573
86574 /*
86575 ** The following macros redefine the API routines so that they are
86576 ** redirected throught the global sqlite3_api structure.
86577 **
86578 ** This header file is also used by the loadext.c source file
86579 ** (part of the main SQLite library - not an extension) so that
86580 ** it can get access to the sqlite3_api_routines structure
86581 ** definition.  But the main library does not want to redefine
86582 ** the API.  So the redefinition macros are only valid if the
86583 ** SQLITE_CORE macros is undefined.
86584 */
86585 #ifndef SQLITE_CORE
86586 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
86587 #ifndef SQLITE_OMIT_DEPRECATED
86588 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
86589 #endif
86590 #define sqlite3_bind_blob              sqlite3_api->bind_blob
86591 #define sqlite3_bind_double            sqlite3_api->bind_double
86592 #define sqlite3_bind_int               sqlite3_api->bind_int
86593 #define sqlite3_bind_int64             sqlite3_api->bind_int64
86594 #define sqlite3_bind_null              sqlite3_api->bind_null
86595 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
86596 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
86597 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
86598 #define sqlite3_bind_text              sqlite3_api->bind_text
86599 #define sqlite3_bind_text16            sqlite3_api->bind_text16
86600 #define sqlite3_bind_value             sqlite3_api->bind_value
86601 #define sqlite3_busy_handler           sqlite3_api->busy_handler
86602 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
86603 #define sqlite3_changes                sqlite3_api->changes
86604 #define sqlite3_close                  sqlite3_api->close
86605 #define sqlite3_collation_needed       sqlite3_api->collation_needed
86606 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
86607 #define sqlite3_column_blob            sqlite3_api->column_blob
86608 #define sqlite3_column_bytes           sqlite3_api->column_bytes
86609 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
86610 #define sqlite3_column_count           sqlite3_api->column_count
86611 #define sqlite3_column_database_name   sqlite3_api->column_database_name
86612 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
86613 #define sqlite3_column_decltype        sqlite3_api->column_decltype
86614 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
86615 #define sqlite3_column_double          sqlite3_api->column_double
86616 #define sqlite3_column_int             sqlite3_api->column_int
86617 #define sqlite3_column_int64           sqlite3_api->column_int64
86618 #define sqlite3_column_name            sqlite3_api->column_name
86619 #define sqlite3_column_name16          sqlite3_api->column_name16
86620 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
86621 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
86622 #define sqlite3_column_table_name      sqlite3_api->column_table_name
86623 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
86624 #define sqlite3_column_text            sqlite3_api->column_text
86625 #define sqlite3_column_text16          sqlite3_api->column_text16
86626 #define sqlite3_column_type            sqlite3_api->column_type
86627 #define sqlite3_column_value           sqlite3_api->column_value
86628 #define sqlite3_commit_hook            sqlite3_api->commit_hook
86629 #define sqlite3_complete               sqlite3_api->complete
86630 #define sqlite3_complete16             sqlite3_api->complete16
86631 #define sqlite3_create_collation       sqlite3_api->create_collation
86632 #define sqlite3_create_collation16     sqlite3_api->create_collation16
86633 #define sqlite3_create_function        sqlite3_api->create_function
86634 #define sqlite3_create_function16      sqlite3_api->create_function16
86635 #define sqlite3_create_module          sqlite3_api->create_module
86636 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
86637 #define sqlite3_data_count             sqlite3_api->data_count
86638 #define sqlite3_db_handle              sqlite3_api->db_handle
86639 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
86640 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
86641 #define sqlite3_errcode                sqlite3_api->errcode
86642 #define sqlite3_errmsg                 sqlite3_api->errmsg
86643 #define sqlite3_errmsg16               sqlite3_api->errmsg16
86644 #define sqlite3_exec                   sqlite3_api->exec
86645 #ifndef SQLITE_OMIT_DEPRECATED
86646 #define sqlite3_expired                sqlite3_api->expired
86647 #endif
86648 #define sqlite3_finalize               sqlite3_api->finalize
86649 #define sqlite3_free                   sqlite3_api->free
86650 #define sqlite3_free_table             sqlite3_api->free_table
86651 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
86652 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
86653 #define sqlite3_get_table              sqlite3_api->get_table
86654 #ifndef SQLITE_OMIT_DEPRECATED
86655 #define sqlite3_global_recover         sqlite3_api->global_recover
86656 #endif
86657 #define sqlite3_interrupt              sqlite3_api->interruptx
86658 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
86659 #define sqlite3_libversion             sqlite3_api->libversion
86660 #define sqlite3_libversion_number      sqlite3_api->libversion_number
86661 #define sqlite3_malloc                 sqlite3_api->malloc
86662 #define sqlite3_mprintf                sqlite3_api->mprintf
86663 #define sqlite3_open                   sqlite3_api->open
86664 #define sqlite3_open16                 sqlite3_api->open16
86665 #define sqlite3_prepare                sqlite3_api->prepare
86666 #define sqlite3_prepare16              sqlite3_api->prepare16
86667 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86668 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86669 #define sqlite3_profile                sqlite3_api->profile
86670 #define sqlite3_progress_handler       sqlite3_api->progress_handler
86671 #define sqlite3_realloc                sqlite3_api->realloc
86672 #define sqlite3_reset                  sqlite3_api->reset
86673 #define sqlite3_result_blob            sqlite3_api->result_blob
86674 #define sqlite3_result_double          sqlite3_api->result_double
86675 #define sqlite3_result_error           sqlite3_api->result_error
86676 #define sqlite3_result_error16         sqlite3_api->result_error16
86677 #define sqlite3_result_int             sqlite3_api->result_int
86678 #define sqlite3_result_int64           sqlite3_api->result_int64
86679 #define sqlite3_result_null            sqlite3_api->result_null
86680 #define sqlite3_result_text            sqlite3_api->result_text
86681 #define sqlite3_result_text16          sqlite3_api->result_text16
86682 #define sqlite3_result_text16be        sqlite3_api->result_text16be
86683 #define sqlite3_result_text16le        sqlite3_api->result_text16le
86684 #define sqlite3_result_value           sqlite3_api->result_value
86685 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
86686 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
86687 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
86688 #define sqlite3_snprintf               sqlite3_api->snprintf
86689 #define sqlite3_step                   sqlite3_api->step
86690 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
86691 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
86692 #define sqlite3_total_changes          sqlite3_api->total_changes
86693 #define sqlite3_trace                  sqlite3_api->trace
86694 #ifndef SQLITE_OMIT_DEPRECATED
86695 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
86696 #endif
86697 #define sqlite3_update_hook            sqlite3_api->update_hook
86698 #define sqlite3_user_data              sqlite3_api->user_data
86699 #define sqlite3_value_blob             sqlite3_api->value_blob
86700 #define sqlite3_value_bytes            sqlite3_api->value_bytes
86701 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
86702 #define sqlite3_value_double           sqlite3_api->value_double
86703 #define sqlite3_value_int              sqlite3_api->value_int
86704 #define sqlite3_value_int64            sqlite3_api->value_int64
86705 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
86706 #define sqlite3_value_text             sqlite3_api->value_text
86707 #define sqlite3_value_text16           sqlite3_api->value_text16
86708 #define sqlite3_value_text16be         sqlite3_api->value_text16be
86709 #define sqlite3_value_text16le         sqlite3_api->value_text16le
86710 #define sqlite3_value_type             sqlite3_api->value_type
86711 #define sqlite3_vmprintf               sqlite3_api->vmprintf
86712 #define sqlite3_overload_function      sqlite3_api->overload_function
86713 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
86714 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
86715 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
86716 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
86717 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
86718 #define sqlite3_blob_close             sqlite3_api->blob_close
86719 #define sqlite3_blob_open              sqlite3_api->blob_open
86720 #define sqlite3_blob_read              sqlite3_api->blob_read
86721 #define sqlite3_blob_write             sqlite3_api->blob_write
86722 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
86723 #define sqlite3_file_control           sqlite3_api->file_control
86724 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
86725 #define sqlite3_memory_used            sqlite3_api->memory_used
86726 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
86727 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
86728 #define sqlite3_mutex_free             sqlite3_api->mutex_free
86729 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
86730 #define sqlite3_mutex_try              sqlite3_api->mutex_try
86731 #define sqlite3_open_v2                sqlite3_api->open_v2
86732 #define sqlite3_release_memory         sqlite3_api->release_memory
86733 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
86734 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
86735 #define sqlite3_sleep                  sqlite3_api->sleep
86736 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
86737 #define sqlite3_vfs_find               sqlite3_api->vfs_find
86738 #define sqlite3_vfs_register           sqlite3_api->vfs_register
86739 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
86740 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
86741 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
86742 #define sqlite3_result_error_code      sqlite3_api->result_error_code
86743 #define sqlite3_test_control           sqlite3_api->test_control
86744 #define sqlite3_randomness             sqlite3_api->randomness
86745 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
86746 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
86747 #define sqlite3_limit                  sqlite3_api->limit
86748 #define sqlite3_next_stmt              sqlite3_api->next_stmt
86749 #define sqlite3_sql                    sqlite3_api->sql
86750 #define sqlite3_status                 sqlite3_api->status
86751 #define sqlite3_backup_finish          sqlite3_api->backup_finish
86752 #define sqlite3_backup_init            sqlite3_api->backup_init
86753 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
86754 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
86755 #define sqlite3_backup_step            sqlite3_api->backup_step
86756 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
86757 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
86758 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
86759 #define sqlite3_db_config              sqlite3_api->db_config
86760 #define sqlite3_db_mutex               sqlite3_api->db_mutex
86761 #define sqlite3_db_status              sqlite3_api->db_status
86762 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
86763 #define sqlite3_log                    sqlite3_api->log
86764 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
86765 #define sqlite3_sourceid               sqlite3_api->sourceid
86766 #define sqlite3_stmt_status            sqlite3_api->stmt_status
86767 #define sqlite3_strnicmp               sqlite3_api->strnicmp
86768 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
86769 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
86770 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
86771 #define sqlite3_wal_hook               sqlite3_api->wal_hook
86772 #endif /* SQLITE_CORE */
86773
86774 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
86775 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
86776
86777 #endif /* _SQLITE3EXT_H_ */
86778
86779 /************** End of sqlite3ext.h ******************************************/
86780 /************** Continuing where we left off in loadext.c ********************/
86781
86782 #ifndef SQLITE_OMIT_LOAD_EXTENSION
86783
86784 /*
86785 ** Some API routines are omitted when various features are
86786 ** excluded from a build of SQLite.  Substitute a NULL pointer
86787 ** for any missing APIs.
86788 */
86789 #ifndef SQLITE_ENABLE_COLUMN_METADATA
86790 # define sqlite3_column_database_name   0
86791 # define sqlite3_column_database_name16 0
86792 # define sqlite3_column_table_name      0
86793 # define sqlite3_column_table_name16    0
86794 # define sqlite3_column_origin_name     0
86795 # define sqlite3_column_origin_name16   0
86796 # define sqlite3_table_column_metadata  0
86797 #endif
86798
86799 #ifdef SQLITE_OMIT_AUTHORIZATION
86800 # define sqlite3_set_authorizer         0
86801 #endif
86802
86803 #ifdef SQLITE_OMIT_UTF16
86804 # define sqlite3_bind_text16            0
86805 # define sqlite3_collation_needed16     0
86806 # define sqlite3_column_decltype16      0
86807 # define sqlite3_column_name16          0
86808 # define sqlite3_column_text16          0
86809 # define sqlite3_complete16             0
86810 # define sqlite3_create_collation16     0
86811 # define sqlite3_create_function16      0
86812 # define sqlite3_errmsg16               0
86813 # define sqlite3_open16                 0
86814 # define sqlite3_prepare16              0
86815 # define sqlite3_prepare16_v2           0
86816 # define sqlite3_result_error16         0
86817 # define sqlite3_result_text16          0
86818 # define sqlite3_result_text16be        0
86819 # define sqlite3_result_text16le        0
86820 # define sqlite3_value_text16           0
86821 # define sqlite3_value_text16be         0
86822 # define sqlite3_value_text16le         0
86823 # define sqlite3_column_database_name16 0
86824 # define sqlite3_column_table_name16    0
86825 # define sqlite3_column_origin_name16   0
86826 #endif
86827
86828 #ifdef SQLITE_OMIT_COMPLETE
86829 # define sqlite3_complete 0
86830 # define sqlite3_complete16 0
86831 #endif
86832
86833 #ifdef SQLITE_OMIT_DECLTYPE
86834 # define sqlite3_column_decltype16      0
86835 # define sqlite3_column_decltype        0
86836 #endif
86837
86838 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
86839 # define sqlite3_progress_handler 0
86840 #endif
86841
86842 #ifdef SQLITE_OMIT_VIRTUALTABLE
86843 # define sqlite3_create_module 0
86844 # define sqlite3_create_module_v2 0
86845 # define sqlite3_declare_vtab 0
86846 #endif
86847
86848 #ifdef SQLITE_OMIT_SHARED_CACHE
86849 # define sqlite3_enable_shared_cache 0
86850 #endif
86851
86852 #ifdef SQLITE_OMIT_TRACE
86853 # define sqlite3_profile       0
86854 # define sqlite3_trace         0
86855 #endif
86856
86857 #ifdef SQLITE_OMIT_GET_TABLE
86858 # define sqlite3_free_table    0
86859 # define sqlite3_get_table     0
86860 #endif
86861
86862 #ifdef SQLITE_OMIT_INCRBLOB
86863 #define sqlite3_bind_zeroblob  0
86864 #define sqlite3_blob_bytes     0
86865 #define sqlite3_blob_close     0
86866 #define sqlite3_blob_open      0
86867 #define sqlite3_blob_read      0
86868 #define sqlite3_blob_write     0
86869 #endif
86870
86871 /*
86872 ** The following structure contains pointers to all SQLite API routines.
86873 ** A pointer to this structure is passed into extensions when they are
86874 ** loaded so that the extension can make calls back into the SQLite
86875 ** library.
86876 **
86877 ** When adding new APIs, add them to the bottom of this structure
86878 ** in order to preserve backwards compatibility.
86879 **
86880 ** Extensions that use newer APIs should first call the
86881 ** sqlite3_libversion_number() to make sure that the API they
86882 ** intend to use is supported by the library.  Extensions should
86883 ** also check to make sure that the pointer to the function is
86884 ** not NULL before calling it.
86885 */
86886 static const sqlite3_api_routines sqlite3Apis = {
86887   sqlite3_aggregate_context,
86888 #ifndef SQLITE_OMIT_DEPRECATED
86889   sqlite3_aggregate_count,
86890 #else
86891   0,
86892 #endif
86893   sqlite3_bind_blob,
86894   sqlite3_bind_double,
86895   sqlite3_bind_int,
86896   sqlite3_bind_int64,
86897   sqlite3_bind_null,
86898   sqlite3_bind_parameter_count,
86899   sqlite3_bind_parameter_index,
86900   sqlite3_bind_parameter_name,
86901   sqlite3_bind_text,
86902   sqlite3_bind_text16,
86903   sqlite3_bind_value,
86904   sqlite3_busy_handler,
86905   sqlite3_busy_timeout,
86906   sqlite3_changes,
86907   sqlite3_close,
86908   sqlite3_collation_needed,
86909   sqlite3_collation_needed16,
86910   sqlite3_column_blob,
86911   sqlite3_column_bytes,
86912   sqlite3_column_bytes16,
86913   sqlite3_column_count,
86914   sqlite3_column_database_name,
86915   sqlite3_column_database_name16,
86916   sqlite3_column_decltype,
86917   sqlite3_column_decltype16,
86918   sqlite3_column_double,
86919   sqlite3_column_int,
86920   sqlite3_column_int64,
86921   sqlite3_column_name,
86922   sqlite3_column_name16,
86923   sqlite3_column_origin_name,
86924   sqlite3_column_origin_name16,
86925   sqlite3_column_table_name,
86926   sqlite3_column_table_name16,
86927   sqlite3_column_text,
86928   sqlite3_column_text16,
86929   sqlite3_column_type,
86930   sqlite3_column_value,
86931   sqlite3_commit_hook,
86932   sqlite3_complete,
86933   sqlite3_complete16,
86934   sqlite3_create_collation,
86935   sqlite3_create_collation16,
86936   sqlite3_create_function,
86937   sqlite3_create_function16,
86938   sqlite3_create_module,
86939   sqlite3_data_count,
86940   sqlite3_db_handle,
86941   sqlite3_declare_vtab,
86942   sqlite3_enable_shared_cache,
86943   sqlite3_errcode,
86944   sqlite3_errmsg,
86945   sqlite3_errmsg16,
86946   sqlite3_exec,
86947 #ifndef SQLITE_OMIT_DEPRECATED
86948   sqlite3_expired,
86949 #else
86950   0,
86951 #endif
86952   sqlite3_finalize,
86953   sqlite3_free,
86954   sqlite3_free_table,
86955   sqlite3_get_autocommit,
86956   sqlite3_get_auxdata,
86957   sqlite3_get_table,
86958   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
86959   sqlite3_interrupt,
86960   sqlite3_last_insert_rowid,
86961   sqlite3_libversion,
86962   sqlite3_libversion_number,
86963   sqlite3_malloc,
86964   sqlite3_mprintf,
86965   sqlite3_open,
86966   sqlite3_open16,
86967   sqlite3_prepare,
86968   sqlite3_prepare16,
86969   sqlite3_profile,
86970   sqlite3_progress_handler,
86971   sqlite3_realloc,
86972   sqlite3_reset,
86973   sqlite3_result_blob,
86974   sqlite3_result_double,
86975   sqlite3_result_error,
86976   sqlite3_result_error16,
86977   sqlite3_result_int,
86978   sqlite3_result_int64,
86979   sqlite3_result_null,
86980   sqlite3_result_text,
86981   sqlite3_result_text16,
86982   sqlite3_result_text16be,
86983   sqlite3_result_text16le,
86984   sqlite3_result_value,
86985   sqlite3_rollback_hook,
86986   sqlite3_set_authorizer,
86987   sqlite3_set_auxdata,
86988   sqlite3_snprintf,
86989   sqlite3_step,
86990   sqlite3_table_column_metadata,
86991 #ifndef SQLITE_OMIT_DEPRECATED
86992   sqlite3_thread_cleanup,
86993 #else
86994   0,
86995 #endif
86996   sqlite3_total_changes,
86997   sqlite3_trace,
86998 #ifndef SQLITE_OMIT_DEPRECATED
86999   sqlite3_transfer_bindings,
87000 #else
87001   0,
87002 #endif
87003   sqlite3_update_hook,
87004   sqlite3_user_data,
87005   sqlite3_value_blob,
87006   sqlite3_value_bytes,
87007   sqlite3_value_bytes16,
87008   sqlite3_value_double,
87009   sqlite3_value_int,
87010   sqlite3_value_int64,
87011   sqlite3_value_numeric_type,
87012   sqlite3_value_text,
87013   sqlite3_value_text16,
87014   sqlite3_value_text16be,
87015   sqlite3_value_text16le,
87016   sqlite3_value_type,
87017   sqlite3_vmprintf,
87018   /*
87019   ** The original API set ends here.  All extensions can call any
87020   ** of the APIs above provided that the pointer is not NULL.  But
87021   ** before calling APIs that follow, extension should check the
87022   ** sqlite3_libversion_number() to make sure they are dealing with
87023   ** a library that is new enough to support that API.
87024   *************************************************************************
87025   */
87026   sqlite3_overload_function,
87027
87028   /*
87029   ** Added after 3.3.13
87030   */
87031   sqlite3_prepare_v2,
87032   sqlite3_prepare16_v2,
87033   sqlite3_clear_bindings,
87034
87035   /*
87036   ** Added for 3.4.1
87037   */
87038   sqlite3_create_module_v2,
87039
87040   /*
87041   ** Added for 3.5.0
87042   */
87043   sqlite3_bind_zeroblob,
87044   sqlite3_blob_bytes,
87045   sqlite3_blob_close,
87046   sqlite3_blob_open,
87047   sqlite3_blob_read,
87048   sqlite3_blob_write,
87049   sqlite3_create_collation_v2,
87050   sqlite3_file_control,
87051   sqlite3_memory_highwater,
87052   sqlite3_memory_used,
87053 #ifdef SQLITE_MUTEX_OMIT
87054   0, 
87055   0, 
87056   0,
87057   0,
87058   0,
87059 #else
87060   sqlite3_mutex_alloc,
87061   sqlite3_mutex_enter,
87062   sqlite3_mutex_free,
87063   sqlite3_mutex_leave,
87064   sqlite3_mutex_try,
87065 #endif
87066   sqlite3_open_v2,
87067   sqlite3_release_memory,
87068   sqlite3_result_error_nomem,
87069   sqlite3_result_error_toobig,
87070   sqlite3_sleep,
87071   sqlite3_soft_heap_limit,
87072   sqlite3_vfs_find,
87073   sqlite3_vfs_register,
87074   sqlite3_vfs_unregister,
87075
87076   /*
87077   ** Added for 3.5.8
87078   */
87079   sqlite3_threadsafe,
87080   sqlite3_result_zeroblob,
87081   sqlite3_result_error_code,
87082   sqlite3_test_control,
87083   sqlite3_randomness,
87084   sqlite3_context_db_handle,
87085
87086   /*
87087   ** Added for 3.6.0
87088   */
87089   sqlite3_extended_result_codes,
87090   sqlite3_limit,
87091   sqlite3_next_stmt,
87092   sqlite3_sql,
87093   sqlite3_status,
87094
87095   /*
87096   ** Added for 3.7.4
87097   */
87098   sqlite3_backup_finish,
87099   sqlite3_backup_init,
87100   sqlite3_backup_pagecount,
87101   sqlite3_backup_remaining,
87102   sqlite3_backup_step,
87103 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87104   sqlite3_compileoption_get,
87105   sqlite3_compileoption_used,
87106 #else
87107   0,
87108   0,
87109 #endif
87110   sqlite3_create_function_v2,
87111   sqlite3_db_config,
87112   sqlite3_db_mutex,
87113   sqlite3_db_status,
87114   sqlite3_extended_errcode,
87115   sqlite3_log,
87116   sqlite3_soft_heap_limit64,
87117   sqlite3_sourceid,
87118   sqlite3_stmt_status,
87119   sqlite3_strnicmp,
87120 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87121   sqlite3_unlock_notify,
87122 #else
87123   0,
87124 #endif
87125 #ifndef SQLITE_OMIT_WAL
87126   sqlite3_wal_autocheckpoint,
87127   sqlite3_wal_checkpoint,
87128   sqlite3_wal_hook,
87129 #else
87130   0,
87131   0,
87132   0,
87133 #endif
87134 };
87135
87136 /*
87137 ** Attempt to load an SQLite extension library contained in the file
87138 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
87139 ** default entry point name (sqlite3_extension_init) is used.  Use
87140 ** of the default name is recommended.
87141 **
87142 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87143 **
87144 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
87145 ** error message text.  The calling function should free this memory
87146 ** by calling sqlite3DbFree(db, ).
87147 */
87148 static int sqlite3LoadExtension(
87149   sqlite3 *db,          /* Load the extension into this database connection */
87150   const char *zFile,    /* Name of the shared library containing extension */
87151   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87152   char **pzErrMsg       /* Put error message here if not 0 */
87153 ){
87154   sqlite3_vfs *pVfs = db->pVfs;
87155   void *handle;
87156   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87157   char *zErrmsg = 0;
87158   void **aHandle;
87159   const int nMsg = 300;
87160
87161   if( pzErrMsg ) *pzErrMsg = 0;
87162
87163   /* Ticket #1863.  To avoid a creating security problems for older
87164   ** applications that relink against newer versions of SQLite, the
87165   ** ability to run load_extension is turned off by default.  One
87166   ** must call sqlite3_enable_load_extension() to turn on extension
87167   ** loading.  Otherwise you get the following error.
87168   */
87169   if( (db->flags & SQLITE_LoadExtension)==0 ){
87170     if( pzErrMsg ){
87171       *pzErrMsg = sqlite3_mprintf("not authorized");
87172     }
87173     return SQLITE_ERROR;
87174   }
87175
87176   if( zProc==0 ){
87177     zProc = "sqlite3_extension_init";
87178   }
87179
87180   handle = sqlite3OsDlOpen(pVfs, zFile);
87181   if( handle==0 ){
87182     if( pzErrMsg ){
87183       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87184       if( zErrmsg ){
87185         sqlite3_snprintf(nMsg, zErrmsg, 
87186             "unable to open shared library [%s]", zFile);
87187         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87188       }
87189     }
87190     return SQLITE_ERROR;
87191   }
87192   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87193                    sqlite3OsDlSym(pVfs, handle, zProc);
87194   if( xInit==0 ){
87195     if( pzErrMsg ){
87196       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87197       if( zErrmsg ){
87198         sqlite3_snprintf(nMsg, zErrmsg,
87199             "no entry point [%s] in shared library [%s]", zProc,zFile);
87200         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87201       }
87202       sqlite3OsDlClose(pVfs, handle);
87203     }
87204     return SQLITE_ERROR;
87205   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87206     if( pzErrMsg ){
87207       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87208     }
87209     sqlite3_free(zErrmsg);
87210     sqlite3OsDlClose(pVfs, handle);
87211     return SQLITE_ERROR;
87212   }
87213
87214   /* Append the new shared library handle to the db->aExtension array. */
87215   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87216   if( aHandle==0 ){
87217     return SQLITE_NOMEM;
87218   }
87219   if( db->nExtension>0 ){
87220     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87221   }
87222   sqlite3DbFree(db, db->aExtension);
87223   db->aExtension = aHandle;
87224
87225   db->aExtension[db->nExtension++] = handle;
87226   return SQLITE_OK;
87227 }
87228 SQLITE_API int sqlite3_load_extension(
87229   sqlite3 *db,          /* Load the extension into this database connection */
87230   const char *zFile,    /* Name of the shared library containing extension */
87231   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87232   char **pzErrMsg       /* Put error message here if not 0 */
87233 ){
87234   int rc;
87235   sqlite3_mutex_enter(db->mutex);
87236   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87237   rc = sqlite3ApiExit(db, rc);
87238   sqlite3_mutex_leave(db->mutex);
87239   return rc;
87240 }
87241
87242 /*
87243 ** Call this routine when the database connection is closing in order
87244 ** to clean up loaded extensions
87245 */
87246 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87247   int i;
87248   assert( sqlite3_mutex_held(db->mutex) );
87249   for(i=0; i<db->nExtension; i++){
87250     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87251   }
87252   sqlite3DbFree(db, db->aExtension);
87253 }
87254
87255 /*
87256 ** Enable or disable extension loading.  Extension loading is disabled by
87257 ** default so as not to open security holes in older applications.
87258 */
87259 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87260   sqlite3_mutex_enter(db->mutex);
87261   if( onoff ){
87262     db->flags |= SQLITE_LoadExtension;
87263   }else{
87264     db->flags &= ~SQLITE_LoadExtension;
87265   }
87266   sqlite3_mutex_leave(db->mutex);
87267   return SQLITE_OK;
87268 }
87269
87270 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
87271
87272 /*
87273 ** The auto-extension code added regardless of whether or not extension
87274 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
87275 ** code if regular extension loading is not available.  This is that
87276 ** dummy pointer.
87277 */
87278 #ifdef SQLITE_OMIT_LOAD_EXTENSION
87279 static const sqlite3_api_routines sqlite3Apis = { 0 };
87280 #endif
87281
87282
87283 /*
87284 ** The following object holds the list of automatically loaded
87285 ** extensions.
87286 **
87287 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
87288 ** mutex must be held while accessing this list.
87289 */
87290 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87291 static SQLITE_WSD struct sqlite3AutoExtList {
87292   int nExt;              /* Number of entries in aExt[] */          
87293   void (**aExt)(void);   /* Pointers to the extension init functions */
87294 } sqlite3Autoext = { 0, 0 };
87295
87296 /* The "wsdAutoext" macro will resolve to the autoextension
87297 ** state vector.  If writable static data is unsupported on the target,
87298 ** we have to locate the state vector at run-time.  In the more common
87299 ** case where writable static data is supported, wsdStat can refer directly
87300 ** to the "sqlite3Autoext" state vector declared above.
87301 */
87302 #ifdef SQLITE_OMIT_WSD
87303 # define wsdAutoextInit \
87304   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87305 # define wsdAutoext x[0]
87306 #else
87307 # define wsdAutoextInit
87308 # define wsdAutoext sqlite3Autoext
87309 #endif
87310
87311
87312 /*
87313 ** Register a statically linked extension that is automatically
87314 ** loaded by every new database connection.
87315 */
87316 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87317   int rc = SQLITE_OK;
87318 #ifndef SQLITE_OMIT_AUTOINIT
87319   rc = sqlite3_initialize();
87320   if( rc ){
87321     return rc;
87322   }else
87323 #endif
87324   {
87325     int i;
87326 #if SQLITE_THREADSAFE
87327     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87328 #endif
87329     wsdAutoextInit;
87330     sqlite3_mutex_enter(mutex);
87331     for(i=0; i<wsdAutoext.nExt; i++){
87332       if( wsdAutoext.aExt[i]==xInit ) break;
87333     }
87334     if( i==wsdAutoext.nExt ){
87335       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
87336       void (**aNew)(void);
87337       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
87338       if( aNew==0 ){
87339         rc = SQLITE_NOMEM;
87340       }else{
87341         wsdAutoext.aExt = aNew;
87342         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
87343         wsdAutoext.nExt++;
87344       }
87345     }
87346     sqlite3_mutex_leave(mutex);
87347     assert( (rc&0xff)==rc );
87348     return rc;
87349   }
87350 }
87351
87352 /*
87353 ** Reset the automatic extension loading mechanism.
87354 */
87355 SQLITE_API void sqlite3_reset_auto_extension(void){
87356 #ifndef SQLITE_OMIT_AUTOINIT
87357   if( sqlite3_initialize()==SQLITE_OK )
87358 #endif
87359   {
87360 #if SQLITE_THREADSAFE
87361     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87362 #endif
87363     wsdAutoextInit;
87364     sqlite3_mutex_enter(mutex);
87365     sqlite3_free(wsdAutoext.aExt);
87366     wsdAutoext.aExt = 0;
87367     wsdAutoext.nExt = 0;
87368     sqlite3_mutex_leave(mutex);
87369   }
87370 }
87371
87372 /*
87373 ** Load all automatic extensions.
87374 **
87375 ** If anything goes wrong, set an error in the database connection.
87376 */
87377 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
87378   int i;
87379   int go = 1;
87380   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87381
87382   wsdAutoextInit;
87383   if( wsdAutoext.nExt==0 ){
87384     /* Common case: early out without every having to acquire a mutex */
87385     return;
87386   }
87387   for(i=0; go; i++){
87388     char *zErrmsg;
87389 #if SQLITE_THREADSAFE
87390     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87391 #endif
87392     sqlite3_mutex_enter(mutex);
87393     if( i>=wsdAutoext.nExt ){
87394       xInit = 0;
87395       go = 0;
87396     }else{
87397       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87398               wsdAutoext.aExt[i];
87399     }
87400     sqlite3_mutex_leave(mutex);
87401     zErrmsg = 0;
87402     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
87403       sqlite3Error(db, SQLITE_ERROR,
87404             "automatic extension loading failed: %s", zErrmsg);
87405       go = 0;
87406     }
87407     sqlite3_free(zErrmsg);
87408   }
87409 }
87410
87411 /************** End of loadext.c *********************************************/
87412 /************** Begin file pragma.c ******************************************/
87413 /*
87414 ** 2003 April 6
87415 **
87416 ** The author disclaims copyright to this source code.  In place of
87417 ** a legal notice, here is a blessing:
87418 **
87419 **    May you do good and not evil.
87420 **    May you find forgiveness for yourself and forgive others.
87421 **    May you share freely, never taking more than you give.
87422 **
87423 *************************************************************************
87424 ** This file contains code used to implement the PRAGMA command.
87425 */
87426
87427 /* Ignore this whole file if pragmas are disabled
87428 */
87429 #if !defined(SQLITE_OMIT_PRAGMA)
87430
87431 /*
87432 ** Interpret the given string as a safety level.  Return 0 for OFF,
87433 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
87434 ** unrecognized string argument.
87435 **
87436 ** Note that the values returned are one less that the values that
87437 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
87438 ** to support legacy SQL code.  The safety level used to be boolean
87439 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
87440 */
87441 static u8 getSafetyLevel(const char *z){
87442                              /* 123456789 123456789 */
87443   static const char zText[] = "onoffalseyestruefull";
87444   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
87445   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
87446   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
87447   int i, n;
87448   if( sqlite3Isdigit(*z) ){
87449     return (u8)sqlite3Atoi(z);
87450   }
87451   n = sqlite3Strlen30(z);
87452   for(i=0; i<ArraySize(iLength); i++){
87453     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
87454       return iValue[i];
87455     }
87456   }
87457   return 1;
87458 }
87459
87460 /*
87461 ** Interpret the given string as a boolean value.
87462 */
87463 static u8 getBoolean(const char *z){
87464   return getSafetyLevel(z)&1;
87465 }
87466
87467 /*
87468 ** Interpret the given string as a locking mode value.
87469 */
87470 static int getLockingMode(const char *z){
87471   if( z ){
87472     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
87473     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87474   }
87475   return PAGER_LOCKINGMODE_QUERY;
87476 }
87477
87478 #ifndef SQLITE_OMIT_AUTOVACUUM
87479 /*
87480 ** Interpret the given string as an auto-vacuum mode value.
87481 **
87482 ** The following strings, "none", "full" and "incremental" are 
87483 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
87484 */
87485 static int getAutoVacuum(const char *z){
87486   int i;
87487   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
87488   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
87489   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
87490   i = sqlite3Atoi(z);
87491   return (u8)((i>=0&&i<=2)?i:0);
87492 }
87493 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
87494
87495 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87496 /*
87497 ** Interpret the given string as a temp db location. Return 1 for file
87498 ** backed temporary databases, 2 for the Red-Black tree in memory database
87499 ** and 0 to use the compile-time default.
87500 */
87501 static int getTempStore(const char *z){
87502   if( z[0]>='0' && z[0]<='2' ){
87503     return z[0] - '0';
87504   }else if( sqlite3StrICmp(z, "file")==0 ){
87505     return 1;
87506   }else if( sqlite3StrICmp(z, "memory")==0 ){
87507     return 2;
87508   }else{
87509     return 0;
87510   }
87511 }
87512 #endif /* SQLITE_PAGER_PRAGMAS */
87513
87514 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87515 /*
87516 ** Invalidate temp storage, either when the temp storage is changed
87517 ** from default, or when 'file' and the temp_store_directory has changed
87518 */
87519 static int invalidateTempStorage(Parse *pParse){
87520   sqlite3 *db = pParse->db;
87521   if( db->aDb[1].pBt!=0 ){
87522     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
87523       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
87524         "from within a transaction");
87525       return SQLITE_ERROR;
87526     }
87527     sqlite3BtreeClose(db->aDb[1].pBt);
87528     db->aDb[1].pBt = 0;
87529     sqlite3ResetInternalSchema(db, -1);
87530   }
87531   return SQLITE_OK;
87532 }
87533 #endif /* SQLITE_PAGER_PRAGMAS */
87534
87535 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87536 /*
87537 ** If the TEMP database is open, close it and mark the database schema
87538 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
87539 ** or DEFAULT_TEMP_STORE pragmas.
87540 */
87541 static int changeTempStorage(Parse *pParse, const char *zStorageType){
87542   int ts = getTempStore(zStorageType);
87543   sqlite3 *db = pParse->db;
87544   if( db->temp_store==ts ) return SQLITE_OK;
87545   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
87546     return SQLITE_ERROR;
87547   }
87548   db->temp_store = (u8)ts;
87549   return SQLITE_OK;
87550 }
87551 #endif /* SQLITE_PAGER_PRAGMAS */
87552
87553 /*
87554 ** Generate code to return a single integer value.
87555 */
87556 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
87557   Vdbe *v = sqlite3GetVdbe(pParse);
87558   int mem = ++pParse->nMem;
87559   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
87560   if( pI64 ){
87561     memcpy(pI64, &value, sizeof(value));
87562   }
87563   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
87564   sqlite3VdbeSetNumCols(v, 1);
87565   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
87566   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
87567 }
87568
87569 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
87570 /*
87571 ** Check to see if zRight and zLeft refer to a pragma that queries
87572 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
87573 ** Also, implement the pragma.
87574 */
87575 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
87576   static const struct sPragmaType {
87577     const char *zName;  /* Name of the pragma */
87578     int mask;           /* Mask for the db->flags value */
87579   } aPragma[] = {
87580     { "full_column_names",        SQLITE_FullColNames  },
87581     { "short_column_names",       SQLITE_ShortColNames },
87582     { "count_changes",            SQLITE_CountRows     },
87583     { "empty_result_callbacks",   SQLITE_NullCallback  },
87584     { "legacy_file_format",       SQLITE_LegacyFileFmt },
87585     { "fullfsync",                SQLITE_FullFSync     },
87586     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
87587     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
87588 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
87589     { "automatic_index",          SQLITE_AutoIndex     },
87590 #endif
87591 #ifdef SQLITE_DEBUG
87592     { "sql_trace",                SQLITE_SqlTrace      },
87593     { "vdbe_listing",             SQLITE_VdbeListing   },
87594     { "vdbe_trace",               SQLITE_VdbeTrace     },
87595 #endif
87596 #ifndef SQLITE_OMIT_CHECK
87597     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
87598 #endif
87599     /* The following is VERY experimental */
87600     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
87601     { "omit_readlock",            SQLITE_NoReadlock    },
87602
87603     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
87604     ** flag if there are any active statements. */
87605     { "read_uncommitted",         SQLITE_ReadUncommitted },
87606     { "recursive_triggers",       SQLITE_RecTriggers },
87607
87608     /* This flag may only be set if both foreign-key and trigger support
87609     ** are present in the build.  */
87610 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87611     { "foreign_keys",             SQLITE_ForeignKeys },
87612 #endif
87613   };
87614   int i;
87615   const struct sPragmaType *p;
87616   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
87617     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
87618       sqlite3 *db = pParse->db;
87619       Vdbe *v;
87620       v = sqlite3GetVdbe(pParse);
87621       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
87622       if( ALWAYS(v) ){
87623         if( zRight==0 ){
87624           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
87625         }else{
87626           int mask = p->mask;          /* Mask of bits to set or clear. */
87627           if( db->autoCommit==0 ){
87628             /* Foreign key support may not be enabled or disabled while not
87629             ** in auto-commit mode.  */
87630             mask &= ~(SQLITE_ForeignKeys);
87631           }
87632
87633           if( getBoolean(zRight) ){
87634             db->flags |= mask;
87635           }else{
87636             db->flags &= ~mask;
87637           }
87638
87639           /* Many of the flag-pragmas modify the code generated by the SQL 
87640           ** compiler (eg. count_changes). So add an opcode to expire all
87641           ** compiled SQL statements after modifying a pragma value.
87642           */
87643           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87644         }
87645       }
87646
87647       return 1;
87648     }
87649   }
87650   return 0;
87651 }
87652 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
87653
87654 /*
87655 ** Return a human-readable name for a constraint resolution action.
87656 */
87657 #ifndef SQLITE_OMIT_FOREIGN_KEY
87658 static const char *actionName(u8 action){
87659   const char *zName;
87660   switch( action ){
87661     case OE_SetNull:  zName = "SET NULL";        break;
87662     case OE_SetDflt:  zName = "SET DEFAULT";     break;
87663     case OE_Cascade:  zName = "CASCADE";         break;
87664     case OE_Restrict: zName = "RESTRICT";        break;
87665     default:          zName = "NO ACTION";  
87666                       assert( action==OE_None ); break;
87667   }
87668   return zName;
87669 }
87670 #endif
87671
87672
87673 /*
87674 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
87675 ** defined in pager.h. This function returns the associated lowercase
87676 ** journal-mode name.
87677 */
87678 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
87679   static char * const azModeName[] = {
87680     "delete", "persist", "off", "truncate", "memory"
87681 #ifndef SQLITE_OMIT_WAL
87682      , "wal"
87683 #endif
87684   };
87685   assert( PAGER_JOURNALMODE_DELETE==0 );
87686   assert( PAGER_JOURNALMODE_PERSIST==1 );
87687   assert( PAGER_JOURNALMODE_OFF==2 );
87688   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
87689   assert( PAGER_JOURNALMODE_MEMORY==4 );
87690   assert( PAGER_JOURNALMODE_WAL==5 );
87691   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
87692
87693   if( eMode==ArraySize(azModeName) ) return 0;
87694   return azModeName[eMode];
87695 }
87696
87697 /*
87698 ** Process a pragma statement.  
87699 **
87700 ** Pragmas are of this form:
87701 **
87702 **      PRAGMA [database.]id [= value]
87703 **
87704 ** The identifier might also be a string.  The value is a string, and
87705 ** identifier, or a number.  If minusFlag is true, then the value is
87706 ** a number that was preceded by a minus sign.
87707 **
87708 ** If the left side is "database.id" then pId1 is the database name
87709 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
87710 ** id and pId2 is any empty string.
87711 */
87712 SQLITE_PRIVATE void sqlite3Pragma(
87713   Parse *pParse, 
87714   Token *pId1,        /* First part of [database.]id field */
87715   Token *pId2,        /* Second part of [database.]id field, or NULL */
87716   Token *pValue,      /* Token for <value>, or NULL */
87717   int minusFlag       /* True if a '-' sign preceded <value> */
87718 ){
87719   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
87720   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
87721   const char *zDb = 0;   /* The database name */
87722   Token *pId;            /* Pointer to <id> token */
87723   int iDb;               /* Database index for <database> */
87724   sqlite3 *db = pParse->db;
87725   Db *pDb;
87726   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
87727   if( v==0 ) return;
87728   sqlite3VdbeRunOnlyOnce(v);
87729   pParse->nMem = 2;
87730
87731   /* Interpret the [database.] part of the pragma statement. iDb is the
87732   ** index of the database this pragma is being applied to in db.aDb[]. */
87733   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
87734   if( iDb<0 ) return;
87735   pDb = &db->aDb[iDb];
87736
87737   /* If the temp database has been explicitly named as part of the 
87738   ** pragma, make sure it is open. 
87739   */
87740   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
87741     return;
87742   }
87743
87744   zLeft = sqlite3NameFromToken(db, pId);
87745   if( !zLeft ) return;
87746   if( minusFlag ){
87747     zRight = sqlite3MPrintf(db, "-%T", pValue);
87748   }else{
87749     zRight = sqlite3NameFromToken(db, pValue);
87750   }
87751
87752   assert( pId2 );
87753   zDb = pId2->n>0 ? pDb->zName : 0;
87754   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
87755     goto pragma_out;
87756   }
87757  
87758 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87759   /*
87760   **  PRAGMA [database.]default_cache_size
87761   **  PRAGMA [database.]default_cache_size=N
87762   **
87763   ** The first form reports the current persistent setting for the
87764   ** page cache size.  The value returned is the maximum number of
87765   ** pages in the page cache.  The second form sets both the current
87766   ** page cache size value and the persistent page cache size value
87767   ** stored in the database file.
87768   **
87769   ** Older versions of SQLite would set the default cache size to a
87770   ** negative number to indicate synchronous=OFF.  These days, synchronous
87771   ** is always on by default regardless of the sign of the default cache
87772   ** size.  But continue to take the absolute value of the default cache
87773   ** size of historical compatibility.
87774   */
87775   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
87776     static const VdbeOpList getCacheSize[] = {
87777       { OP_Transaction, 0, 0,        0},                         /* 0 */
87778       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
87779       { OP_IfPos,       1, 7,        0},
87780       { OP_Integer,     0, 2,        0},
87781       { OP_Subtract,    1, 2,        1},
87782       { OP_IfPos,       1, 7,        0},
87783       { OP_Integer,     0, 1,        0},                         /* 6 */
87784       { OP_ResultRow,   1, 1,        0},
87785     };
87786     int addr;
87787     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87788     sqlite3VdbeUsesBtree(v, iDb);
87789     if( !zRight ){
87790       sqlite3VdbeSetNumCols(v, 1);
87791       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
87792       pParse->nMem += 2;
87793       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
87794       sqlite3VdbeChangeP1(v, addr, iDb);
87795       sqlite3VdbeChangeP1(v, addr+1, iDb);
87796       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
87797     }else{
87798       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
87799       sqlite3BeginWriteOperation(pParse, 0, iDb);
87800       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
87801       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
87802       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87803       pDb->pSchema->cache_size = size;
87804       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
87805     }
87806   }else
87807
87808   /*
87809   **  PRAGMA [database.]page_size
87810   **  PRAGMA [database.]page_size=N
87811   **
87812   ** The first form reports the current setting for the
87813   ** database page size in bytes.  The second form sets the
87814   ** database page size value.  The value can only be set if
87815   ** the database has not yet been created.
87816   */
87817   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
87818     Btree *pBt = pDb->pBt;
87819     assert( pBt!=0 );
87820     if( !zRight ){
87821       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
87822       returnSingleInt(pParse, "page_size", size);
87823     }else{
87824       /* Malloc may fail when setting the page-size, as there is an internal
87825       ** buffer that the pager module resizes using sqlite3_realloc().
87826       */
87827       db->nextPagesize = sqlite3Atoi(zRight);
87828       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
87829         db->mallocFailed = 1;
87830       }
87831     }
87832   }else
87833
87834   /*
87835   **  PRAGMA [database.]secure_delete
87836   **  PRAGMA [database.]secure_delete=ON/OFF
87837   **
87838   ** The first form reports the current setting for the
87839   ** secure_delete flag.  The second form changes the secure_delete
87840   ** flag setting and reports thenew value.
87841   */
87842   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
87843     Btree *pBt = pDb->pBt;
87844     int b = -1;
87845     assert( pBt!=0 );
87846     if( zRight ){
87847       b = getBoolean(zRight);
87848     }
87849     if( pId2->n==0 && b>=0 ){
87850       int ii;
87851       for(ii=0; ii<db->nDb; ii++){
87852         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
87853       }
87854     }
87855     b = sqlite3BtreeSecureDelete(pBt, b);
87856     returnSingleInt(pParse, "secure_delete", b);
87857   }else
87858
87859   /*
87860   **  PRAGMA [database.]max_page_count
87861   **  PRAGMA [database.]max_page_count=N
87862   **
87863   ** The first form reports the current setting for the
87864   ** maximum number of pages in the database file.  The 
87865   ** second form attempts to change this setting.  Both
87866   ** forms return the current setting.
87867   **
87868   **  PRAGMA [database.]page_count
87869   **
87870   ** Return the number of pages in the specified database.
87871   */
87872   if( sqlite3StrICmp(zLeft,"page_count")==0
87873    || sqlite3StrICmp(zLeft,"max_page_count")==0
87874   ){
87875     int iReg;
87876     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87877     sqlite3CodeVerifySchema(pParse, iDb);
87878     iReg = ++pParse->nMem;
87879     if( zLeft[0]=='p' ){
87880       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
87881     }else{
87882       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
87883     }
87884     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
87885     sqlite3VdbeSetNumCols(v, 1);
87886     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
87887   }else
87888
87889   /*
87890   **  PRAGMA [database.]locking_mode
87891   **  PRAGMA [database.]locking_mode = (normal|exclusive)
87892   */
87893   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
87894     const char *zRet = "normal";
87895     int eMode = getLockingMode(zRight);
87896
87897     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
87898       /* Simple "PRAGMA locking_mode;" statement. This is a query for
87899       ** the current default locking mode (which may be different to
87900       ** the locking-mode of the main database).
87901       */
87902       eMode = db->dfltLockMode;
87903     }else{
87904       Pager *pPager;
87905       if( pId2->n==0 ){
87906         /* This indicates that no database name was specified as part
87907         ** of the PRAGMA command. In this case the locking-mode must be
87908         ** set on all attached databases, as well as the main db file.
87909         **
87910         ** Also, the sqlite3.dfltLockMode variable is set so that
87911         ** any subsequently attached databases also use the specified
87912         ** locking mode.
87913         */
87914         int ii;
87915         assert(pDb==&db->aDb[0]);
87916         for(ii=2; ii<db->nDb; ii++){
87917           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
87918           sqlite3PagerLockingMode(pPager, eMode);
87919         }
87920         db->dfltLockMode = (u8)eMode;
87921       }
87922       pPager = sqlite3BtreePager(pDb->pBt);
87923       eMode = sqlite3PagerLockingMode(pPager, eMode);
87924     }
87925
87926     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
87927     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
87928       zRet = "exclusive";
87929     }
87930     sqlite3VdbeSetNumCols(v, 1);
87931     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
87932     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
87933     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
87934   }else
87935
87936   /*
87937   **  PRAGMA [database.]journal_mode
87938   **  PRAGMA [database.]journal_mode =
87939   **                      (delete|persist|off|truncate|memory|wal|off)
87940   */
87941   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
87942     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
87943     int ii;           /* Loop counter */
87944
87945     /* Force the schema to be loaded on all databases.  This cases all
87946     ** database files to be opened and the journal_modes set. */
87947     if( sqlite3ReadSchema(pParse) ){
87948       goto pragma_out;
87949     }
87950
87951     sqlite3VdbeSetNumCols(v, 1);
87952     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
87953
87954     if( zRight==0 ){
87955       /* If there is no "=MODE" part of the pragma, do a query for the
87956       ** current mode */
87957       eMode = PAGER_JOURNALMODE_QUERY;
87958     }else{
87959       const char *zMode;
87960       int n = sqlite3Strlen30(zRight);
87961       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
87962         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
87963       }
87964       if( !zMode ){
87965         /* If the "=MODE" part does not match any known journal mode,
87966         ** then do a query */
87967         eMode = PAGER_JOURNALMODE_QUERY;
87968       }
87969     }
87970     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
87971       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
87972       iDb = 0;
87973       pId2->n = 1;
87974     }
87975     for(ii=db->nDb-1; ii>=0; ii--){
87976       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
87977         sqlite3VdbeUsesBtree(v, ii);
87978         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
87979       }
87980     }
87981     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
87982   }else
87983
87984   /*
87985   **  PRAGMA [database.]journal_size_limit
87986   **  PRAGMA [database.]journal_size_limit=N
87987   **
87988   ** Get or set the size limit on rollback journal files.
87989   */
87990   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
87991     Pager *pPager = sqlite3BtreePager(pDb->pBt);
87992     i64 iLimit = -2;
87993     if( zRight ){
87994       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
87995       if( iLimit<-1 ) iLimit = -1;
87996     }
87997     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
87998     returnSingleInt(pParse, "journal_size_limit", iLimit);
87999   }else
88000
88001 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88002
88003   /*
88004   **  PRAGMA [database.]auto_vacuum
88005   **  PRAGMA [database.]auto_vacuum=N
88006   **
88007   ** Get or set the value of the database 'auto-vacuum' parameter.
88008   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
88009   */
88010 #ifndef SQLITE_OMIT_AUTOVACUUM
88011   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88012     Btree *pBt = pDb->pBt;
88013     assert( pBt!=0 );
88014     if( sqlite3ReadSchema(pParse) ){
88015       goto pragma_out;
88016     }
88017     if( !zRight ){
88018       int auto_vacuum;
88019       if( ALWAYS(pBt) ){
88020          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88021       }else{
88022          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88023       }
88024       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88025     }else{
88026       int eAuto = getAutoVacuum(zRight);
88027       assert( eAuto>=0 && eAuto<=2 );
88028       db->nextAutovac = (u8)eAuto;
88029       if( ALWAYS(eAuto>=0) ){
88030         /* Call SetAutoVacuum() to set initialize the internal auto and
88031         ** incr-vacuum flags. This is required in case this connection
88032         ** creates the database file. It is important that it is created
88033         ** as an auto-vacuum capable db.
88034         */
88035         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88036         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88037           /* When setting the auto_vacuum mode to either "full" or 
88038           ** "incremental", write the value of meta[6] in the database
88039           ** file. Before writing to meta[6], check that meta[3] indicates
88040           ** that this really is an auto-vacuum capable database.
88041           */
88042           static const VdbeOpList setMeta6[] = {
88043             { OP_Transaction,    0,         1,                 0},    /* 0 */
88044             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
88045             { OP_If,             1,         0,                 0},    /* 2 */
88046             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
88047             { OP_Integer,        0,         1,                 0},    /* 4 */
88048             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
88049           };
88050           int iAddr;
88051           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88052           sqlite3VdbeChangeP1(v, iAddr, iDb);
88053           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88054           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88055           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88056           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88057           sqlite3VdbeUsesBtree(v, iDb);
88058         }
88059       }
88060     }
88061   }else
88062 #endif
88063
88064   /*
88065   **  PRAGMA [database.]incremental_vacuum(N)
88066   **
88067   ** Do N steps of incremental vacuuming on a database.
88068   */
88069 #ifndef SQLITE_OMIT_AUTOVACUUM
88070   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88071     int iLimit, addr;
88072     if( sqlite3ReadSchema(pParse) ){
88073       goto pragma_out;
88074     }
88075     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88076       iLimit = 0x7fffffff;
88077     }
88078     sqlite3BeginWriteOperation(pParse, 0, iDb);
88079     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88080     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88081     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88082     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88083     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88084     sqlite3VdbeJumpHere(v, addr);
88085   }else
88086 #endif
88087
88088 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88089   /*
88090   **  PRAGMA [database.]cache_size
88091   **  PRAGMA [database.]cache_size=N
88092   **
88093   ** The first form reports the current local setting for the
88094   ** page cache size.  The local setting can be different from
88095   ** the persistent cache size value that is stored in the database
88096   ** file itself.  The value returned is the maximum number of
88097   ** pages in the page cache.  The second form sets the local
88098   ** page cache size value.  It does not change the persistent
88099   ** cache size stored on the disk so the cache size will revert
88100   ** to its default value when the database is closed and reopened.
88101   ** N should be a positive integer.
88102   */
88103   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88104     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88105     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88106     if( !zRight ){
88107       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88108     }else{
88109       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88110       pDb->pSchema->cache_size = size;
88111       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88112     }
88113   }else
88114
88115   /*
88116   **   PRAGMA temp_store
88117   **   PRAGMA temp_store = "default"|"memory"|"file"
88118   **
88119   ** Return or set the local value of the temp_store flag.  Changing
88120   ** the local value does not make changes to the disk file and the default
88121   ** value will be restored the next time the database is opened.
88122   **
88123   ** Note that it is possible for the library compile-time options to
88124   ** override this setting
88125   */
88126   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88127     if( !zRight ){
88128       returnSingleInt(pParse, "temp_store", db->temp_store);
88129     }else{
88130       changeTempStorage(pParse, zRight);
88131     }
88132   }else
88133
88134   /*
88135   **   PRAGMA temp_store_directory
88136   **   PRAGMA temp_store_directory = ""|"directory_name"
88137   **
88138   ** Return or set the local value of the temp_store_directory flag.  Changing
88139   ** the value sets a specific directory to be used for temporary files.
88140   ** Setting to a null string reverts to the default temporary directory search.
88141   ** If temporary directory is changed, then invalidateTempStorage.
88142   **
88143   */
88144   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88145     if( !zRight ){
88146       if( sqlite3_temp_directory ){
88147         sqlite3VdbeSetNumCols(v, 1);
88148         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88149             "temp_store_directory", SQLITE_STATIC);
88150         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88151         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88152       }
88153     }else{
88154 #ifndef SQLITE_OMIT_WSD
88155       if( zRight[0] ){
88156         int rc;
88157         int res;
88158         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88159         if( rc!=SQLITE_OK || res==0 ){
88160           sqlite3ErrorMsg(pParse, "not a writable directory");
88161           goto pragma_out;
88162         }
88163       }
88164       if( SQLITE_TEMP_STORE==0
88165        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88166        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88167       ){
88168         invalidateTempStorage(pParse);
88169       }
88170       sqlite3_free(sqlite3_temp_directory);
88171       if( zRight[0] ){
88172         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88173       }else{
88174         sqlite3_temp_directory = 0;
88175       }
88176 #endif /* SQLITE_OMIT_WSD */
88177     }
88178   }else
88179
88180 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88181 #  if defined(__APPLE__)
88182 #    define SQLITE_ENABLE_LOCKING_STYLE 1
88183 #  else
88184 #    define SQLITE_ENABLE_LOCKING_STYLE 0
88185 #  endif
88186 #endif
88187 #if SQLITE_ENABLE_LOCKING_STYLE
88188   /*
88189    **   PRAGMA [database.]lock_proxy_file
88190    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88191    **
88192    ** Return or set the value of the lock_proxy_file flag.  Changing
88193    ** the value sets a specific file to be used for database access locks.
88194    **
88195    */
88196   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88197     if( !zRight ){
88198       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88199       char *proxy_file_path = NULL;
88200       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88201       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
88202                            &proxy_file_path);
88203       
88204       if( proxy_file_path ){
88205         sqlite3VdbeSetNumCols(v, 1);
88206         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88207                               "lock_proxy_file", SQLITE_STATIC);
88208         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88209         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88210       }
88211     }else{
88212       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88213       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88214       int res;
88215       if( zRight[0] ){
88216         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88217                                      zRight);
88218       } else {
88219         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88220                                      NULL);
88221       }
88222       if( res!=SQLITE_OK ){
88223         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88224         goto pragma_out;
88225       }
88226     }
88227   }else
88228 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
88229     
88230   /*
88231   **   PRAGMA [database.]synchronous
88232   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88233   **
88234   ** Return or set the local value of the synchronous flag.  Changing
88235   ** the local value does not make changes to the disk file and the
88236   ** default value will be restored the next time the database is
88237   ** opened.
88238   */
88239   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88240     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88241     if( !zRight ){
88242       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88243     }else{
88244       if( !db->autoCommit ){
88245         sqlite3ErrorMsg(pParse, 
88246             "Safety level may not be changed inside a transaction");
88247       }else{
88248         pDb->safety_level = getSafetyLevel(zRight)+1;
88249       }
88250     }
88251   }else
88252 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88253
88254 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88255   if( flagPragma(pParse, zLeft, zRight) ){
88256     /* The flagPragma() subroutine also generates any necessary code
88257     ** there is nothing more to do here */
88258   }else
88259 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88260
88261 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88262   /*
88263   **   PRAGMA table_info(<table>)
88264   **
88265   ** Return a single row for each column of the named table. The columns of
88266   ** the returned data set are:
88267   **
88268   ** cid:        Column id (numbered from left to right, starting at 0)
88269   ** name:       Column name
88270   ** type:       Column declaration type.
88271   ** notnull:    True if 'NOT NULL' is part of column declaration
88272   ** dflt_value: The default value for the column, if any.
88273   */
88274   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88275     Table *pTab;
88276     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88277     pTab = sqlite3FindTable(db, zRight, zDb);
88278     if( pTab ){
88279       int i;
88280       int nHidden = 0;
88281       Column *pCol;
88282       sqlite3VdbeSetNumCols(v, 6);
88283       pParse->nMem = 6;
88284       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88285       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88286       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88287       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88288       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88289       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88290       sqlite3ViewGetColumnNames(pParse, pTab);
88291       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88292         if( IsHiddenColumn(pCol) ){
88293           nHidden++;
88294           continue;
88295         }
88296         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88297         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88298         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88299            pCol->zType ? pCol->zType : "", 0);
88300         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88301         if( pCol->zDflt ){
88302           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88303         }else{
88304           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88305         }
88306         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88307         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88308       }
88309     }
88310   }else
88311
88312   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88313     Index *pIdx;
88314     Table *pTab;
88315     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88316     pIdx = sqlite3FindIndex(db, zRight, zDb);
88317     if( pIdx ){
88318       int i;
88319       pTab = pIdx->pTable;
88320       sqlite3VdbeSetNumCols(v, 3);
88321       pParse->nMem = 3;
88322       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88323       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88324       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88325       for(i=0; i<pIdx->nColumn; i++){
88326         int cnum = pIdx->aiColumn[i];
88327         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88328         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88329         assert( pTab->nCol>cnum );
88330         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
88331         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88332       }
88333     }
88334   }else
88335
88336   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
88337     Index *pIdx;
88338     Table *pTab;
88339     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88340     pTab = sqlite3FindTable(db, zRight, zDb);
88341     if( pTab ){
88342       v = sqlite3GetVdbe(pParse);
88343       pIdx = pTab->pIndex;
88344       if( pIdx ){
88345         int i = 0; 
88346         sqlite3VdbeSetNumCols(v, 3);
88347         pParse->nMem = 3;
88348         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88349         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88350         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
88351         while(pIdx){
88352           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88353           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
88354           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
88355           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88356           ++i;
88357           pIdx = pIdx->pNext;
88358         }
88359       }
88360     }
88361   }else
88362
88363   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
88364     int i;
88365     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88366     sqlite3VdbeSetNumCols(v, 3);
88367     pParse->nMem = 3;
88368     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88369     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88370     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
88371     for(i=0; i<db->nDb; i++){
88372       if( db->aDb[i].pBt==0 ) continue;
88373       assert( db->aDb[i].zName!=0 );
88374       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88375       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
88376       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88377            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
88378       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88379     }
88380   }else
88381
88382   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
88383     int i = 0;
88384     HashElem *p;
88385     sqlite3VdbeSetNumCols(v, 2);
88386     pParse->nMem = 2;
88387     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88388     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88389     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
88390       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
88391       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
88392       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
88393       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88394     }
88395   }else
88396 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
88397
88398 #ifndef SQLITE_OMIT_FOREIGN_KEY
88399   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
88400     FKey *pFK;
88401     Table *pTab;
88402     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88403     pTab = sqlite3FindTable(db, zRight, zDb);
88404     if( pTab ){
88405       v = sqlite3GetVdbe(pParse);
88406       pFK = pTab->pFKey;
88407       if( pFK ){
88408         int i = 0; 
88409         sqlite3VdbeSetNumCols(v, 8);
88410         pParse->nMem = 8;
88411         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
88412         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
88413         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
88414         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
88415         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
88416         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
88417         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
88418         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
88419         while(pFK){
88420           int j;
88421           for(j=0; j<pFK->nCol; j++){
88422             char *zCol = pFK->aCol[j].zCol;
88423             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
88424             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
88425             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88426             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
88427             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
88428             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
88429                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
88430             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
88431             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
88432             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
88433             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
88434             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
88435           }
88436           ++i;
88437           pFK = pFK->pNextFrom;
88438         }
88439       }
88440     }
88441   }else
88442 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
88443
88444 #ifndef NDEBUG
88445   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
88446     if( zRight ){
88447       if( getBoolean(zRight) ){
88448         sqlite3ParserTrace(stderr, "parser: ");
88449       }else{
88450         sqlite3ParserTrace(0, 0);
88451       }
88452     }
88453   }else
88454 #endif
88455
88456   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
88457   ** used will be case sensitive or not depending on the RHS.
88458   */
88459   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
88460     if( zRight ){
88461       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
88462     }
88463   }else
88464
88465 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
88466 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
88467 #endif
88468
88469 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
88470   /* Pragma "quick_check" is an experimental reduced version of 
88471   ** integrity_check designed to detect most database corruption
88472   ** without most of the overhead of a full integrity-check.
88473   */
88474   if( sqlite3StrICmp(zLeft, "integrity_check")==0
88475    || sqlite3StrICmp(zLeft, "quick_check")==0 
88476   ){
88477     int i, j, addr, mxErr;
88478
88479     /* Code that appears at the end of the integrity check.  If no error
88480     ** messages have been generated, output OK.  Otherwise output the
88481     ** error message
88482     */
88483     static const VdbeOpList endCode[] = {
88484       { OP_AddImm,      1, 0,        0},    /* 0 */
88485       { OP_IfNeg,       1, 0,        0},    /* 1 */
88486       { OP_String8,     0, 3,        0},    /* 2 */
88487       { OP_ResultRow,   3, 1,        0},
88488     };
88489
88490     int isQuick = (zLeft[0]=='q');
88491
88492     /* Initialize the VDBE program */
88493     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88494     pParse->nMem = 6;
88495     sqlite3VdbeSetNumCols(v, 1);
88496     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
88497
88498     /* Set the maximum error count */
88499     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88500     if( zRight ){
88501       sqlite3GetInt32(zRight, &mxErr);
88502       if( mxErr<=0 ){
88503         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88504       }
88505     }
88506     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
88507
88508     /* Do an integrity check on each database file */
88509     for(i=0; i<db->nDb; i++){
88510       HashElem *x;
88511       Hash *pTbls;
88512       int cnt = 0;
88513
88514       if( OMIT_TEMPDB && i==1 ) continue;
88515
88516       sqlite3CodeVerifySchema(pParse, i);
88517       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
88518       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88519       sqlite3VdbeJumpHere(v, addr);
88520
88521       /* Do an integrity check of the B-Tree
88522       **
88523       ** Begin by filling registers 2, 3, ... with the root pages numbers
88524       ** for all tables and indices in the database.
88525       */
88526       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88527       pTbls = &db->aDb[i].pSchema->tblHash;
88528       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
88529         Table *pTab = sqliteHashData(x);
88530         Index *pIdx;
88531         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
88532         cnt++;
88533         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88534           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
88535           cnt++;
88536         }
88537       }
88538
88539       /* Make sure sufficient number of registers have been allocated */
88540       if( pParse->nMem < cnt+4 ){
88541         pParse->nMem = cnt+4;
88542       }
88543
88544       /* Do the b-tree integrity checks */
88545       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
88546       sqlite3VdbeChangeP5(v, (u8)i);
88547       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
88548       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88549          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
88550          P4_DYNAMIC);
88551       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
88552       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
88553       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
88554       sqlite3VdbeJumpHere(v, addr);
88555
88556       /* Make sure all the indices are constructed correctly.
88557       */
88558       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
88559         Table *pTab = sqliteHashData(x);
88560         Index *pIdx;
88561         int loopTop;
88562
88563         if( pTab->pIndex==0 ) continue;
88564         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
88565         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88566         sqlite3VdbeJumpHere(v, addr);
88567         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
88568         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
88569         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
88570         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
88571         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88572           int jmp2;
88573           int r1;
88574           static const VdbeOpList idxErr[] = {
88575             { OP_AddImm,      1, -1,  0},
88576             { OP_String8,     0,  3,  0},    /* 1 */
88577             { OP_Rowid,       1,  4,  0},
88578             { OP_String8,     0,  5,  0},    /* 3 */
88579             { OP_String8,     0,  6,  0},    /* 4 */
88580             { OP_Concat,      4,  3,  3},
88581             { OP_Concat,      5,  3,  3},
88582             { OP_Concat,      6,  3,  3},
88583             { OP_ResultRow,   3,  1,  0},
88584             { OP_IfPos,       1,  0,  0},    /* 9 */
88585             { OP_Halt,        0,  0,  0},
88586           };
88587           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
88588           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
88589           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
88590           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
88591           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
88592           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
88593           sqlite3VdbeJumpHere(v, addr+9);
88594           sqlite3VdbeJumpHere(v, jmp2);
88595         }
88596         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
88597         sqlite3VdbeJumpHere(v, loopTop);
88598         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88599           static const VdbeOpList cntIdx[] = {
88600              { OP_Integer,      0,  3,  0},
88601              { OP_Rewind,       0,  0,  0},  /* 1 */
88602              { OP_AddImm,       3,  1,  0},
88603              { OP_Next,         0,  0,  0},  /* 3 */
88604              { OP_Eq,           2,  0,  3},  /* 4 */
88605              { OP_AddImm,       1, -1,  0},
88606              { OP_String8,      0,  2,  0},  /* 6 */
88607              { OP_String8,      0,  3,  0},  /* 7 */
88608              { OP_Concat,       3,  2,  2},
88609              { OP_ResultRow,    2,  1,  0},
88610           };
88611           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
88612           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88613           sqlite3VdbeJumpHere(v, addr);
88614           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
88615           sqlite3VdbeChangeP1(v, addr+1, j+2);
88616           sqlite3VdbeChangeP2(v, addr+1, addr+4);
88617           sqlite3VdbeChangeP1(v, addr+3, j+2);
88618           sqlite3VdbeChangeP2(v, addr+3, addr+2);
88619           sqlite3VdbeJumpHere(v, addr+4);
88620           sqlite3VdbeChangeP4(v, addr+6, 
88621                      "wrong # of entries in index ", P4_STATIC);
88622           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
88623         }
88624       } 
88625     }
88626     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
88627     sqlite3VdbeChangeP2(v, addr, -mxErr);
88628     sqlite3VdbeJumpHere(v, addr+1);
88629     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
88630   }else
88631 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
88632
88633 #ifndef SQLITE_OMIT_UTF16
88634   /*
88635   **   PRAGMA encoding
88636   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
88637   **
88638   ** In its first form, this pragma returns the encoding of the main
88639   ** database. If the database is not initialized, it is initialized now.
88640   **
88641   ** The second form of this pragma is a no-op if the main database file
88642   ** has not already been initialized. In this case it sets the default
88643   ** encoding that will be used for the main database file if a new file
88644   ** is created. If an existing main database file is opened, then the
88645   ** default text encoding for the existing database is used.
88646   ** 
88647   ** In all cases new databases created using the ATTACH command are
88648   ** created to use the same default text encoding as the main database. If
88649   ** the main database has not been initialized and/or created when ATTACH
88650   ** is executed, this is done before the ATTACH operation.
88651   **
88652   ** In the second form this pragma sets the text encoding to be used in
88653   ** new database files created using this database handle. It is only
88654   ** useful if invoked immediately after the main database i
88655   */
88656   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
88657     static const struct EncName {
88658       char *zName;
88659       u8 enc;
88660     } encnames[] = {
88661       { "UTF8",     SQLITE_UTF8        },
88662       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
88663       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
88664       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
88665       { "UTF16le",  SQLITE_UTF16LE     },
88666       { "UTF16be",  SQLITE_UTF16BE     },
88667       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
88668       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
88669       { 0, 0 }
88670     };
88671     const struct EncName *pEnc;
88672     if( !zRight ){    /* "PRAGMA encoding" */
88673       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88674       sqlite3VdbeSetNumCols(v, 1);
88675       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
88676       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
88677       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
88678       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
88679       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
88680       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
88681       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88682     }else{                        /* "PRAGMA encoding = XXX" */
88683       /* Only change the value of sqlite.enc if the database handle is not
88684       ** initialized. If the main database exists, the new sqlite.enc value
88685       ** will be overwritten when the schema is next loaded. If it does not
88686       ** already exists, it will be created to use the new encoding value.
88687       */
88688       if( 
88689         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
88690         DbHasProperty(db, 0, DB_Empty) 
88691       ){
88692         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
88693           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
88694             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
88695             break;
88696           }
88697         }
88698         if( !pEnc->zName ){
88699           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
88700         }
88701       }
88702     }
88703   }else
88704 #endif /* SQLITE_OMIT_UTF16 */
88705
88706 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
88707   /*
88708   **   PRAGMA [database.]schema_version
88709   **   PRAGMA [database.]schema_version = <integer>
88710   **
88711   **   PRAGMA [database.]user_version
88712   **   PRAGMA [database.]user_version = <integer>
88713   **
88714   ** The pragma's schema_version and user_version are used to set or get
88715   ** the value of the schema-version and user-version, respectively. Both
88716   ** the schema-version and the user-version are 32-bit signed integers
88717   ** stored in the database header.
88718   **
88719   ** The schema-cookie is usually only manipulated internally by SQLite. It
88720   ** is incremented by SQLite whenever the database schema is modified (by
88721   ** creating or dropping a table or index). The schema version is used by
88722   ** SQLite each time a query is executed to ensure that the internal cache
88723   ** of the schema used when compiling the SQL query matches the schema of
88724   ** the database against which the compiled query is actually executed.
88725   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
88726   ** the schema-version is potentially dangerous and may lead to program
88727   ** crashes or database corruption. Use with caution!
88728   **
88729   ** The user-version is not used internally by SQLite. It may be used by
88730   ** applications for any purpose.
88731   */
88732   if( sqlite3StrICmp(zLeft, "schema_version")==0 
88733    || sqlite3StrICmp(zLeft, "user_version")==0 
88734    || sqlite3StrICmp(zLeft, "freelist_count")==0 
88735   ){
88736     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
88737     sqlite3VdbeUsesBtree(v, iDb);
88738     switch( zLeft[0] ){
88739       case 'f': case 'F':
88740         iCookie = BTREE_FREE_PAGE_COUNT;
88741         break;
88742       case 's': case 'S':
88743         iCookie = BTREE_SCHEMA_VERSION;
88744         break;
88745       default:
88746         iCookie = BTREE_USER_VERSION;
88747         break;
88748     }
88749
88750     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
88751       /* Write the specified cookie value */
88752       static const VdbeOpList setCookie[] = {
88753         { OP_Transaction,    0,  1,  0},    /* 0 */
88754         { OP_Integer,        0,  1,  0},    /* 1 */
88755         { OP_SetCookie,      0,  0,  1},    /* 2 */
88756       };
88757       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
88758       sqlite3VdbeChangeP1(v, addr, iDb);
88759       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
88760       sqlite3VdbeChangeP1(v, addr+2, iDb);
88761       sqlite3VdbeChangeP2(v, addr+2, iCookie);
88762     }else{
88763       /* Read the specified cookie value */
88764       static const VdbeOpList readCookie[] = {
88765         { OP_Transaction,     0,  0,  0},    /* 0 */
88766         { OP_ReadCookie,      0,  1,  0},    /* 1 */
88767         { OP_ResultRow,       1,  1,  0}
88768       };
88769       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
88770       sqlite3VdbeChangeP1(v, addr, iDb);
88771       sqlite3VdbeChangeP1(v, addr+1, iDb);
88772       sqlite3VdbeChangeP3(v, addr+1, iCookie);
88773       sqlite3VdbeSetNumCols(v, 1);
88774       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88775     }
88776   }else
88777 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
88778
88779 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88780   /*
88781   **   PRAGMA compile_options
88782   **
88783   ** Return the names of all compile-time options used in this build,
88784   ** one option per row.
88785   */
88786   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
88787     int i = 0;
88788     const char *zOpt;
88789     sqlite3VdbeSetNumCols(v, 1);
88790     pParse->nMem = 1;
88791     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
88792     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
88793       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
88794       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88795     }
88796   }else
88797 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88798
88799 #ifndef SQLITE_OMIT_WAL
88800   /*
88801   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
88802   **
88803   ** Checkpoint the database.
88804   */
88805   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
88806     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
88807     int eMode = SQLITE_CHECKPOINT_PASSIVE;
88808     if( zRight ){
88809       if( sqlite3StrICmp(zRight, "full")==0 ){
88810         eMode = SQLITE_CHECKPOINT_FULL;
88811       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
88812         eMode = SQLITE_CHECKPOINT_RESTART;
88813       }
88814     }
88815     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88816     sqlite3VdbeSetNumCols(v, 3);
88817     pParse->nMem = 3;
88818     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
88819     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
88820     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
88821
88822     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
88823     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88824   }else
88825
88826   /*
88827   **   PRAGMA wal_autocheckpoint
88828   **   PRAGMA wal_autocheckpoint = N
88829   **
88830   ** Configure a database connection to automatically checkpoint a database
88831   ** after accumulating N frames in the log. Or query for the current value
88832   ** of N.
88833   */
88834   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
88835     if( zRight ){
88836       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
88837     }
88838     returnSingleInt(pParse, "wal_autocheckpoint", 
88839        db->xWalCallback==sqlite3WalDefaultHook ? 
88840            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
88841   }else
88842 #endif
88843
88844 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
88845   /*
88846   ** Report the current state of file logs for all databases
88847   */
88848   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
88849     static const char *const azLockName[] = {
88850       "unlocked", "shared", "reserved", "pending", "exclusive"
88851     };
88852     int i;
88853     sqlite3VdbeSetNumCols(v, 2);
88854     pParse->nMem = 2;
88855     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
88856     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
88857     for(i=0; i<db->nDb; i++){
88858       Btree *pBt;
88859       Pager *pPager;
88860       const char *zState = "unknown";
88861       int j;
88862       if( db->aDb[i].zName==0 ) continue;
88863       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
88864       pBt = db->aDb[i].pBt;
88865       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
88866         zState = "closed";
88867       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
88868                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
88869          zState = azLockName[j];
88870       }
88871       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
88872       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88873     }
88874
88875   }else
88876 #endif
88877
88878 #ifdef SQLITE_HAS_CODEC
88879   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
88880     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
88881   }else
88882   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
88883     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
88884   }else
88885   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
88886                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
88887     int i, h1, h2;
88888     char zKey[40];
88889     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
88890       h1 += 9*(1&(h1>>6));
88891       h2 += 9*(1&(h2>>6));
88892       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
88893     }
88894     if( (zLeft[3] & 0xf)==0xb ){
88895       sqlite3_key(db, zKey, i/2);
88896     }else{
88897       sqlite3_rekey(db, zKey, i/2);
88898     }
88899   }else
88900 #endif
88901 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
88902   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
88903 #ifdef SQLITE_HAS_CODEC
88904     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
88905       sqlite3_activate_see(&zRight[4]);
88906     }
88907 #endif
88908 #ifdef SQLITE_ENABLE_CEROD
88909     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
88910       sqlite3_activate_cerod(&zRight[6]);
88911     }
88912 #endif
88913   }else
88914 #endif
88915
88916  
88917   {/* Empty ELSE clause */}
88918
88919   /*
88920   ** Reset the safety level, in case the fullfsync flag or synchronous
88921   ** setting changed.
88922   */
88923 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88924   if( db->autoCommit ){
88925     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
88926                (db->flags&SQLITE_FullFSync)!=0,
88927                (db->flags&SQLITE_CkptFullFSync)!=0);
88928   }
88929 #endif
88930 pragma_out:
88931   sqlite3DbFree(db, zLeft);
88932   sqlite3DbFree(db, zRight);
88933 }
88934
88935 #endif /* SQLITE_OMIT_PRAGMA */
88936
88937 /************** End of pragma.c **********************************************/
88938 /************** Begin file prepare.c *****************************************/
88939 /*
88940 ** 2005 May 25
88941 **
88942 ** The author disclaims copyright to this source code.  In place of
88943 ** a legal notice, here is a blessing:
88944 **
88945 **    May you do good and not evil.
88946 **    May you find forgiveness for yourself and forgive others.
88947 **    May you share freely, never taking more than you give.
88948 **
88949 *************************************************************************
88950 ** This file contains the implementation of the sqlite3_prepare()
88951 ** interface, and routines that contribute to loading the database schema
88952 ** from disk.
88953 */
88954
88955 /*
88956 ** Fill the InitData structure with an error message that indicates
88957 ** that the database is corrupt.
88958 */
88959 static void corruptSchema(
88960   InitData *pData,     /* Initialization context */
88961   const char *zObj,    /* Object being parsed at the point of error */
88962   const char *zExtra   /* Error information */
88963 ){
88964   sqlite3 *db = pData->db;
88965   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
88966     if( zObj==0 ) zObj = "?";
88967     sqlite3SetString(pData->pzErrMsg, db,
88968       "malformed database schema (%s)", zObj);
88969     if( zExtra ){
88970       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
88971                                  "%s - %s", *pData->pzErrMsg, zExtra);
88972     }
88973   }
88974   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
88975 }
88976
88977 /*
88978 ** This is the callback routine for the code that initializes the
88979 ** database.  See sqlite3Init() below for additional information.
88980 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
88981 **
88982 ** Each callback contains the following information:
88983 **
88984 **     argv[0] = name of thing being created
88985 **     argv[1] = root page number for table or index. 0 for trigger or view.
88986 **     argv[2] = SQL text for the CREATE statement.
88987 **
88988 */
88989 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
88990   InitData *pData = (InitData*)pInit;
88991   sqlite3 *db = pData->db;
88992   int iDb = pData->iDb;
88993
88994   assert( argc==3 );
88995   UNUSED_PARAMETER2(NotUsed, argc);
88996   assert( sqlite3_mutex_held(db->mutex) );
88997   DbClearProperty(db, iDb, DB_Empty);
88998   if( db->mallocFailed ){
88999     corruptSchema(pData, argv[0], 0);
89000     return 1;
89001   }
89002
89003   assert( iDb>=0 && iDb<db->nDb );
89004   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
89005   if( argv[1]==0 ){
89006     corruptSchema(pData, argv[0], 0);
89007   }else if( argv[2] && argv[2][0] ){
89008     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
89009     ** But because db->init.busy is set to 1, no VDBE code is generated
89010     ** or executed.  All the parser does is build the internal data
89011     ** structures that describe the table, index, or view.
89012     */
89013     int rc;
89014     sqlite3_stmt *pStmt;
89015     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
89016
89017     assert( db->init.busy );
89018     db->init.iDb = iDb;
89019     db->init.newTnum = sqlite3Atoi(argv[1]);
89020     db->init.orphanTrigger = 0;
89021     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89022     rc = db->errCode;
89023     assert( (rc&0xFF)==(rcp&0xFF) );
89024     db->init.iDb = 0;
89025     if( SQLITE_OK!=rc ){
89026       if( db->init.orphanTrigger ){
89027         assert( iDb==1 );
89028       }else{
89029         pData->rc = rc;
89030         if( rc==SQLITE_NOMEM ){
89031           db->mallocFailed = 1;
89032         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89033           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89034         }
89035       }
89036     }
89037     sqlite3_finalize(pStmt);
89038   }else if( argv[0]==0 ){
89039     corruptSchema(pData, 0, 0);
89040   }else{
89041     /* If the SQL column is blank it means this is an index that
89042     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89043     ** constraint for a CREATE TABLE.  The index should have already
89044     ** been created when we processed the CREATE TABLE.  All we have
89045     ** to do here is record the root page number for that index.
89046     */
89047     Index *pIndex;
89048     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89049     if( pIndex==0 ){
89050       /* This can occur if there exists an index on a TEMP table which
89051       ** has the same name as another index on a permanent index.  Since
89052       ** the permanent table is hidden by the TEMP table, we can also
89053       ** safely ignore the index on the permanent table.
89054       */
89055       /* Do Nothing */;
89056     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89057       corruptSchema(pData, argv[0], "invalid rootpage");
89058     }
89059   }
89060   return 0;
89061 }
89062
89063 /*
89064 ** Attempt to read the database schema and initialize internal
89065 ** data structures for a single database file.  The index of the
89066 ** database file is given by iDb.  iDb==0 is used for the main
89067 ** database.  iDb==1 should never be used.  iDb>=2 is used for
89068 ** auxiliary databases.  Return one of the SQLITE_ error codes to
89069 ** indicate success or failure.
89070 */
89071 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89072   int rc;
89073   int i;
89074   int size;
89075   Table *pTab;
89076   Db *pDb;
89077   char const *azArg[4];
89078   int meta[5];
89079   InitData initData;
89080   char const *zMasterSchema;
89081   char const *zMasterName;
89082   int openedTransaction = 0;
89083
89084   /*
89085   ** The master database table has a structure like this
89086   */
89087   static const char master_schema[] = 
89088      "CREATE TABLE sqlite_master(\n"
89089      "  type text,\n"
89090      "  name text,\n"
89091      "  tbl_name text,\n"
89092      "  rootpage integer,\n"
89093      "  sql text\n"
89094      ")"
89095   ;
89096 #ifndef SQLITE_OMIT_TEMPDB
89097   static const char temp_master_schema[] = 
89098      "CREATE TEMP TABLE sqlite_temp_master(\n"
89099      "  type text,\n"
89100      "  name text,\n"
89101      "  tbl_name text,\n"
89102      "  rootpage integer,\n"
89103      "  sql text\n"
89104      ")"
89105   ;
89106 #else
89107   #define temp_master_schema 0
89108 #endif
89109
89110   assert( iDb>=0 && iDb<db->nDb );
89111   assert( db->aDb[iDb].pSchema );
89112   assert( sqlite3_mutex_held(db->mutex) );
89113   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89114
89115   /* zMasterSchema and zInitScript are set to point at the master schema
89116   ** and initialisation script appropriate for the database being
89117   ** initialised. zMasterName is the name of the master table.
89118   */
89119   if( !OMIT_TEMPDB && iDb==1 ){
89120     zMasterSchema = temp_master_schema;
89121   }else{
89122     zMasterSchema = master_schema;
89123   }
89124   zMasterName = SCHEMA_TABLE(iDb);
89125
89126   /* Construct the schema tables.  */
89127   azArg[0] = zMasterName;
89128   azArg[1] = "1";
89129   azArg[2] = zMasterSchema;
89130   azArg[3] = 0;
89131   initData.db = db;
89132   initData.iDb = iDb;
89133   initData.rc = SQLITE_OK;
89134   initData.pzErrMsg = pzErrMsg;
89135   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89136   if( initData.rc ){
89137     rc = initData.rc;
89138     goto error_out;
89139   }
89140   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89141   if( ALWAYS(pTab) ){
89142     pTab->tabFlags |= TF_Readonly;
89143   }
89144
89145   /* Create a cursor to hold the database open
89146   */
89147   pDb = &db->aDb[iDb];
89148   if( pDb->pBt==0 ){
89149     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89150       DbSetProperty(db, 1, DB_SchemaLoaded);
89151     }
89152     return SQLITE_OK;
89153   }
89154
89155   /* If there is not already a read-only (or read-write) transaction opened
89156   ** on the b-tree database, open one now. If a transaction is opened, it 
89157   ** will be closed before this function returns.  */
89158   sqlite3BtreeEnter(pDb->pBt);
89159   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89160     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89161     if( rc!=SQLITE_OK ){
89162       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89163       goto initone_error_out;
89164     }
89165     openedTransaction = 1;
89166   }
89167
89168   /* Get the database meta information.
89169   **
89170   ** Meta values are as follows:
89171   **    meta[0]   Schema cookie.  Changes with each schema change.
89172   **    meta[1]   File format of schema layer.
89173   **    meta[2]   Size of the page cache.
89174   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
89175   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89176   **    meta[5]   User version
89177   **    meta[6]   Incremental vacuum mode
89178   **    meta[7]   unused
89179   **    meta[8]   unused
89180   **    meta[9]   unused
89181   **
89182   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89183   ** the possible values of meta[4].
89184   */
89185   for(i=0; i<ArraySize(meta); i++){
89186     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89187   }
89188   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89189
89190   /* If opening a non-empty database, check the text encoding. For the
89191   ** main database, set sqlite3.enc to the encoding of the main database.
89192   ** For an attached db, it is an error if the encoding is not the same
89193   ** as sqlite3.enc.
89194   */
89195   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
89196     if( iDb==0 ){
89197       u8 encoding;
89198       /* If opening the main database, set ENC(db). */
89199       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89200       if( encoding==0 ) encoding = SQLITE_UTF8;
89201       ENC(db) = encoding;
89202       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89203     }else{
89204       /* If opening an attached database, the encoding much match ENC(db) */
89205       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89206         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89207             " text encoding as main database");
89208         rc = SQLITE_ERROR;
89209         goto initone_error_out;
89210       }
89211     }
89212   }else{
89213     DbSetProperty(db, iDb, DB_Empty);
89214   }
89215   pDb->pSchema->enc = ENC(db);
89216
89217   if( pDb->pSchema->cache_size==0 ){
89218     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89219     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89220     pDb->pSchema->cache_size = size;
89221     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89222   }
89223
89224   /*
89225   ** file_format==1    Version 3.0.0.
89226   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
89227   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
89228   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
89229   */
89230   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89231   if( pDb->pSchema->file_format==0 ){
89232     pDb->pSchema->file_format = 1;
89233   }
89234   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89235     sqlite3SetString(pzErrMsg, db, "unsupported file format");
89236     rc = SQLITE_ERROR;
89237     goto initone_error_out;
89238   }
89239
89240   /* Ticket #2804:  When we open a database in the newer file format,
89241   ** clear the legacy_file_format pragma flag so that a VACUUM will
89242   ** not downgrade the database and thus invalidate any descending
89243   ** indices that the user might have created.
89244   */
89245   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89246     db->flags &= ~SQLITE_LegacyFileFmt;
89247   }
89248
89249   /* Read the schema information out of the schema tables
89250   */
89251   assert( db->init.busy );
89252   {
89253     char *zSql;
89254     zSql = sqlite3MPrintf(db, 
89255         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89256         db->aDb[iDb].zName, zMasterName);
89257 #ifndef SQLITE_OMIT_AUTHORIZATION
89258     {
89259       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89260       xAuth = db->xAuth;
89261       db->xAuth = 0;
89262 #endif
89263       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89264 #ifndef SQLITE_OMIT_AUTHORIZATION
89265       db->xAuth = xAuth;
89266     }
89267 #endif
89268     if( rc==SQLITE_OK ) rc = initData.rc;
89269     sqlite3DbFree(db, zSql);
89270 #ifndef SQLITE_OMIT_ANALYZE
89271     if( rc==SQLITE_OK ){
89272       sqlite3AnalysisLoad(db, iDb);
89273     }
89274 #endif
89275   }
89276   if( db->mallocFailed ){
89277     rc = SQLITE_NOMEM;
89278     sqlite3ResetInternalSchema(db, -1);
89279   }
89280   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89281     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89282     ** the schema loaded, even if errors occurred. In this situation the 
89283     ** current sqlite3_prepare() operation will fail, but the following one
89284     ** will attempt to compile the supplied statement against whatever subset
89285     ** of the schema was loaded before the error occurred. The primary
89286     ** purpose of this is to allow access to the sqlite_master table
89287     ** even when its contents have been corrupted.
89288     */
89289     DbSetProperty(db, iDb, DB_SchemaLoaded);
89290     rc = SQLITE_OK;
89291   }
89292
89293   /* Jump here for an error that occurs after successfully allocating
89294   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89295   ** before that point, jump to error_out.
89296   */
89297 initone_error_out:
89298   if( openedTransaction ){
89299     sqlite3BtreeCommit(pDb->pBt);
89300   }
89301   sqlite3BtreeLeave(pDb->pBt);
89302
89303 error_out:
89304   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89305     db->mallocFailed = 1;
89306   }
89307   return rc;
89308 }
89309
89310 /*
89311 ** Initialize all database files - the main database file, the file
89312 ** used to store temporary tables, and any additional database files
89313 ** created using ATTACH statements.  Return a success code.  If an
89314 ** error occurs, write an error message into *pzErrMsg.
89315 **
89316 ** After a database is initialized, the DB_SchemaLoaded bit is set
89317 ** bit is set in the flags field of the Db structure. If the database
89318 ** file was of zero-length, then the DB_Empty flag is also set.
89319 */
89320 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89321   int i, rc;
89322   int commit_internal = !(db->flags&SQLITE_InternChanges);
89323   
89324   assert( sqlite3_mutex_held(db->mutex) );
89325   rc = SQLITE_OK;
89326   db->init.busy = 1;
89327   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89328     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89329     rc = sqlite3InitOne(db, i, pzErrMsg);
89330     if( rc ){
89331       sqlite3ResetInternalSchema(db, i);
89332     }
89333   }
89334
89335   /* Once all the other databases have been initialised, load the schema
89336   ** for the TEMP database. This is loaded last, as the TEMP database
89337   ** schema may contain references to objects in other databases.
89338   */
89339 #ifndef SQLITE_OMIT_TEMPDB
89340   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
89341                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
89342     rc = sqlite3InitOne(db, 1, pzErrMsg);
89343     if( rc ){
89344       sqlite3ResetInternalSchema(db, 1);
89345     }
89346   }
89347 #endif
89348
89349   db->init.busy = 0;
89350   if( rc==SQLITE_OK && commit_internal ){
89351     sqlite3CommitInternalChanges(db);
89352   }
89353
89354   return rc; 
89355 }
89356
89357 /*
89358 ** This routine is a no-op if the database schema is already initialised.
89359 ** Otherwise, the schema is loaded. An error code is returned.
89360 */
89361 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
89362   int rc = SQLITE_OK;
89363   sqlite3 *db = pParse->db;
89364   assert( sqlite3_mutex_held(db->mutex) );
89365   if( !db->init.busy ){
89366     rc = sqlite3Init(db, &pParse->zErrMsg);
89367   }
89368   if( rc!=SQLITE_OK ){
89369     pParse->rc = rc;
89370     pParse->nErr++;
89371   }
89372   return rc;
89373 }
89374
89375
89376 /*
89377 ** Check schema cookies in all databases.  If any cookie is out
89378 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
89379 ** make no changes to pParse->rc.
89380 */
89381 static void schemaIsValid(Parse *pParse){
89382   sqlite3 *db = pParse->db;
89383   int iDb;
89384   int rc;
89385   int cookie;
89386
89387   assert( pParse->checkSchema );
89388   assert( sqlite3_mutex_held(db->mutex) );
89389   for(iDb=0; iDb<db->nDb; iDb++){
89390     int openedTransaction = 0;         /* True if a transaction is opened */
89391     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
89392     if( pBt==0 ) continue;
89393
89394     /* If there is not already a read-only (or read-write) transaction opened
89395     ** on the b-tree database, open one now. If a transaction is opened, it 
89396     ** will be closed immediately after reading the meta-value. */
89397     if( !sqlite3BtreeIsInReadTrans(pBt) ){
89398       rc = sqlite3BtreeBeginTrans(pBt, 0);
89399       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89400         db->mallocFailed = 1;
89401       }
89402       if( rc!=SQLITE_OK ) return;
89403       openedTransaction = 1;
89404     }
89405
89406     /* Read the schema cookie from the database. If it does not match the 
89407     ** value stored as part of the in-memory schema representation,
89408     ** set Parse.rc to SQLITE_SCHEMA. */
89409     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
89410     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89411     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
89412       sqlite3ResetInternalSchema(db, iDb);
89413       pParse->rc = SQLITE_SCHEMA;
89414     }
89415
89416     /* Close the transaction, if one was opened. */
89417     if( openedTransaction ){
89418       sqlite3BtreeCommit(pBt);
89419     }
89420   }
89421 }
89422
89423 /*
89424 ** Convert a schema pointer into the iDb index that indicates
89425 ** which database file in db->aDb[] the schema refers to.
89426 **
89427 ** If the same database is attached more than once, the first
89428 ** attached database is returned.
89429 */
89430 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
89431   int i = -1000000;
89432
89433   /* If pSchema is NULL, then return -1000000. This happens when code in 
89434   ** expr.c is trying to resolve a reference to a transient table (i.e. one
89435   ** created by a sub-select). In this case the return value of this 
89436   ** function should never be used.
89437   **
89438   ** We return -1000000 instead of the more usual -1 simply because using
89439   ** -1000000 as the incorrect index into db->aDb[] is much 
89440   ** more likely to cause a segfault than -1 (of course there are assert()
89441   ** statements too, but it never hurts to play the odds).
89442   */
89443   assert( sqlite3_mutex_held(db->mutex) );
89444   if( pSchema ){
89445     for(i=0; ALWAYS(i<db->nDb); i++){
89446       if( db->aDb[i].pSchema==pSchema ){
89447         break;
89448       }
89449     }
89450     assert( i>=0 && i<db->nDb );
89451   }
89452   return i;
89453 }
89454
89455 /*
89456 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
89457 */
89458 static int sqlite3Prepare(
89459   sqlite3 *db,              /* Database handle. */
89460   const char *zSql,         /* UTF-8 encoded SQL statement. */
89461   int nBytes,               /* Length of zSql in bytes. */
89462   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89463   Vdbe *pReprepare,         /* VM being reprepared */
89464   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89465   const char **pzTail       /* OUT: End of parsed string */
89466 ){
89467   Parse *pParse;            /* Parsing context */
89468   char *zErrMsg = 0;        /* Error message */
89469   int rc = SQLITE_OK;       /* Result code */
89470   int i;                    /* Loop counter */
89471
89472   /* Allocate the parsing context */
89473   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
89474   if( pParse==0 ){
89475     rc = SQLITE_NOMEM;
89476     goto end_prepare;
89477   }
89478   pParse->pReprepare = pReprepare;
89479   assert( ppStmt && *ppStmt==0 );
89480   assert( !db->mallocFailed );
89481   assert( sqlite3_mutex_held(db->mutex) );
89482
89483   /* Check to verify that it is possible to get a read lock on all
89484   ** database schemas.  The inability to get a read lock indicates that
89485   ** some other database connection is holding a write-lock, which in
89486   ** turn means that the other connection has made uncommitted changes
89487   ** to the schema.
89488   **
89489   ** Were we to proceed and prepare the statement against the uncommitted
89490   ** schema changes and if those schema changes are subsequently rolled
89491   ** back and different changes are made in their place, then when this
89492   ** prepared statement goes to run the schema cookie would fail to detect
89493   ** the schema change.  Disaster would follow.
89494   **
89495   ** This thread is currently holding mutexes on all Btrees (because
89496   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
89497   ** is not possible for another thread to start a new schema change
89498   ** while this routine is running.  Hence, we do not need to hold 
89499   ** locks on the schema, we just need to make sure nobody else is 
89500   ** holding them.
89501   **
89502   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
89503   ** but it does *not* override schema lock detection, so this all still
89504   ** works even if READ_UNCOMMITTED is set.
89505   */
89506   for(i=0; i<db->nDb; i++) {
89507     Btree *pBt = db->aDb[i].pBt;
89508     if( pBt ){
89509       assert( sqlite3BtreeHoldsMutex(pBt) );
89510       rc = sqlite3BtreeSchemaLocked(pBt);
89511       if( rc ){
89512         const char *zDb = db->aDb[i].zName;
89513         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
89514         testcase( db->flags & SQLITE_ReadUncommitted );
89515         goto end_prepare;
89516       }
89517     }
89518   }
89519
89520   sqlite3VtabUnlockList(db);
89521
89522   pParse->db = db;
89523   pParse->nQueryLoop = (double)1;
89524   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
89525     char *zSqlCopy;
89526     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
89527     testcase( nBytes==mxLen );
89528     testcase( nBytes==mxLen+1 );
89529     if( nBytes>mxLen ){
89530       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
89531       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
89532       goto end_prepare;
89533     }
89534     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
89535     if( zSqlCopy ){
89536       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
89537       sqlite3DbFree(db, zSqlCopy);
89538       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
89539     }else{
89540       pParse->zTail = &zSql[nBytes];
89541     }
89542   }else{
89543     sqlite3RunParser(pParse, zSql, &zErrMsg);
89544   }
89545   assert( 1==(int)pParse->nQueryLoop );
89546
89547   if( db->mallocFailed ){
89548     pParse->rc = SQLITE_NOMEM;
89549   }
89550   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
89551   if( pParse->checkSchema ){
89552     schemaIsValid(pParse);
89553   }
89554   if( db->mallocFailed ){
89555     pParse->rc = SQLITE_NOMEM;
89556   }
89557   if( pzTail ){
89558     *pzTail = pParse->zTail;
89559   }
89560   rc = pParse->rc;
89561
89562 #ifndef SQLITE_OMIT_EXPLAIN
89563   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
89564     static const char * const azColName[] = {
89565        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
89566        "selectid", "order", "from", "detail"
89567     };
89568     int iFirst, mx;
89569     if( pParse->explain==2 ){
89570       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
89571       iFirst = 8;
89572       mx = 12;
89573     }else{
89574       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
89575       iFirst = 0;
89576       mx = 8;
89577     }
89578     for(i=iFirst; i<mx; i++){
89579       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
89580                             azColName[i], SQLITE_STATIC);
89581     }
89582   }
89583 #endif
89584
89585   assert( db->init.busy==0 || saveSqlFlag==0 );
89586   if( db->init.busy==0 ){
89587     Vdbe *pVdbe = pParse->pVdbe;
89588     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
89589   }
89590   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
89591     sqlite3VdbeFinalize(pParse->pVdbe);
89592     assert(!(*ppStmt));
89593   }else{
89594     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
89595   }
89596
89597   if( zErrMsg ){
89598     sqlite3Error(db, rc, "%s", zErrMsg);
89599     sqlite3DbFree(db, zErrMsg);
89600   }else{
89601     sqlite3Error(db, rc, 0);
89602   }
89603
89604   /* Delete any TriggerPrg structures allocated while parsing this statement. */
89605   while( pParse->pTriggerPrg ){
89606     TriggerPrg *pT = pParse->pTriggerPrg;
89607     pParse->pTriggerPrg = pT->pNext;
89608     sqlite3DbFree(db, pT);
89609   }
89610
89611 end_prepare:
89612
89613   sqlite3StackFree(db, pParse);
89614   rc = sqlite3ApiExit(db, rc);
89615   assert( (rc&db->errMask)==rc );
89616   return rc;
89617 }
89618 static int sqlite3LockAndPrepare(
89619   sqlite3 *db,              /* Database handle. */
89620   const char *zSql,         /* UTF-8 encoded SQL statement. */
89621   int nBytes,               /* Length of zSql in bytes. */
89622   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
89623   Vdbe *pOld,               /* VM being reprepared */
89624   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89625   const char **pzTail       /* OUT: End of parsed string */
89626 ){
89627   int rc;
89628   assert( ppStmt!=0 );
89629   *ppStmt = 0;
89630   if( !sqlite3SafetyCheckOk(db) ){
89631     return SQLITE_MISUSE_BKPT;
89632   }
89633   sqlite3_mutex_enter(db->mutex);
89634   sqlite3BtreeEnterAll(db);
89635   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89636   if( rc==SQLITE_SCHEMA ){
89637     sqlite3_finalize(*ppStmt);
89638     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89639   }
89640   sqlite3BtreeLeaveAll(db);
89641   sqlite3_mutex_leave(db->mutex);
89642   return rc;
89643 }
89644
89645 /*
89646 ** Rerun the compilation of a statement after a schema change.
89647 **
89648 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
89649 ** if the statement cannot be recompiled because another connection has
89650 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
89651 ** occurs, return SQLITE_SCHEMA.
89652 */
89653 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
89654   int rc;
89655   sqlite3_stmt *pNew;
89656   const char *zSql;
89657   sqlite3 *db;
89658
89659   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
89660   zSql = sqlite3_sql((sqlite3_stmt *)p);
89661   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
89662   db = sqlite3VdbeDb(p);
89663   assert( sqlite3_mutex_held(db->mutex) );
89664   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
89665   if( rc ){
89666     if( rc==SQLITE_NOMEM ){
89667       db->mallocFailed = 1;
89668     }
89669     assert( pNew==0 );
89670     return rc;
89671   }else{
89672     assert( pNew!=0 );
89673   }
89674   sqlite3VdbeSwap((Vdbe*)pNew, p);
89675   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
89676   sqlite3VdbeResetStepResult((Vdbe*)pNew);
89677   sqlite3VdbeFinalize((Vdbe*)pNew);
89678   return SQLITE_OK;
89679 }
89680
89681
89682 /*
89683 ** Two versions of the official API.  Legacy and new use.  In the legacy
89684 ** version, the original SQL text is not saved in the prepared statement
89685 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89686 ** sqlite3_step().  In the new version, the original SQL text is retained
89687 ** and the statement is automatically recompiled if an schema change
89688 ** occurs.
89689 */
89690 SQLITE_API int sqlite3_prepare(
89691   sqlite3 *db,              /* Database handle. */
89692   const char *zSql,         /* UTF-8 encoded SQL statement. */
89693   int nBytes,               /* Length of zSql in bytes. */
89694   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89695   const char **pzTail       /* OUT: End of parsed string */
89696 ){
89697   int rc;
89698   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
89699   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89700   return rc;
89701 }
89702 SQLITE_API int sqlite3_prepare_v2(
89703   sqlite3 *db,              /* Database handle. */
89704   const char *zSql,         /* UTF-8 encoded SQL statement. */
89705   int nBytes,               /* Length of zSql in bytes. */
89706   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89707   const char **pzTail       /* OUT: End of parsed string */
89708 ){
89709   int rc;
89710   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
89711   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89712   return rc;
89713 }
89714
89715
89716 #ifndef SQLITE_OMIT_UTF16
89717 /*
89718 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
89719 */
89720 static int sqlite3Prepare16(
89721   sqlite3 *db,              /* Database handle. */ 
89722   const void *zSql,         /* UTF-16 encoded SQL statement. */
89723   int nBytes,               /* Length of zSql in bytes. */
89724   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
89725   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89726   const void **pzTail       /* OUT: End of parsed string */
89727 ){
89728   /* This function currently works by first transforming the UTF-16
89729   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
89730   ** tricky bit is figuring out the pointer to return in *pzTail.
89731   */
89732   char *zSql8;
89733   const char *zTail8 = 0;
89734   int rc = SQLITE_OK;
89735
89736   assert( ppStmt );
89737   *ppStmt = 0;
89738   if( !sqlite3SafetyCheckOk(db) ){
89739     return SQLITE_MISUSE_BKPT;
89740   }
89741   sqlite3_mutex_enter(db->mutex);
89742   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
89743   if( zSql8 ){
89744     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
89745   }
89746
89747   if( zTail8 && pzTail ){
89748     /* If sqlite3_prepare returns a tail pointer, we calculate the
89749     ** equivalent pointer into the UTF-16 string by counting the unicode
89750     ** characters between zSql8 and zTail8, and then returning a pointer
89751     ** the same number of characters into the UTF-16 string.
89752     */
89753     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
89754     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
89755   }
89756   sqlite3DbFree(db, zSql8); 
89757   rc = sqlite3ApiExit(db, rc);
89758   sqlite3_mutex_leave(db->mutex);
89759   return rc;
89760 }
89761
89762 /*
89763 ** Two versions of the official API.  Legacy and new use.  In the legacy
89764 ** version, the original SQL text is not saved in the prepared statement
89765 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
89766 ** sqlite3_step().  In the new version, the original SQL text is retained
89767 ** and the statement is automatically recompiled if an schema change
89768 ** occurs.
89769 */
89770 SQLITE_API int sqlite3_prepare16(
89771   sqlite3 *db,              /* Database handle. */ 
89772   const void *zSql,         /* UTF-16 encoded SQL statement. */
89773   int nBytes,               /* Length of zSql in bytes. */
89774   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89775   const void **pzTail       /* OUT: End of parsed string */
89776 ){
89777   int rc;
89778   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
89779   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89780   return rc;
89781 }
89782 SQLITE_API int sqlite3_prepare16_v2(
89783   sqlite3 *db,              /* Database handle. */ 
89784   const void *zSql,         /* UTF-16 encoded SQL statement. */
89785   int nBytes,               /* Length of zSql in bytes. */
89786   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
89787   const void **pzTail       /* OUT: End of parsed string */
89788 ){
89789   int rc;
89790   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
89791   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
89792   return rc;
89793 }
89794
89795 #endif /* SQLITE_OMIT_UTF16 */
89796
89797 /************** End of prepare.c *********************************************/
89798 /************** Begin file select.c ******************************************/
89799 /*
89800 ** 2001 September 15
89801 **
89802 ** The author disclaims copyright to this source code.  In place of
89803 ** a legal notice, here is a blessing:
89804 **
89805 **    May you do good and not evil.
89806 **    May you find forgiveness for yourself and forgive others.
89807 **    May you share freely, never taking more than you give.
89808 **
89809 *************************************************************************
89810 ** This file contains C code routines that are called by the parser
89811 ** to handle SELECT statements in SQLite.
89812 */
89813
89814
89815 /*
89816 ** Delete all the content of a Select structure but do not deallocate
89817 ** the select structure itself.
89818 */
89819 static void clearSelect(sqlite3 *db, Select *p){
89820   sqlite3ExprListDelete(db, p->pEList);
89821   sqlite3SrcListDelete(db, p->pSrc);
89822   sqlite3ExprDelete(db, p->pWhere);
89823   sqlite3ExprListDelete(db, p->pGroupBy);
89824   sqlite3ExprDelete(db, p->pHaving);
89825   sqlite3ExprListDelete(db, p->pOrderBy);
89826   sqlite3SelectDelete(db, p->pPrior);
89827   sqlite3ExprDelete(db, p->pLimit);
89828   sqlite3ExprDelete(db, p->pOffset);
89829 }
89830
89831 /*
89832 ** Initialize a SelectDest structure.
89833 */
89834 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
89835   pDest->eDest = (u8)eDest;
89836   pDest->iParm = iParm;
89837   pDest->affinity = 0;
89838   pDest->iMem = 0;
89839   pDest->nMem = 0;
89840 }
89841
89842
89843 /*
89844 ** Allocate a new Select structure and return a pointer to that
89845 ** structure.
89846 */
89847 SQLITE_PRIVATE Select *sqlite3SelectNew(
89848   Parse *pParse,        /* Parsing context */
89849   ExprList *pEList,     /* which columns to include in the result */
89850   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
89851   Expr *pWhere,         /* the WHERE clause */
89852   ExprList *pGroupBy,   /* the GROUP BY clause */
89853   Expr *pHaving,        /* the HAVING clause */
89854   ExprList *pOrderBy,   /* the ORDER BY clause */
89855   int isDistinct,       /* true if the DISTINCT keyword is present */
89856   Expr *pLimit,         /* LIMIT value.  NULL means not used */
89857   Expr *pOffset         /* OFFSET value.  NULL means no offset */
89858 ){
89859   Select *pNew;
89860   Select standin;
89861   sqlite3 *db = pParse->db;
89862   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
89863   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
89864   if( pNew==0 ){
89865     pNew = &standin;
89866     memset(pNew, 0, sizeof(*pNew));
89867   }
89868   if( pEList==0 ){
89869     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
89870   }
89871   pNew->pEList = pEList;
89872   pNew->pSrc = pSrc;
89873   pNew->pWhere = pWhere;
89874   pNew->pGroupBy = pGroupBy;
89875   pNew->pHaving = pHaving;
89876   pNew->pOrderBy = pOrderBy;
89877   pNew->selFlags = isDistinct ? SF_Distinct : 0;
89878   pNew->op = TK_SELECT;
89879   pNew->pLimit = pLimit;
89880   pNew->pOffset = pOffset;
89881   assert( pOffset==0 || pLimit!=0 );
89882   pNew->addrOpenEphm[0] = -1;
89883   pNew->addrOpenEphm[1] = -1;
89884   pNew->addrOpenEphm[2] = -1;
89885   if( db->mallocFailed ) {
89886     clearSelect(db, pNew);
89887     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
89888     pNew = 0;
89889   }
89890   return pNew;
89891 }
89892
89893 /*
89894 ** Delete the given Select structure and all of its substructures.
89895 */
89896 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
89897   if( p ){
89898     clearSelect(db, p);
89899     sqlite3DbFree(db, p);
89900   }
89901 }
89902
89903 /*
89904 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
89905 ** type of join.  Return an integer constant that expresses that type
89906 ** in terms of the following bit values:
89907 **
89908 **     JT_INNER
89909 **     JT_CROSS
89910 **     JT_OUTER
89911 **     JT_NATURAL
89912 **     JT_LEFT
89913 **     JT_RIGHT
89914 **
89915 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
89916 **
89917 ** If an illegal or unsupported join type is seen, then still return
89918 ** a join type, but put an error in the pParse structure.
89919 */
89920 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
89921   int jointype = 0;
89922   Token *apAll[3];
89923   Token *p;
89924                              /*   0123456789 123456789 123456789 123 */
89925   static const char zKeyText[] = "naturaleftouterightfullinnercross";
89926   static const struct {
89927     u8 i;        /* Beginning of keyword text in zKeyText[] */
89928     u8 nChar;    /* Length of the keyword in characters */
89929     u8 code;     /* Join type mask */
89930   } aKeyword[] = {
89931     /* natural */ { 0,  7, JT_NATURAL                },
89932     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
89933     /* outer   */ { 10, 5, JT_OUTER                  },
89934     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
89935     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
89936     /* inner   */ { 23, 5, JT_INNER                  },
89937     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
89938   };
89939   int i, j;
89940   apAll[0] = pA;
89941   apAll[1] = pB;
89942   apAll[2] = pC;
89943   for(i=0; i<3 && apAll[i]; i++){
89944     p = apAll[i];
89945     for(j=0; j<ArraySize(aKeyword); j++){
89946       if( p->n==aKeyword[j].nChar 
89947           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
89948         jointype |= aKeyword[j].code;
89949         break;
89950       }
89951     }
89952     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
89953     if( j>=ArraySize(aKeyword) ){
89954       jointype |= JT_ERROR;
89955       break;
89956     }
89957   }
89958   if(
89959      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
89960      (jointype & JT_ERROR)!=0
89961   ){
89962     const char *zSp = " ";
89963     assert( pB!=0 );
89964     if( pC==0 ){ zSp++; }
89965     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
89966        "%T %T%s%T", pA, pB, zSp, pC);
89967     jointype = JT_INNER;
89968   }else if( (jointype & JT_OUTER)!=0 
89969          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
89970     sqlite3ErrorMsg(pParse, 
89971       "RIGHT and FULL OUTER JOINs are not currently supported");
89972     jointype = JT_INNER;
89973   }
89974   return jointype;
89975 }
89976
89977 /*
89978 ** Return the index of a column in a table.  Return -1 if the column
89979 ** is not contained in the table.
89980 */
89981 static int columnIndex(Table *pTab, const char *zCol){
89982   int i;
89983   for(i=0; i<pTab->nCol; i++){
89984     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
89985   }
89986   return -1;
89987 }
89988
89989 /*
89990 ** Search the first N tables in pSrc, from left to right, looking for a
89991 ** table that has a column named zCol.  
89992 **
89993 ** When found, set *piTab and *piCol to the table index and column index
89994 ** of the matching column and return TRUE.
89995 **
89996 ** If not found, return FALSE.
89997 */
89998 static int tableAndColumnIndex(
89999   SrcList *pSrc,       /* Array of tables to search */
90000   int N,               /* Number of tables in pSrc->a[] to search */
90001   const char *zCol,    /* Name of the column we are looking for */
90002   int *piTab,          /* Write index of pSrc->a[] here */
90003   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
90004 ){
90005   int i;               /* For looping over tables in pSrc */
90006   int iCol;            /* Index of column matching zCol */
90007
90008   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
90009   for(i=0; i<N; i++){
90010     iCol = columnIndex(pSrc->a[i].pTab, zCol);
90011     if( iCol>=0 ){
90012       if( piTab ){
90013         *piTab = i;
90014         *piCol = iCol;
90015       }
90016       return 1;
90017     }
90018   }
90019   return 0;
90020 }
90021
90022 /*
90023 ** This function is used to add terms implied by JOIN syntax to the
90024 ** WHERE clause expression of a SELECT statement. The new term, which
90025 ** is ANDed with the existing WHERE clause, is of the form:
90026 **
90027 **    (tab1.col1 = tab2.col2)
90028 **
90029 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
90030 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90031 ** column iColRight of tab2.
90032 */
90033 static void addWhereTerm(
90034   Parse *pParse,                  /* Parsing context */
90035   SrcList *pSrc,                  /* List of tables in FROM clause */
90036   int iLeft,                      /* Index of first table to join in pSrc */
90037   int iColLeft,                   /* Index of column in first table */
90038   int iRight,                     /* Index of second table in pSrc */
90039   int iColRight,                  /* Index of column in second table */
90040   int isOuterJoin,                /* True if this is an OUTER join */
90041   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
90042 ){
90043   sqlite3 *db = pParse->db;
90044   Expr *pE1;
90045   Expr *pE2;
90046   Expr *pEq;
90047
90048   assert( iLeft<iRight );
90049   assert( pSrc->nSrc>iRight );
90050   assert( pSrc->a[iLeft].pTab );
90051   assert( pSrc->a[iRight].pTab );
90052
90053   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90054   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90055
90056   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90057   if( pEq && isOuterJoin ){
90058     ExprSetProperty(pEq, EP_FromJoin);
90059     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90060     ExprSetIrreducible(pEq);
90061     pEq->iRightJoinTable = (i16)pE2->iTable;
90062   }
90063   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90064 }
90065
90066 /*
90067 ** Set the EP_FromJoin property on all terms of the given expression.
90068 ** And set the Expr.iRightJoinTable to iTable for every term in the
90069 ** expression.
90070 **
90071 ** The EP_FromJoin property is used on terms of an expression to tell
90072 ** the LEFT OUTER JOIN processing logic that this term is part of the
90073 ** join restriction specified in the ON or USING clause and not a part
90074 ** of the more general WHERE clause.  These terms are moved over to the
90075 ** WHERE clause during join processing but we need to remember that they
90076 ** originated in the ON or USING clause.
90077 **
90078 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
90079 ** expression depends on table iRightJoinTable even if that table is not
90080 ** explicitly mentioned in the expression.  That information is needed
90081 ** for cases like this:
90082 **
90083 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90084 **
90085 ** The where clause needs to defer the handling of the t1.x=5
90086 ** term until after the t2 loop of the join.  In that way, a
90087 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
90088 ** defer the handling of t1.x=5, it will be processed immediately
90089 ** after the t1 loop and rows with t1.x!=5 will never appear in
90090 ** the output, which is incorrect.
90091 */
90092 static void setJoinExpr(Expr *p, int iTable){
90093   while( p ){
90094     ExprSetProperty(p, EP_FromJoin);
90095     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90096     ExprSetIrreducible(p);
90097     p->iRightJoinTable = (i16)iTable;
90098     setJoinExpr(p->pLeft, iTable);
90099     p = p->pRight;
90100   } 
90101 }
90102
90103 /*
90104 ** This routine processes the join information for a SELECT statement.
90105 ** ON and USING clauses are converted into extra terms of the WHERE clause.
90106 ** NATURAL joins also create extra WHERE clause terms.
90107 **
90108 ** The terms of a FROM clause are contained in the Select.pSrc structure.
90109 ** The left most table is the first entry in Select.pSrc.  The right-most
90110 ** table is the last entry.  The join operator is held in the entry to
90111 ** the left.  Thus entry 0 contains the join operator for the join between
90112 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
90113 ** also attached to the left entry.
90114 **
90115 ** This routine returns the number of errors encountered.
90116 */
90117 static int sqliteProcessJoin(Parse *pParse, Select *p){
90118   SrcList *pSrc;                  /* All tables in the FROM clause */
90119   int i, j;                       /* Loop counters */
90120   struct SrcList_item *pLeft;     /* Left table being joined */
90121   struct SrcList_item *pRight;    /* Right table being joined */
90122
90123   pSrc = p->pSrc;
90124   pLeft = &pSrc->a[0];
90125   pRight = &pLeft[1];
90126   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90127     Table *pLeftTab = pLeft->pTab;
90128     Table *pRightTab = pRight->pTab;
90129     int isOuter;
90130
90131     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90132     isOuter = (pRight->jointype & JT_OUTER)!=0;
90133
90134     /* When the NATURAL keyword is present, add WHERE clause terms for
90135     ** every column that the two tables have in common.
90136     */
90137     if( pRight->jointype & JT_NATURAL ){
90138       if( pRight->pOn || pRight->pUsing ){
90139         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90140            "an ON or USING clause", 0);
90141         return 1;
90142       }
90143       for(j=0; j<pRightTab->nCol; j++){
90144         char *zName;   /* Name of column in the right table */
90145         int iLeft;     /* Matching left table */
90146         int iLeftCol;  /* Matching column in the left table */
90147
90148         zName = pRightTab->aCol[j].zName;
90149         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90150           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90151                        isOuter, &p->pWhere);
90152         }
90153       }
90154     }
90155
90156     /* Disallow both ON and USING clauses in the same join
90157     */
90158     if( pRight->pOn && pRight->pUsing ){
90159       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90160         "clauses in the same join");
90161       return 1;
90162     }
90163
90164     /* Add the ON clause to the end of the WHERE clause, connected by
90165     ** an AND operator.
90166     */
90167     if( pRight->pOn ){
90168       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90169       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90170       pRight->pOn = 0;
90171     }
90172
90173     /* Create extra terms on the WHERE clause for each column named
90174     ** in the USING clause.  Example: If the two tables to be joined are 
90175     ** A and B and the USING clause names X, Y, and Z, then add this
90176     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90177     ** Report an error if any column mentioned in the USING clause is
90178     ** not contained in both tables to be joined.
90179     */
90180     if( pRight->pUsing ){
90181       IdList *pList = pRight->pUsing;
90182       for(j=0; j<pList->nId; j++){
90183         char *zName;     /* Name of the term in the USING clause */
90184         int iLeft;       /* Table on the left with matching column name */
90185         int iLeftCol;    /* Column number of matching column on the left */
90186         int iRightCol;   /* Column number of matching column on the right */
90187
90188         zName = pList->a[j].zName;
90189         iRightCol = columnIndex(pRightTab, zName);
90190         if( iRightCol<0
90191          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90192         ){
90193           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90194             "not present in both tables", zName);
90195           return 1;
90196         }
90197         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90198                      isOuter, &p->pWhere);
90199       }
90200     }
90201   }
90202   return 0;
90203 }
90204
90205 /*
90206 ** Insert code into "v" that will push the record on the top of the
90207 ** stack into the sorter.
90208 */
90209 static void pushOntoSorter(
90210   Parse *pParse,         /* Parser context */
90211   ExprList *pOrderBy,    /* The ORDER BY clause */
90212   Select *pSelect,       /* The whole SELECT statement */
90213   int regData            /* Register holding data to be sorted */
90214 ){
90215   Vdbe *v = pParse->pVdbe;
90216   int nExpr = pOrderBy->nExpr;
90217   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90218   int regRecord = sqlite3GetTempReg(pParse);
90219   sqlite3ExprCacheClear(pParse);
90220   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90221   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90222   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90223   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90224   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90225   sqlite3ReleaseTempReg(pParse, regRecord);
90226   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90227   if( pSelect->iLimit ){
90228     int addr1, addr2;
90229     int iLimit;
90230     if( pSelect->iOffset ){
90231       iLimit = pSelect->iOffset+1;
90232     }else{
90233       iLimit = pSelect->iLimit;
90234     }
90235     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90236     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90237     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90238     sqlite3VdbeJumpHere(v, addr1);
90239     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90240     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90241     sqlite3VdbeJumpHere(v, addr2);
90242   }
90243 }
90244
90245 /*
90246 ** Add code to implement the OFFSET
90247 */
90248 static void codeOffset(
90249   Vdbe *v,          /* Generate code into this VM */
90250   Select *p,        /* The SELECT statement being coded */
90251   int iContinue     /* Jump here to skip the current record */
90252 ){
90253   if( p->iOffset && iContinue!=0 ){
90254     int addr;
90255     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90256     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90257     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90258     VdbeComment((v, "skip OFFSET records"));
90259     sqlite3VdbeJumpHere(v, addr);
90260   }
90261 }
90262
90263 /*
90264 ** Add code that will check to make sure the N registers starting at iMem
90265 ** form a distinct entry.  iTab is a sorting index that holds previously
90266 ** seen combinations of the N values.  A new entry is made in iTab
90267 ** if the current N values are new.
90268 **
90269 ** A jump to addrRepeat is made and the N+1 values are popped from the
90270 ** stack if the top N elements are not distinct.
90271 */
90272 static void codeDistinct(
90273   Parse *pParse,     /* Parsing and code generating context */
90274   int iTab,          /* A sorting index used to test for distinctness */
90275   int addrRepeat,    /* Jump to here if not distinct */
90276   int N,             /* Number of elements */
90277   int iMem           /* First element */
90278 ){
90279   Vdbe *v;
90280   int r1;
90281
90282   v = pParse->pVdbe;
90283   r1 = sqlite3GetTempReg(pParse);
90284   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90285   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90286   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90287   sqlite3ReleaseTempReg(pParse, r1);
90288 }
90289
90290 #ifndef SQLITE_OMIT_SUBQUERY
90291 /*
90292 ** Generate an error message when a SELECT is used within a subexpression
90293 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
90294 ** column.  We do this in a subroutine because the error used to occur
90295 ** in multiple places.  (The error only occurs in one place now, but we
90296 ** retain the subroutine to minimize code disruption.)
90297 */
90298 static int checkForMultiColumnSelectError(
90299   Parse *pParse,       /* Parse context. */
90300   SelectDest *pDest,   /* Destination of SELECT results */
90301   int nExpr            /* Number of result columns returned by SELECT */
90302 ){
90303   int eDest = pDest->eDest;
90304   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90305     sqlite3ErrorMsg(pParse, "only a single result allowed for "
90306        "a SELECT that is part of an expression");
90307     return 1;
90308   }else{
90309     return 0;
90310   }
90311 }
90312 #endif
90313
90314 /*
90315 ** This routine generates the code for the inside of the inner loop
90316 ** of a SELECT.
90317 **
90318 ** If srcTab and nColumn are both zero, then the pEList expressions
90319 ** are evaluated in order to get the data for this row.  If nColumn>0
90320 ** then data is pulled from srcTab and pEList is used only to get the
90321 ** datatypes for each column.
90322 */
90323 static void selectInnerLoop(
90324   Parse *pParse,          /* The parser context */
90325   Select *p,              /* The complete select statement being coded */
90326   ExprList *pEList,       /* List of values being extracted */
90327   int srcTab,             /* Pull data from this table */
90328   int nColumn,            /* Number of columns in the source table */
90329   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
90330   int distinct,           /* If >=0, make sure results are distinct */
90331   SelectDest *pDest,      /* How to dispose of the results */
90332   int iContinue,          /* Jump here to continue with next row */
90333   int iBreak              /* Jump here to break out of the inner loop */
90334 ){
90335   Vdbe *v = pParse->pVdbe;
90336   int i;
90337   int hasDistinct;        /* True if the DISTINCT keyword is present */
90338   int regResult;              /* Start of memory holding result set */
90339   int eDest = pDest->eDest;   /* How to dispose of results */
90340   int iParm = pDest->iParm;   /* First argument to disposal method */
90341   int nResultCol;             /* Number of result columns */
90342
90343   assert( v );
90344   if( NEVER(v==0) ) return;
90345   assert( pEList!=0 );
90346   hasDistinct = distinct>=0;
90347   if( pOrderBy==0 && !hasDistinct ){
90348     codeOffset(v, p, iContinue);
90349   }
90350
90351   /* Pull the requested columns.
90352   */
90353   if( nColumn>0 ){
90354     nResultCol = nColumn;
90355   }else{
90356     nResultCol = pEList->nExpr;
90357   }
90358   if( pDest->iMem==0 ){
90359     pDest->iMem = pParse->nMem+1;
90360     pDest->nMem = nResultCol;
90361     pParse->nMem += nResultCol;
90362   }else{ 
90363     assert( pDest->nMem==nResultCol );
90364   }
90365   regResult = pDest->iMem;
90366   if( nColumn>0 ){
90367     for(i=0; i<nColumn; i++){
90368       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
90369     }
90370   }else if( eDest!=SRT_Exists ){
90371     /* If the destination is an EXISTS(...) expression, the actual
90372     ** values returned by the SELECT are not required.
90373     */
90374     sqlite3ExprCacheClear(pParse);
90375     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
90376   }
90377   nColumn = nResultCol;
90378
90379   /* If the DISTINCT keyword was present on the SELECT statement
90380   ** and this row has been seen before, then do not make this row
90381   ** part of the result.
90382   */
90383   if( hasDistinct ){
90384     assert( pEList!=0 );
90385     assert( pEList->nExpr==nColumn );
90386     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
90387     if( pOrderBy==0 ){
90388       codeOffset(v, p, iContinue);
90389     }
90390   }
90391
90392   switch( eDest ){
90393     /* In this mode, write each query result to the key of the temporary
90394     ** table iParm.
90395     */
90396 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90397     case SRT_Union: {
90398       int r1;
90399       r1 = sqlite3GetTempReg(pParse);
90400       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90401       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90402       sqlite3ReleaseTempReg(pParse, r1);
90403       break;
90404     }
90405
90406     /* Construct a record from the query result, but instead of
90407     ** saving that record, use it as a key to delete elements from
90408     ** the temporary table iParm.
90409     */
90410     case SRT_Except: {
90411       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
90412       break;
90413     }
90414 #endif
90415
90416     /* Store the result as data using a unique key.
90417     */
90418     case SRT_Table:
90419     case SRT_EphemTab: {
90420       int r1 = sqlite3GetTempReg(pParse);
90421       testcase( eDest==SRT_Table );
90422       testcase( eDest==SRT_EphemTab );
90423       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90424       if( pOrderBy ){
90425         pushOntoSorter(pParse, pOrderBy, p, r1);
90426       }else{
90427         int r2 = sqlite3GetTempReg(pParse);
90428         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
90429         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
90430         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90431         sqlite3ReleaseTempReg(pParse, r2);
90432       }
90433       sqlite3ReleaseTempReg(pParse, r1);
90434       break;
90435     }
90436
90437 #ifndef SQLITE_OMIT_SUBQUERY
90438     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
90439     ** then there should be a single item on the stack.  Write this
90440     ** item into the set table with bogus data.
90441     */
90442     case SRT_Set: {
90443       assert( nColumn==1 );
90444       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
90445       if( pOrderBy ){
90446         /* At first glance you would think we could optimize out the
90447         ** ORDER BY in this case since the order of entries in the set
90448         ** does not matter.  But there might be a LIMIT clause, in which
90449         ** case the order does matter */
90450         pushOntoSorter(pParse, pOrderBy, p, regResult);
90451       }else{
90452         int r1 = sqlite3GetTempReg(pParse);
90453         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
90454         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
90455         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90456         sqlite3ReleaseTempReg(pParse, r1);
90457       }
90458       break;
90459     }
90460
90461     /* If any row exist in the result set, record that fact and abort.
90462     */
90463     case SRT_Exists: {
90464       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
90465       /* The LIMIT clause will terminate the loop for us */
90466       break;
90467     }
90468
90469     /* If this is a scalar select that is part of an expression, then
90470     ** store the results in the appropriate memory cell and break out
90471     ** of the scan loop.
90472     */
90473     case SRT_Mem: {
90474       assert( nColumn==1 );
90475       if( pOrderBy ){
90476         pushOntoSorter(pParse, pOrderBy, p, regResult);
90477       }else{
90478         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
90479         /* The LIMIT clause will jump out of the loop for us */
90480       }
90481       break;
90482     }
90483 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90484
90485     /* Send the data to the callback function or to a subroutine.  In the
90486     ** case of a subroutine, the subroutine itself is responsible for
90487     ** popping the data from the stack.
90488     */
90489     case SRT_Coroutine:
90490     case SRT_Output: {
90491       testcase( eDest==SRT_Coroutine );
90492       testcase( eDest==SRT_Output );
90493       if( pOrderBy ){
90494         int r1 = sqlite3GetTempReg(pParse);
90495         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90496         pushOntoSorter(pParse, pOrderBy, p, r1);
90497         sqlite3ReleaseTempReg(pParse, r1);
90498       }else if( eDest==SRT_Coroutine ){
90499         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90500       }else{
90501         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
90502         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
90503       }
90504       break;
90505     }
90506
90507 #if !defined(SQLITE_OMIT_TRIGGER)
90508     /* Discard the results.  This is used for SELECT statements inside
90509     ** the body of a TRIGGER.  The purpose of such selects is to call
90510     ** user-defined functions that have side effects.  We do not care
90511     ** about the actual results of the select.
90512     */
90513     default: {
90514       assert( eDest==SRT_Discard );
90515       break;
90516     }
90517 #endif
90518   }
90519
90520   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
90521   ** there is a sorter, in which case the sorter has already limited
90522   ** the output for us.
90523   */
90524   if( pOrderBy==0 && p->iLimit ){
90525     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90526   }
90527 }
90528
90529 /*
90530 ** Given an expression list, generate a KeyInfo structure that records
90531 ** the collating sequence for each expression in that expression list.
90532 **
90533 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
90534 ** KeyInfo structure is appropriate for initializing a virtual index to
90535 ** implement that clause.  If the ExprList is the result set of a SELECT
90536 ** then the KeyInfo structure is appropriate for initializing a virtual
90537 ** index to implement a DISTINCT test.
90538 **
90539 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
90540 ** function is responsible for seeing that this structure is eventually
90541 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
90542 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
90543 */
90544 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
90545   sqlite3 *db = pParse->db;
90546   int nExpr;
90547   KeyInfo *pInfo;
90548   struct ExprList_item *pItem;
90549   int i;
90550
90551   nExpr = pList->nExpr;
90552   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
90553   if( pInfo ){
90554     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
90555     pInfo->nField = (u16)nExpr;
90556     pInfo->enc = ENC(db);
90557     pInfo->db = db;
90558     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
90559       CollSeq *pColl;
90560       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90561       if( !pColl ){
90562         pColl = db->pDfltColl;
90563       }
90564       pInfo->aColl[i] = pColl;
90565       pInfo->aSortOrder[i] = pItem->sortOrder;
90566     }
90567   }
90568   return pInfo;
90569 }
90570
90571 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90572 /*
90573 ** Name of the connection operator, used for error messages.
90574 */
90575 static const char *selectOpName(int id){
90576   char *z;
90577   switch( id ){
90578     case TK_ALL:       z = "UNION ALL";   break;
90579     case TK_INTERSECT: z = "INTERSECT";   break;
90580     case TK_EXCEPT:    z = "EXCEPT";      break;
90581     default:           z = "UNION";       break;
90582   }
90583   return z;
90584 }
90585 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
90586
90587 #ifndef SQLITE_OMIT_EXPLAIN
90588 /*
90589 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90590 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90591 ** where the caption is of the form:
90592 **
90593 **   "USE TEMP B-TREE FOR xxx"
90594 **
90595 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
90596 ** is determined by the zUsage argument.
90597 */
90598 static void explainTempTable(Parse *pParse, const char *zUsage){
90599   if( pParse->explain==2 ){
90600     Vdbe *v = pParse->pVdbe;
90601     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
90602     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90603   }
90604 }
90605
90606 /*
90607 ** Assign expression b to lvalue a. A second, no-op, version of this macro
90608 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
90609 ** in sqlite3Select() to assign values to structure member variables that
90610 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
90611 ** code with #ifndef directives.
90612 */
90613 # define explainSetInteger(a, b) a = b
90614
90615 #else
90616 /* No-op versions of the explainXXX() functions and macros. */
90617 # define explainTempTable(y,z)
90618 # define explainSetInteger(y,z)
90619 #endif
90620
90621 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
90622 /*
90623 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90624 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90625 ** where the caption is of one of the two forms:
90626 **
90627 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
90628 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
90629 **
90630 ** where iSub1 and iSub2 are the integers passed as the corresponding
90631 ** function parameters, and op is the text representation of the parameter
90632 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
90633 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
90634 ** false, or the second form if it is true.
90635 */
90636 static void explainComposite(
90637   Parse *pParse,                  /* Parse context */
90638   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
90639   int iSub1,                      /* Subquery id 1 */
90640   int iSub2,                      /* Subquery id 2 */
90641   int bUseTmp                     /* True if a temp table was used */
90642 ){
90643   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
90644   if( pParse->explain==2 ){
90645     Vdbe *v = pParse->pVdbe;
90646     char *zMsg = sqlite3MPrintf(
90647         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
90648         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
90649     );
90650     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90651   }
90652 }
90653 #else
90654 /* No-op versions of the explainXXX() functions and macros. */
90655 # define explainComposite(v,w,x,y,z)
90656 #endif
90657
90658 /*
90659 ** If the inner loop was generated using a non-null pOrderBy argument,
90660 ** then the results were placed in a sorter.  After the loop is terminated
90661 ** we need to run the sorter and output the results.  The following
90662 ** routine generates the code needed to do that.
90663 */
90664 static void generateSortTail(
90665   Parse *pParse,    /* Parsing context */
90666   Select *p,        /* The SELECT statement */
90667   Vdbe *v,          /* Generate code into this VDBE */
90668   int nColumn,      /* Number of columns of data */
90669   SelectDest *pDest /* Write the sorted results here */
90670 ){
90671   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
90672   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
90673   int addr;
90674   int iTab;
90675   int pseudoTab = 0;
90676   ExprList *pOrderBy = p->pOrderBy;
90677
90678   int eDest = pDest->eDest;
90679   int iParm = pDest->iParm;
90680
90681   int regRow;
90682   int regRowid;
90683
90684   iTab = pOrderBy->iECursor;
90685   regRow = sqlite3GetTempReg(pParse);
90686   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90687     pseudoTab = pParse->nTab++;
90688     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
90689     regRowid = 0;
90690   }else{
90691     regRowid = sqlite3GetTempReg(pParse);
90692   }
90693   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
90694   codeOffset(v, p, addrContinue);
90695   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
90696   switch( eDest ){
90697     case SRT_Table:
90698     case SRT_EphemTab: {
90699       testcase( eDest==SRT_Table );
90700       testcase( eDest==SRT_EphemTab );
90701       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
90702       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
90703       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90704       break;
90705     }
90706 #ifndef SQLITE_OMIT_SUBQUERY
90707     case SRT_Set: {
90708       assert( nColumn==1 );
90709       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
90710       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
90711       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
90712       break;
90713     }
90714     case SRT_Mem: {
90715       assert( nColumn==1 );
90716       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
90717       /* The LIMIT clause will terminate the loop for us */
90718       break;
90719     }
90720 #endif
90721     default: {
90722       int i;
90723       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
90724       testcase( eDest==SRT_Output );
90725       testcase( eDest==SRT_Coroutine );
90726       for(i=0; i<nColumn; i++){
90727         assert( regRow!=pDest->iMem+i );
90728         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
90729         if( i==0 ){
90730           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
90731         }
90732       }
90733       if( eDest==SRT_Output ){
90734         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
90735         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
90736       }else{
90737         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90738       }
90739       break;
90740     }
90741   }
90742   sqlite3ReleaseTempReg(pParse, regRow);
90743   sqlite3ReleaseTempReg(pParse, regRowid);
90744
90745   /* The bottom of the loop
90746   */
90747   sqlite3VdbeResolveLabel(v, addrContinue);
90748   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
90749   sqlite3VdbeResolveLabel(v, addrBreak);
90750   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
90751     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
90752   }
90753 }
90754
90755 /*
90756 ** Return a pointer to a string containing the 'declaration type' of the
90757 ** expression pExpr. The string may be treated as static by the caller.
90758 **
90759 ** The declaration type is the exact datatype definition extracted from the
90760 ** original CREATE TABLE statement if the expression is a column. The
90761 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
90762 ** is considered a column can be complex in the presence of subqueries. The
90763 ** result-set expression in all of the following SELECT statements is 
90764 ** considered a column by this function.
90765 **
90766 **   SELECT col FROM tbl;
90767 **   SELECT (SELECT col FROM tbl;
90768 **   SELECT (SELECT col FROM tbl);
90769 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
90770 ** 
90771 ** The declaration type for any expression other than a column is NULL.
90772 */
90773 static const char *columnType(
90774   NameContext *pNC, 
90775   Expr *pExpr,
90776   const char **pzOriginDb,
90777   const char **pzOriginTab,
90778   const char **pzOriginCol
90779 ){
90780   char const *zType = 0;
90781   char const *zOriginDb = 0;
90782   char const *zOriginTab = 0;
90783   char const *zOriginCol = 0;
90784   int j;
90785   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
90786
90787   switch( pExpr->op ){
90788     case TK_AGG_COLUMN:
90789     case TK_COLUMN: {
90790       /* The expression is a column. Locate the table the column is being
90791       ** extracted from in NameContext.pSrcList. This table may be real
90792       ** database table or a subquery.
90793       */
90794       Table *pTab = 0;            /* Table structure column is extracted from */
90795       Select *pS = 0;             /* Select the column is extracted from */
90796       int iCol = pExpr->iColumn;  /* Index of column in pTab */
90797       testcase( pExpr->op==TK_AGG_COLUMN );
90798       testcase( pExpr->op==TK_COLUMN );
90799       while( pNC && !pTab ){
90800         SrcList *pTabList = pNC->pSrcList;
90801         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
90802         if( j<pTabList->nSrc ){
90803           pTab = pTabList->a[j].pTab;
90804           pS = pTabList->a[j].pSelect;
90805         }else{
90806           pNC = pNC->pNext;
90807         }
90808       }
90809
90810       if( pTab==0 ){
90811         /* At one time, code such as "SELECT new.x" within a trigger would
90812         ** cause this condition to run.  Since then, we have restructured how
90813         ** trigger code is generated and so this condition is no longer 
90814         ** possible. However, it can still be true for statements like
90815         ** the following:
90816         **
90817         **   CREATE TABLE t1(col INTEGER);
90818         **   SELECT (SELECT t1.col) FROM FROM t1;
90819         **
90820         ** when columnType() is called on the expression "t1.col" in the 
90821         ** sub-select. In this case, set the column type to NULL, even
90822         ** though it should really be "INTEGER".
90823         **
90824         ** This is not a problem, as the column type of "t1.col" is never
90825         ** used. When columnType() is called on the expression 
90826         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
90827         ** branch below.  */
90828         break;
90829       }
90830
90831       assert( pTab && pExpr->pTab==pTab );
90832       if( pS ){
90833         /* The "table" is actually a sub-select or a view in the FROM clause
90834         ** of the SELECT statement. Return the declaration type and origin
90835         ** data for the result-set column of the sub-select.
90836         */
90837         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
90838           /* If iCol is less than zero, then the expression requests the
90839           ** rowid of the sub-select or view. This expression is legal (see 
90840           ** test case misc2.2.2) - it always evaluates to NULL.
90841           */
90842           NameContext sNC;
90843           Expr *p = pS->pEList->a[iCol].pExpr;
90844           sNC.pSrcList = pS->pSrc;
90845           sNC.pNext = pNC;
90846           sNC.pParse = pNC->pParse;
90847           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
90848         }
90849       }else if( ALWAYS(pTab->pSchema) ){
90850         /* A real table */
90851         assert( !pS );
90852         if( iCol<0 ) iCol = pTab->iPKey;
90853         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
90854         if( iCol<0 ){
90855           zType = "INTEGER";
90856           zOriginCol = "rowid";
90857         }else{
90858           zType = pTab->aCol[iCol].zType;
90859           zOriginCol = pTab->aCol[iCol].zName;
90860         }
90861         zOriginTab = pTab->zName;
90862         if( pNC->pParse ){
90863           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
90864           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
90865         }
90866       }
90867       break;
90868     }
90869 #ifndef SQLITE_OMIT_SUBQUERY
90870     case TK_SELECT: {
90871       /* The expression is a sub-select. Return the declaration type and
90872       ** origin info for the single column in the result set of the SELECT
90873       ** statement.
90874       */
90875       NameContext sNC;
90876       Select *pS = pExpr->x.pSelect;
90877       Expr *p = pS->pEList->a[0].pExpr;
90878       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
90879       sNC.pSrcList = pS->pSrc;
90880       sNC.pNext = pNC;
90881       sNC.pParse = pNC->pParse;
90882       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
90883       break;
90884     }
90885 #endif
90886   }
90887   
90888   if( pzOriginDb ){
90889     assert( pzOriginTab && pzOriginCol );
90890     *pzOriginDb = zOriginDb;
90891     *pzOriginTab = zOriginTab;
90892     *pzOriginCol = zOriginCol;
90893   }
90894   return zType;
90895 }
90896
90897 /*
90898 ** Generate code that will tell the VDBE the declaration types of columns
90899 ** in the result set.
90900 */
90901 static void generateColumnTypes(
90902   Parse *pParse,      /* Parser context */
90903   SrcList *pTabList,  /* List of tables */
90904   ExprList *pEList    /* Expressions defining the result set */
90905 ){
90906 #ifndef SQLITE_OMIT_DECLTYPE
90907   Vdbe *v = pParse->pVdbe;
90908   int i;
90909   NameContext sNC;
90910   sNC.pSrcList = pTabList;
90911   sNC.pParse = pParse;
90912   for(i=0; i<pEList->nExpr; i++){
90913     Expr *p = pEList->a[i].pExpr;
90914     const char *zType;
90915 #ifdef SQLITE_ENABLE_COLUMN_METADATA
90916     const char *zOrigDb = 0;
90917     const char *zOrigTab = 0;
90918     const char *zOrigCol = 0;
90919     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
90920
90921     /* The vdbe must make its own copy of the column-type and other 
90922     ** column specific strings, in case the schema is reset before this
90923     ** virtual machine is deleted.
90924     */
90925     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
90926     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
90927     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
90928 #else
90929     zType = columnType(&sNC, p, 0, 0, 0);
90930 #endif
90931     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
90932   }
90933 #endif /* SQLITE_OMIT_DECLTYPE */
90934 }
90935
90936 /*
90937 ** Generate code that will tell the VDBE the names of columns
90938 ** in the result set.  This information is used to provide the
90939 ** azCol[] values in the callback.
90940 */
90941 static void generateColumnNames(
90942   Parse *pParse,      /* Parser context */
90943   SrcList *pTabList,  /* List of tables */
90944   ExprList *pEList    /* Expressions defining the result set */
90945 ){
90946   Vdbe *v = pParse->pVdbe;
90947   int i, j;
90948   sqlite3 *db = pParse->db;
90949   int fullNames, shortNames;
90950
90951 #ifndef SQLITE_OMIT_EXPLAIN
90952   /* If this is an EXPLAIN, skip this step */
90953   if( pParse->explain ){
90954     return;
90955   }
90956 #endif
90957
90958   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
90959   pParse->colNamesSet = 1;
90960   fullNames = (db->flags & SQLITE_FullColNames)!=0;
90961   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
90962   sqlite3VdbeSetNumCols(v, pEList->nExpr);
90963   for(i=0; i<pEList->nExpr; i++){
90964     Expr *p;
90965     p = pEList->a[i].pExpr;
90966     if( NEVER(p==0) ) continue;
90967     if( pEList->a[i].zName ){
90968       char *zName = pEList->a[i].zName;
90969       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
90970     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
90971       Table *pTab;
90972       char *zCol;
90973       int iCol = p->iColumn;
90974       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
90975         if( pTabList->a[j].iCursor==p->iTable ) break;
90976       }
90977       assert( j<pTabList->nSrc );
90978       pTab = pTabList->a[j].pTab;
90979       if( iCol<0 ) iCol = pTab->iPKey;
90980       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
90981       if( iCol<0 ){
90982         zCol = "rowid";
90983       }else{
90984         zCol = pTab->aCol[iCol].zName;
90985       }
90986       if( !shortNames && !fullNames ){
90987         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
90988             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
90989       }else if( fullNames ){
90990         char *zName = 0;
90991         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
90992         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
90993       }else{
90994         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
90995       }
90996     }else{
90997       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
90998           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
90999     }
91000   }
91001   generateColumnTypes(pParse, pTabList, pEList);
91002 }
91003
91004 /*
91005 ** Given a an expression list (which is really the list of expressions
91006 ** that form the result set of a SELECT statement) compute appropriate
91007 ** column names for a table that would hold the expression list.
91008 **
91009 ** All column names will be unique.
91010 **
91011 ** Only the column names are computed.  Column.zType, Column.zColl,
91012 ** and other fields of Column are zeroed.
91013 **
91014 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
91015 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91016 */
91017 static int selectColumnsFromExprList(
91018   Parse *pParse,          /* Parsing context */
91019   ExprList *pEList,       /* Expr list from which to derive column names */
91020   int *pnCol,             /* Write the number of columns here */
91021   Column **paCol          /* Write the new column list here */
91022 ){
91023   sqlite3 *db = pParse->db;   /* Database connection */
91024   int i, j;                   /* Loop counters */
91025   int cnt;                    /* Index added to make the name unique */
91026   Column *aCol, *pCol;        /* For looping over result columns */
91027   int nCol;                   /* Number of columns in the result set */
91028   Expr *p;                    /* Expression for a single result column */
91029   char *zName;                /* Column name */
91030   int nName;                  /* Size of name in zName[] */
91031
91032   *pnCol = nCol = pEList->nExpr;
91033   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91034   if( aCol==0 ) return SQLITE_NOMEM;
91035   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91036     /* Get an appropriate name for the column
91037     */
91038     p = pEList->a[i].pExpr;
91039     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91040                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91041     if( (zName = pEList->a[i].zName)!=0 ){
91042       /* If the column contains an "AS <name>" phrase, use <name> as the name */
91043       zName = sqlite3DbStrDup(db, zName);
91044     }else{
91045       Expr *pColExpr = p;  /* The expression that is the result column name */
91046       Table *pTab;         /* Table associated with this expression */
91047       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91048       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91049         /* For columns use the column name name */
91050         int iCol = pColExpr->iColumn;
91051         pTab = pColExpr->pTab;
91052         if( iCol<0 ) iCol = pTab->iPKey;
91053         zName = sqlite3MPrintf(db, "%s",
91054                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91055       }else if( pColExpr->op==TK_ID ){
91056         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91057         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91058       }else{
91059         /* Use the original text of the column expression as its name */
91060         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91061       }
91062     }
91063     if( db->mallocFailed ){
91064       sqlite3DbFree(db, zName);
91065       break;
91066     }
91067
91068     /* Make sure the column name is unique.  If the name is not unique,
91069     ** append a integer to the name so that it becomes unique.
91070     */
91071     nName = sqlite3Strlen30(zName);
91072     for(j=cnt=0; j<i; j++){
91073       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91074         char *zNewName;
91075         zName[nName] = 0;
91076         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91077         sqlite3DbFree(db, zName);
91078         zName = zNewName;
91079         j = -1;
91080         if( zName==0 ) break;
91081       }
91082     }
91083     pCol->zName = zName;
91084   }
91085   if( db->mallocFailed ){
91086     for(j=0; j<i; j++){
91087       sqlite3DbFree(db, aCol[j].zName);
91088     }
91089     sqlite3DbFree(db, aCol);
91090     *paCol = 0;
91091     *pnCol = 0;
91092     return SQLITE_NOMEM;
91093   }
91094   return SQLITE_OK;
91095 }
91096
91097 /*
91098 ** Add type and collation information to a column list based on
91099 ** a SELECT statement.
91100 ** 
91101 ** The column list presumably came from selectColumnNamesFromExprList().
91102 ** The column list has only names, not types or collations.  This
91103 ** routine goes through and adds the types and collations.
91104 **
91105 ** This routine requires that all identifiers in the SELECT
91106 ** statement be resolved.
91107 */
91108 static void selectAddColumnTypeAndCollation(
91109   Parse *pParse,        /* Parsing contexts */
91110   int nCol,             /* Number of columns */
91111   Column *aCol,         /* List of columns */
91112   Select *pSelect       /* SELECT used to determine types and collations */
91113 ){
91114   sqlite3 *db = pParse->db;
91115   NameContext sNC;
91116   Column *pCol;
91117   CollSeq *pColl;
91118   int i;
91119   Expr *p;
91120   struct ExprList_item *a;
91121
91122   assert( pSelect!=0 );
91123   assert( (pSelect->selFlags & SF_Resolved)!=0 );
91124   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91125   if( db->mallocFailed ) return;
91126   memset(&sNC, 0, sizeof(sNC));
91127   sNC.pSrcList = pSelect->pSrc;
91128   a = pSelect->pEList->a;
91129   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91130     p = a[i].pExpr;
91131     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91132     pCol->affinity = sqlite3ExprAffinity(p);
91133     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91134     pColl = sqlite3ExprCollSeq(pParse, p);
91135     if( pColl ){
91136       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91137     }
91138   }
91139 }
91140
91141 /*
91142 ** Given a SELECT statement, generate a Table structure that describes
91143 ** the result set of that SELECT.
91144 */
91145 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91146   Table *pTab;
91147   sqlite3 *db = pParse->db;
91148   int savedFlags;
91149
91150   savedFlags = db->flags;
91151   db->flags &= ~SQLITE_FullColNames;
91152   db->flags |= SQLITE_ShortColNames;
91153   sqlite3SelectPrep(pParse, pSelect, 0);
91154   if( pParse->nErr ) return 0;
91155   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91156   db->flags = savedFlags;
91157   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91158   if( pTab==0 ){
91159     return 0;
91160   }
91161   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91162   ** is disabled */
91163   assert( db->lookaside.bEnabled==0 );
91164   pTab->nRef = 1;
91165   pTab->zName = 0;
91166   pTab->nRowEst = 1000000;
91167   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91168   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91169   pTab->iPKey = -1;
91170   if( db->mallocFailed ){
91171     sqlite3DeleteTable(db, pTab);
91172     return 0;
91173   }
91174   return pTab;
91175 }
91176
91177 /*
91178 ** Get a VDBE for the given parser context.  Create a new one if necessary.
91179 ** If an error occurs, return NULL and leave a message in pParse.
91180 */
91181 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91182   Vdbe *v = pParse->pVdbe;
91183   if( v==0 ){
91184     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91185 #ifndef SQLITE_OMIT_TRACE
91186     if( v ){
91187       sqlite3VdbeAddOp0(v, OP_Trace);
91188     }
91189 #endif
91190   }
91191   return v;
91192 }
91193
91194
91195 /*
91196 ** Compute the iLimit and iOffset fields of the SELECT based on the
91197 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
91198 ** that appear in the original SQL statement after the LIMIT and OFFSET
91199 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
91200 ** are the integer memory register numbers for counters used to compute 
91201 ** the limit and offset.  If there is no limit and/or offset, then 
91202 ** iLimit and iOffset are negative.
91203 **
91204 ** This routine changes the values of iLimit and iOffset only if
91205 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
91206 ** iOffset should have been preset to appropriate default values
91207 ** (usually but not always -1) prior to calling this routine.
91208 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91209 ** redefined.  The UNION ALL operator uses this property to force
91210 ** the reuse of the same limit and offset registers across multiple
91211 ** SELECT statements.
91212 */
91213 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91214   Vdbe *v = 0;
91215   int iLimit = 0;
91216   int iOffset;
91217   int addr1, n;
91218   if( p->iLimit ) return;
91219
91220   /* 
91221   ** "LIMIT -1" always shows all rows.  There is some
91222   ** contraversy about what the correct behavior should be.
91223   ** The current implementation interprets "LIMIT 0" to mean
91224   ** no rows.
91225   */
91226   sqlite3ExprCacheClear(pParse);
91227   assert( p->pOffset==0 || p->pLimit!=0 );
91228   if( p->pLimit ){
91229     p->iLimit = iLimit = ++pParse->nMem;
91230     v = sqlite3GetVdbe(pParse);
91231     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
91232     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91233       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91234       VdbeComment((v, "LIMIT counter"));
91235       if( n==0 ){
91236         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91237       }else{
91238         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91239       }
91240     }else{
91241       sqlite3ExprCode(pParse, p->pLimit, iLimit);
91242       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91243       VdbeComment((v, "LIMIT counter"));
91244       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91245     }
91246     if( p->pOffset ){
91247       p->iOffset = iOffset = ++pParse->nMem;
91248       pParse->nMem++;   /* Allocate an extra register for limit+offset */
91249       sqlite3ExprCode(pParse, p->pOffset, iOffset);
91250       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91251       VdbeComment((v, "OFFSET counter"));
91252       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91253       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91254       sqlite3VdbeJumpHere(v, addr1);
91255       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91256       VdbeComment((v, "LIMIT+OFFSET"));
91257       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91258       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91259       sqlite3VdbeJumpHere(v, addr1);
91260     }
91261   }
91262 }
91263
91264 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91265 /*
91266 ** Return the appropriate collating sequence for the iCol-th column of
91267 ** the result set for the compound-select statement "p".  Return NULL if
91268 ** the column has no default collating sequence.
91269 **
91270 ** The collating sequence for the compound select is taken from the
91271 ** left-most term of the select that has a collating sequence.
91272 */
91273 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91274   CollSeq *pRet;
91275   if( p->pPrior ){
91276     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91277   }else{
91278     pRet = 0;
91279   }
91280   assert( iCol>=0 );
91281   if( pRet==0 && iCol<p->pEList->nExpr ){
91282     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91283   }
91284   return pRet;
91285 }
91286 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91287
91288 /* Forward reference */
91289 static int multiSelectOrderBy(
91290   Parse *pParse,        /* Parsing context */
91291   Select *p,            /* The right-most of SELECTs to be coded */
91292   SelectDest *pDest     /* What to do with query results */
91293 );
91294
91295
91296 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91297 /*
91298 ** This routine is called to process a compound query form from
91299 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91300 ** INTERSECT
91301 **
91302 ** "p" points to the right-most of the two queries.  the query on the
91303 ** left is p->pPrior.  The left query could also be a compound query
91304 ** in which case this routine will be called recursively. 
91305 **
91306 ** The results of the total query are to be written into a destination
91307 ** of type eDest with parameter iParm.
91308 **
91309 ** Example 1:  Consider a three-way compound SQL statement.
91310 **
91311 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91312 **
91313 ** This statement is parsed up as follows:
91314 **
91315 **     SELECT c FROM t3
91316 **      |
91317 **      `----->  SELECT b FROM t2
91318 **                |
91319 **                `------>  SELECT a FROM t1
91320 **
91321 ** The arrows in the diagram above represent the Select.pPrior pointer.
91322 ** So if this routine is called with p equal to the t3 query, then
91323 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
91324 **
91325 ** Notice that because of the way SQLite parses compound SELECTs, the
91326 ** individual selects always group from left to right.
91327 */
91328 static int multiSelect(
91329   Parse *pParse,        /* Parsing context */
91330   Select *p,            /* The right-most of SELECTs to be coded */
91331   SelectDest *pDest     /* What to do with query results */
91332 ){
91333   int rc = SQLITE_OK;   /* Success code from a subroutine */
91334   Select *pPrior;       /* Another SELECT immediately to our left */
91335   Vdbe *v;              /* Generate code to this VDBE */
91336   SelectDest dest;      /* Alternative data destination */
91337   Select *pDelete = 0;  /* Chain of simple selects to delete */
91338   sqlite3 *db;          /* Database connection */
91339 #ifndef SQLITE_OMIT_EXPLAIN
91340   int iSub1;            /* EQP id of left-hand query */
91341   int iSub2;            /* EQP id of right-hand query */
91342 #endif
91343
91344   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
91345   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
91346   */
91347   assert( p && p->pPrior );  /* Calling function guarantees this much */
91348   db = pParse->db;
91349   pPrior = p->pPrior;
91350   assert( pPrior->pRightmost!=pPrior );
91351   assert( pPrior->pRightmost==p->pRightmost );
91352   dest = *pDest;
91353   if( pPrior->pOrderBy ){
91354     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
91355       selectOpName(p->op));
91356     rc = 1;
91357     goto multi_select_end;
91358   }
91359   if( pPrior->pLimit ){
91360     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
91361       selectOpName(p->op));
91362     rc = 1;
91363     goto multi_select_end;
91364   }
91365
91366   v = sqlite3GetVdbe(pParse);
91367   assert( v!=0 );  /* The VDBE already created by calling function */
91368
91369   /* Create the destination temporary table if necessary
91370   */
91371   if( dest.eDest==SRT_EphemTab ){
91372     assert( p->pEList );
91373     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
91374     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91375     dest.eDest = SRT_Table;
91376   }
91377
91378   /* Make sure all SELECTs in the statement have the same number of elements
91379   ** in their result sets.
91380   */
91381   assert( p->pEList && pPrior->pEList );
91382   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
91383     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
91384       " do not have the same number of result columns", selectOpName(p->op));
91385     rc = 1;
91386     goto multi_select_end;
91387   }
91388
91389   /* Compound SELECTs that have an ORDER BY clause are handled separately.
91390   */
91391   if( p->pOrderBy ){
91392     return multiSelectOrderBy(pParse, p, pDest);
91393   }
91394
91395   /* Generate code for the left and right SELECT statements.
91396   */
91397   switch( p->op ){
91398     case TK_ALL: {
91399       int addr = 0;
91400       int nLimit;
91401       assert( !pPrior->pLimit );
91402       pPrior->pLimit = p->pLimit;
91403       pPrior->pOffset = p->pOffset;
91404       explainSetInteger(iSub1, pParse->iNextSelectId);
91405       rc = sqlite3Select(pParse, pPrior, &dest);
91406       p->pLimit = 0;
91407       p->pOffset = 0;
91408       if( rc ){
91409         goto multi_select_end;
91410       }
91411       p->pPrior = 0;
91412       p->iLimit = pPrior->iLimit;
91413       p->iOffset = pPrior->iOffset;
91414       if( p->iLimit ){
91415         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
91416         VdbeComment((v, "Jump ahead if LIMIT reached"));
91417       }
91418       explainSetInteger(iSub2, pParse->iNextSelectId);
91419       rc = sqlite3Select(pParse, p, &dest);
91420       testcase( rc!=SQLITE_OK );
91421       pDelete = p->pPrior;
91422       p->pPrior = pPrior;
91423       p->nSelectRow += pPrior->nSelectRow;
91424       if( pPrior->pLimit
91425        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
91426        && p->nSelectRow > (double)nLimit 
91427       ){
91428         p->nSelectRow = (double)nLimit;
91429       }
91430       if( addr ){
91431         sqlite3VdbeJumpHere(v, addr);
91432       }
91433       break;
91434     }
91435     case TK_EXCEPT:
91436     case TK_UNION: {
91437       int unionTab;    /* Cursor number of the temporary table holding result */
91438       u8 op = 0;       /* One of the SRT_ operations to apply to self */
91439       int priorOp;     /* The SRT_ operation to apply to prior selects */
91440       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
91441       int addr;
91442       SelectDest uniondest;
91443
91444       testcase( p->op==TK_EXCEPT );
91445       testcase( p->op==TK_UNION );
91446       priorOp = SRT_Union;
91447       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
91448         /* We can reuse a temporary table generated by a SELECT to our
91449         ** right.
91450         */
91451         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
91452                                      ** of a 3-way or more compound */
91453         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
91454         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
91455         unionTab = dest.iParm;
91456       }else{
91457         /* We will need to create our own temporary table to hold the
91458         ** intermediate results.
91459         */
91460         unionTab = pParse->nTab++;
91461         assert( p->pOrderBy==0 );
91462         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
91463         assert( p->addrOpenEphm[0] == -1 );
91464         p->addrOpenEphm[0] = addr;
91465         p->pRightmost->selFlags |= SF_UsesEphemeral;
91466         assert( p->pEList );
91467       }
91468
91469       /* Code the SELECT statements to our left
91470       */
91471       assert( !pPrior->pOrderBy );
91472       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
91473       explainSetInteger(iSub1, pParse->iNextSelectId);
91474       rc = sqlite3Select(pParse, pPrior, &uniondest);
91475       if( rc ){
91476         goto multi_select_end;
91477       }
91478
91479       /* Code the current SELECT statement
91480       */
91481       if( p->op==TK_EXCEPT ){
91482         op = SRT_Except;
91483       }else{
91484         assert( p->op==TK_UNION );
91485         op = SRT_Union;
91486       }
91487       p->pPrior = 0;
91488       pLimit = p->pLimit;
91489       p->pLimit = 0;
91490       pOffset = p->pOffset;
91491       p->pOffset = 0;
91492       uniondest.eDest = op;
91493       explainSetInteger(iSub2, pParse->iNextSelectId);
91494       rc = sqlite3Select(pParse, p, &uniondest);
91495       testcase( rc!=SQLITE_OK );
91496       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
91497       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
91498       sqlite3ExprListDelete(db, p->pOrderBy);
91499       pDelete = p->pPrior;
91500       p->pPrior = pPrior;
91501       p->pOrderBy = 0;
91502       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
91503       sqlite3ExprDelete(db, p->pLimit);
91504       p->pLimit = pLimit;
91505       p->pOffset = pOffset;
91506       p->iLimit = 0;
91507       p->iOffset = 0;
91508
91509       /* Convert the data in the temporary table into whatever form
91510       ** it is that we currently need.
91511       */
91512       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
91513       if( dest.eDest!=priorOp ){
91514         int iCont, iBreak, iStart;
91515         assert( p->pEList );
91516         if( dest.eDest==SRT_Output ){
91517           Select *pFirst = p;
91518           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91519           generateColumnNames(pParse, 0, pFirst->pEList);
91520         }
91521         iBreak = sqlite3VdbeMakeLabel(v);
91522         iCont = sqlite3VdbeMakeLabel(v);
91523         computeLimitRegisters(pParse, p, iBreak);
91524         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
91525         iStart = sqlite3VdbeCurrentAddr(v);
91526         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
91527                         0, -1, &dest, iCont, iBreak);
91528         sqlite3VdbeResolveLabel(v, iCont);
91529         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
91530         sqlite3VdbeResolveLabel(v, iBreak);
91531         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
91532       }
91533       break;
91534     }
91535     default: assert( p->op==TK_INTERSECT ); {
91536       int tab1, tab2;
91537       int iCont, iBreak, iStart;
91538       Expr *pLimit, *pOffset;
91539       int addr;
91540       SelectDest intersectdest;
91541       int r1;
91542
91543       /* INTERSECT is different from the others since it requires
91544       ** two temporary tables.  Hence it has its own case.  Begin
91545       ** by allocating the tables we will need.
91546       */
91547       tab1 = pParse->nTab++;
91548       tab2 = pParse->nTab++;
91549       assert( p->pOrderBy==0 );
91550
91551       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
91552       assert( p->addrOpenEphm[0] == -1 );
91553       p->addrOpenEphm[0] = addr;
91554       p->pRightmost->selFlags |= SF_UsesEphemeral;
91555       assert( p->pEList );
91556
91557       /* Code the SELECTs to our left into temporary table "tab1".
91558       */
91559       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
91560       explainSetInteger(iSub1, pParse->iNextSelectId);
91561       rc = sqlite3Select(pParse, pPrior, &intersectdest);
91562       if( rc ){
91563         goto multi_select_end;
91564       }
91565
91566       /* Code the current SELECT into temporary table "tab2"
91567       */
91568       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
91569       assert( p->addrOpenEphm[1] == -1 );
91570       p->addrOpenEphm[1] = addr;
91571       p->pPrior = 0;
91572       pLimit = p->pLimit;
91573       p->pLimit = 0;
91574       pOffset = p->pOffset;
91575       p->pOffset = 0;
91576       intersectdest.iParm = tab2;
91577       explainSetInteger(iSub2, pParse->iNextSelectId);
91578       rc = sqlite3Select(pParse, p, &intersectdest);
91579       testcase( rc!=SQLITE_OK );
91580       pDelete = p->pPrior;
91581       p->pPrior = pPrior;
91582       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
91583       sqlite3ExprDelete(db, p->pLimit);
91584       p->pLimit = pLimit;
91585       p->pOffset = pOffset;
91586
91587       /* Generate code to take the intersection of the two temporary
91588       ** tables.
91589       */
91590       assert( p->pEList );
91591       if( dest.eDest==SRT_Output ){
91592         Select *pFirst = p;
91593         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91594         generateColumnNames(pParse, 0, pFirst->pEList);
91595       }
91596       iBreak = sqlite3VdbeMakeLabel(v);
91597       iCont = sqlite3VdbeMakeLabel(v);
91598       computeLimitRegisters(pParse, p, iBreak);
91599       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
91600       r1 = sqlite3GetTempReg(pParse);
91601       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
91602       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
91603       sqlite3ReleaseTempReg(pParse, r1);
91604       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
91605                       0, -1, &dest, iCont, iBreak);
91606       sqlite3VdbeResolveLabel(v, iCont);
91607       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
91608       sqlite3VdbeResolveLabel(v, iBreak);
91609       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
91610       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
91611       break;
91612     }
91613   }
91614
91615   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
91616
91617   /* Compute collating sequences used by 
91618   ** temporary tables needed to implement the compound select.
91619   ** Attach the KeyInfo structure to all temporary tables.
91620   **
91621   ** This section is run by the right-most SELECT statement only.
91622   ** SELECT statements to the left always skip this part.  The right-most
91623   ** SELECT might also skip this part if it has no ORDER BY clause and
91624   ** no temp tables are required.
91625   */
91626   if( p->selFlags & SF_UsesEphemeral ){
91627     int i;                        /* Loop counter */
91628     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
91629     Select *pLoop;                /* For looping through SELECT statements */
91630     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
91631     int nCol;                     /* Number of columns in result set */
91632
91633     assert( p->pRightmost==p );
91634     nCol = p->pEList->nExpr;
91635     pKeyInfo = sqlite3DbMallocZero(db,
91636                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
91637     if( !pKeyInfo ){
91638       rc = SQLITE_NOMEM;
91639       goto multi_select_end;
91640     }
91641
91642     pKeyInfo->enc = ENC(db);
91643     pKeyInfo->nField = (u16)nCol;
91644
91645     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
91646       *apColl = multiSelectCollSeq(pParse, p, i);
91647       if( 0==*apColl ){
91648         *apColl = db->pDfltColl;
91649       }
91650     }
91651
91652     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
91653       for(i=0; i<2; i++){
91654         int addr = pLoop->addrOpenEphm[i];
91655         if( addr<0 ){
91656           /* If [0] is unused then [1] is also unused.  So we can
91657           ** always safely abort as soon as the first unused slot is found */
91658           assert( pLoop->addrOpenEphm[1]<0 );
91659           break;
91660         }
91661         sqlite3VdbeChangeP2(v, addr, nCol);
91662         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
91663         pLoop->addrOpenEphm[i] = -1;
91664       }
91665     }
91666     sqlite3DbFree(db, pKeyInfo);
91667   }
91668
91669 multi_select_end:
91670   pDest->iMem = dest.iMem;
91671   pDest->nMem = dest.nMem;
91672   sqlite3SelectDelete(db, pDelete);
91673   return rc;
91674 }
91675 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91676
91677 /*
91678 ** Code an output subroutine for a coroutine implementation of a
91679 ** SELECT statment.
91680 **
91681 ** The data to be output is contained in pIn->iMem.  There are
91682 ** pIn->nMem columns to be output.  pDest is where the output should
91683 ** be sent.
91684 **
91685 ** regReturn is the number of the register holding the subroutine
91686 ** return address.
91687 **
91688 ** If regPrev>0 then it is the first register in a vector that
91689 ** records the previous output.  mem[regPrev] is a flag that is false
91690 ** if there has been no previous output.  If regPrev>0 then code is
91691 ** generated to suppress duplicates.  pKeyInfo is used for comparing
91692 ** keys.
91693 **
91694 ** If the LIMIT found in p->iLimit is reached, jump immediately to
91695 ** iBreak.
91696 */
91697 static int generateOutputSubroutine(
91698   Parse *pParse,          /* Parsing context */
91699   Select *p,              /* The SELECT statement */
91700   SelectDest *pIn,        /* Coroutine supplying data */
91701   SelectDest *pDest,      /* Where to send the data */
91702   int regReturn,          /* The return address register */
91703   int regPrev,            /* Previous result register.  No uniqueness if 0 */
91704   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
91705   int p4type,             /* The p4 type for pKeyInfo */
91706   int iBreak              /* Jump here if we hit the LIMIT */
91707 ){
91708   Vdbe *v = pParse->pVdbe;
91709   int iContinue;
91710   int addr;
91711
91712   addr = sqlite3VdbeCurrentAddr(v);
91713   iContinue = sqlite3VdbeMakeLabel(v);
91714
91715   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
91716   */
91717   if( regPrev ){
91718     int j1, j2;
91719     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
91720     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
91721                               (char*)pKeyInfo, p4type);
91722     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
91723     sqlite3VdbeJumpHere(v, j1);
91724     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
91725     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
91726   }
91727   if( pParse->db->mallocFailed ) return 0;
91728
91729   /* Suppress the the first OFFSET entries if there is an OFFSET clause
91730   */
91731   codeOffset(v, p, iContinue);
91732
91733   switch( pDest->eDest ){
91734     /* Store the result as data using a unique key.
91735     */
91736     case SRT_Table:
91737     case SRT_EphemTab: {
91738       int r1 = sqlite3GetTempReg(pParse);
91739       int r2 = sqlite3GetTempReg(pParse);
91740       testcase( pDest->eDest==SRT_Table );
91741       testcase( pDest->eDest==SRT_EphemTab );
91742       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
91743       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
91744       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
91745       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91746       sqlite3ReleaseTempReg(pParse, r2);
91747       sqlite3ReleaseTempReg(pParse, r1);
91748       break;
91749     }
91750
91751 #ifndef SQLITE_OMIT_SUBQUERY
91752     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
91753     ** then there should be a single item on the stack.  Write this
91754     ** item into the set table with bogus data.
91755     */
91756     case SRT_Set: {
91757       int r1;
91758       assert( pIn->nMem==1 );
91759       p->affinity = 
91760          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
91761       r1 = sqlite3GetTempReg(pParse);
91762       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
91763       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
91764       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
91765       sqlite3ReleaseTempReg(pParse, r1);
91766       break;
91767     }
91768
91769 #if 0  /* Never occurs on an ORDER BY query */
91770     /* If any row exist in the result set, record that fact and abort.
91771     */
91772     case SRT_Exists: {
91773       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
91774       /* The LIMIT clause will terminate the loop for us */
91775       break;
91776     }
91777 #endif
91778
91779     /* If this is a scalar select that is part of an expression, then
91780     ** store the results in the appropriate memory cell and break out
91781     ** of the scan loop.
91782     */
91783     case SRT_Mem: {
91784       assert( pIn->nMem==1 );
91785       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
91786       /* The LIMIT clause will jump out of the loop for us */
91787       break;
91788     }
91789 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
91790
91791     /* The results are stored in a sequence of registers
91792     ** starting at pDest->iMem.  Then the co-routine yields.
91793     */
91794     case SRT_Coroutine: {
91795       if( pDest->iMem==0 ){
91796         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
91797         pDest->nMem = pIn->nMem;
91798       }
91799       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
91800       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91801       break;
91802     }
91803
91804     /* If none of the above, then the result destination must be
91805     ** SRT_Output.  This routine is never called with any other
91806     ** destination other than the ones handled above or SRT_Output.
91807     **
91808     ** For SRT_Output, results are stored in a sequence of registers.  
91809     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
91810     ** return the next row of result.
91811     */
91812     default: {
91813       assert( pDest->eDest==SRT_Output );
91814       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
91815       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
91816       break;
91817     }
91818   }
91819
91820   /* Jump to the end of the loop if the LIMIT is reached.
91821   */
91822   if( p->iLimit ){
91823     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
91824   }
91825
91826   /* Generate the subroutine return
91827   */
91828   sqlite3VdbeResolveLabel(v, iContinue);
91829   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
91830
91831   return addr;
91832 }
91833
91834 /*
91835 ** Alternative compound select code generator for cases when there
91836 ** is an ORDER BY clause.
91837 **
91838 ** We assume a query of the following form:
91839 **
91840 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
91841 **
91842 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
91843 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
91844 ** co-routines.  Then run the co-routines in parallel and merge the results
91845 ** into the output.  In addition to the two coroutines (called selectA and
91846 ** selectB) there are 7 subroutines:
91847 **
91848 **    outA:    Move the output of the selectA coroutine into the output
91849 **             of the compound query.
91850 **
91851 **    outB:    Move the output of the selectB coroutine into the output
91852 **             of the compound query.  (Only generated for UNION and
91853 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
91854 **             appears only in B.)
91855 **
91856 **    AltB:    Called when there is data from both coroutines and A<B.
91857 **
91858 **    AeqB:    Called when there is data from both coroutines and A==B.
91859 **
91860 **    AgtB:    Called when there is data from both coroutines and A>B.
91861 **
91862 **    EofA:    Called when data is exhausted from selectA.
91863 **
91864 **    EofB:    Called when data is exhausted from selectB.
91865 **
91866 ** The implementation of the latter five subroutines depend on which 
91867 ** <operator> is used:
91868 **
91869 **
91870 **             UNION ALL         UNION            EXCEPT          INTERSECT
91871 **          -------------  -----------------  --------------  -----------------
91872 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
91873 **
91874 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
91875 **
91876 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
91877 **
91878 **   EofA:   outB, nextB      outB, nextB          halt             halt
91879 **
91880 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
91881 **
91882 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
91883 ** causes an immediate jump to EofA and an EOF on B following nextB causes
91884 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
91885 ** following nextX causes a jump to the end of the select processing.
91886 **
91887 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
91888 ** within the output subroutine.  The regPrev register set holds the previously
91889 ** output value.  A comparison is made against this value and the output
91890 ** is skipped if the next results would be the same as the previous.
91891 **
91892 ** The implementation plan is to implement the two coroutines and seven
91893 ** subroutines first, then put the control logic at the bottom.  Like this:
91894 **
91895 **          goto Init
91896 **     coA: coroutine for left query (A)
91897 **     coB: coroutine for right query (B)
91898 **    outA: output one row of A
91899 **    outB: output one row of B (UNION and UNION ALL only)
91900 **    EofA: ...
91901 **    EofB: ...
91902 **    AltB: ...
91903 **    AeqB: ...
91904 **    AgtB: ...
91905 **    Init: initialize coroutine registers
91906 **          yield coA
91907 **          if eof(A) goto EofA
91908 **          yield coB
91909 **          if eof(B) goto EofB
91910 **    Cmpr: Compare A, B
91911 **          Jump AltB, AeqB, AgtB
91912 **     End: ...
91913 **
91914 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
91915 ** actually called using Gosub and they do not Return.  EofA and EofB loop
91916 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
91917 ** and AgtB jump to either L2 or to one of EofA or EofB.
91918 */
91919 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91920 static int multiSelectOrderBy(
91921   Parse *pParse,        /* Parsing context */
91922   Select *p,            /* The right-most of SELECTs to be coded */
91923   SelectDest *pDest     /* What to do with query results */
91924 ){
91925   int i, j;             /* Loop counters */
91926   Select *pPrior;       /* Another SELECT immediately to our left */
91927   Vdbe *v;              /* Generate code to this VDBE */
91928   SelectDest destA;     /* Destination for coroutine A */
91929   SelectDest destB;     /* Destination for coroutine B */
91930   int regAddrA;         /* Address register for select-A coroutine */
91931   int regEofA;          /* Flag to indicate when select-A is complete */
91932   int regAddrB;         /* Address register for select-B coroutine */
91933   int regEofB;          /* Flag to indicate when select-B is complete */
91934   int addrSelectA;      /* Address of the select-A coroutine */
91935   int addrSelectB;      /* Address of the select-B coroutine */
91936   int regOutA;          /* Address register for the output-A subroutine */
91937   int regOutB;          /* Address register for the output-B subroutine */
91938   int addrOutA;         /* Address of the output-A subroutine */
91939   int addrOutB = 0;     /* Address of the output-B subroutine */
91940   int addrEofA;         /* Address of the select-A-exhausted subroutine */
91941   int addrEofB;         /* Address of the select-B-exhausted subroutine */
91942   int addrAltB;         /* Address of the A<B subroutine */
91943   int addrAeqB;         /* Address of the A==B subroutine */
91944   int addrAgtB;         /* Address of the A>B subroutine */
91945   int regLimitA;        /* Limit register for select-A */
91946   int regLimitB;        /* Limit register for select-A */
91947   int regPrev;          /* A range of registers to hold previous output */
91948   int savedLimit;       /* Saved value of p->iLimit */
91949   int savedOffset;      /* Saved value of p->iOffset */
91950   int labelCmpr;        /* Label for the start of the merge algorithm */
91951   int labelEnd;         /* Label for the end of the overall SELECT stmt */
91952   int j1;               /* Jump instructions that get retargetted */
91953   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
91954   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
91955   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
91956   sqlite3 *db;          /* Database connection */
91957   ExprList *pOrderBy;   /* The ORDER BY clause */
91958   int nOrderBy;         /* Number of terms in the ORDER BY clause */
91959   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
91960 #ifndef SQLITE_OMIT_EXPLAIN
91961   int iSub1;            /* EQP id of left-hand query */
91962   int iSub2;            /* EQP id of right-hand query */
91963 #endif
91964
91965   assert( p->pOrderBy!=0 );
91966   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
91967   db = pParse->db;
91968   v = pParse->pVdbe;
91969   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
91970   labelEnd = sqlite3VdbeMakeLabel(v);
91971   labelCmpr = sqlite3VdbeMakeLabel(v);
91972
91973
91974   /* Patch up the ORDER BY clause
91975   */
91976   op = p->op;  
91977   pPrior = p->pPrior;
91978   assert( pPrior->pOrderBy==0 );
91979   pOrderBy = p->pOrderBy;
91980   assert( pOrderBy );
91981   nOrderBy = pOrderBy->nExpr;
91982
91983   /* For operators other than UNION ALL we have to make sure that
91984   ** the ORDER BY clause covers every term of the result set.  Add
91985   ** terms to the ORDER BY clause as necessary.
91986   */
91987   if( op!=TK_ALL ){
91988     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
91989       struct ExprList_item *pItem;
91990       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
91991         assert( pItem->iCol>0 );
91992         if( pItem->iCol==i ) break;
91993       }
91994       if( j==nOrderBy ){
91995         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
91996         if( pNew==0 ) return SQLITE_NOMEM;
91997         pNew->flags |= EP_IntValue;
91998         pNew->u.iValue = i;
91999         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
92000         pOrderBy->a[nOrderBy++].iCol = (u16)i;
92001       }
92002     }
92003   }
92004
92005   /* Compute the comparison permutation and keyinfo that is used with
92006   ** the permutation used to determine if the next
92007   ** row of results comes from selectA or selectB.  Also add explicit
92008   ** collations to the ORDER BY clause terms so that when the subqueries
92009   ** to the right and the left are evaluated, they use the correct
92010   ** collation.
92011   */
92012   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92013   if( aPermute ){
92014     struct ExprList_item *pItem;
92015     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92016       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
92017       aPermute[i] = pItem->iCol - 1;
92018     }
92019     pKeyMerge =
92020       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92021     if( pKeyMerge ){
92022       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92023       pKeyMerge->nField = (u16)nOrderBy;
92024       pKeyMerge->enc = ENC(db);
92025       for(i=0; i<nOrderBy; i++){
92026         CollSeq *pColl;
92027         Expr *pTerm = pOrderBy->a[i].pExpr;
92028         if( pTerm->flags & EP_ExpCollate ){
92029           pColl = pTerm->pColl;
92030         }else{
92031           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92032           pTerm->flags |= EP_ExpCollate;
92033           pTerm->pColl = pColl;
92034         }
92035         pKeyMerge->aColl[i] = pColl;
92036         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92037       }
92038     }
92039   }else{
92040     pKeyMerge = 0;
92041   }
92042
92043   /* Reattach the ORDER BY clause to the query.
92044   */
92045   p->pOrderBy = pOrderBy;
92046   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92047
92048   /* Allocate a range of temporary registers and the KeyInfo needed
92049   ** for the logic that removes duplicate result rows when the
92050   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92051   */
92052   if( op==TK_ALL ){
92053     regPrev = 0;
92054   }else{
92055     int nExpr = p->pEList->nExpr;
92056     assert( nOrderBy>=nExpr || db->mallocFailed );
92057     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92058     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92059     pKeyDup = sqlite3DbMallocZero(db,
92060                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92061     if( pKeyDup ){
92062       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92063       pKeyDup->nField = (u16)nExpr;
92064       pKeyDup->enc = ENC(db);
92065       for(i=0; i<nExpr; i++){
92066         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92067         pKeyDup->aSortOrder[i] = 0;
92068       }
92069     }
92070   }
92071  
92072   /* Separate the left and the right query from one another
92073   */
92074   p->pPrior = 0;
92075   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92076   if( pPrior->pPrior==0 ){
92077     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92078   }
92079
92080   /* Compute the limit registers */
92081   computeLimitRegisters(pParse, p, labelEnd);
92082   if( p->iLimit && op==TK_ALL ){
92083     regLimitA = ++pParse->nMem;
92084     regLimitB = ++pParse->nMem;
92085     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92086                                   regLimitA);
92087     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92088   }else{
92089     regLimitA = regLimitB = 0;
92090   }
92091   sqlite3ExprDelete(db, p->pLimit);
92092   p->pLimit = 0;
92093   sqlite3ExprDelete(db, p->pOffset);
92094   p->pOffset = 0;
92095
92096   regAddrA = ++pParse->nMem;
92097   regEofA = ++pParse->nMem;
92098   regAddrB = ++pParse->nMem;
92099   regEofB = ++pParse->nMem;
92100   regOutA = ++pParse->nMem;
92101   regOutB = ++pParse->nMem;
92102   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92103   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92104
92105   /* Jump past the various subroutines and coroutines to the main
92106   ** merge loop
92107   */
92108   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92109   addrSelectA = sqlite3VdbeCurrentAddr(v);
92110
92111
92112   /* Generate a coroutine to evaluate the SELECT statement to the
92113   ** left of the compound operator - the "A" select.
92114   */
92115   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92116   pPrior->iLimit = regLimitA;
92117   explainSetInteger(iSub1, pParse->iNextSelectId);
92118   sqlite3Select(pParse, pPrior, &destA);
92119   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92120   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92121   VdbeNoopComment((v, "End coroutine for left SELECT"));
92122
92123   /* Generate a coroutine to evaluate the SELECT statement on 
92124   ** the right - the "B" select
92125   */
92126   addrSelectB = sqlite3VdbeCurrentAddr(v);
92127   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92128   savedLimit = p->iLimit;
92129   savedOffset = p->iOffset;
92130   p->iLimit = regLimitB;
92131   p->iOffset = 0;  
92132   explainSetInteger(iSub2, pParse->iNextSelectId);
92133   sqlite3Select(pParse, p, &destB);
92134   p->iLimit = savedLimit;
92135   p->iOffset = savedOffset;
92136   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92137   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92138   VdbeNoopComment((v, "End coroutine for right SELECT"));
92139
92140   /* Generate a subroutine that outputs the current row of the A
92141   ** select as the next output row of the compound select.
92142   */
92143   VdbeNoopComment((v, "Output routine for A"));
92144   addrOutA = generateOutputSubroutine(pParse,
92145                  p, &destA, pDest, regOutA,
92146                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92147   
92148   /* Generate a subroutine that outputs the current row of the B
92149   ** select as the next output row of the compound select.
92150   */
92151   if( op==TK_ALL || op==TK_UNION ){
92152     VdbeNoopComment((v, "Output routine for B"));
92153     addrOutB = generateOutputSubroutine(pParse,
92154                  p, &destB, pDest, regOutB,
92155                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92156   }
92157
92158   /* Generate a subroutine to run when the results from select A
92159   ** are exhausted and only data in select B remains.
92160   */
92161   VdbeNoopComment((v, "eof-A subroutine"));
92162   if( op==TK_EXCEPT || op==TK_INTERSECT ){
92163     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92164   }else{  
92165     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92166     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92167     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92168     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92169     p->nSelectRow += pPrior->nSelectRow;
92170   }
92171
92172   /* Generate a subroutine to run when the results from select B
92173   ** are exhausted and only data in select A remains.
92174   */
92175   if( op==TK_INTERSECT ){
92176     addrEofB = addrEofA;
92177     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92178   }else{  
92179     VdbeNoopComment((v, "eof-B subroutine"));
92180     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92181     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92182     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92183     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92184   }
92185
92186   /* Generate code to handle the case of A<B
92187   */
92188   VdbeNoopComment((v, "A-lt-B subroutine"));
92189   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92190   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92191   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92192   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92193
92194   /* Generate code to handle the case of A==B
92195   */
92196   if( op==TK_ALL ){
92197     addrAeqB = addrAltB;
92198   }else if( op==TK_INTERSECT ){
92199     addrAeqB = addrAltB;
92200     addrAltB++;
92201   }else{
92202     VdbeNoopComment((v, "A-eq-B subroutine"));
92203     addrAeqB =
92204     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92205     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92206     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92207   }
92208
92209   /* Generate code to handle the case of A>B
92210   */
92211   VdbeNoopComment((v, "A-gt-B subroutine"));
92212   addrAgtB = sqlite3VdbeCurrentAddr(v);
92213   if( op==TK_ALL || op==TK_UNION ){
92214     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92215   }
92216   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92217   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92218   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92219
92220   /* This code runs once to initialize everything.
92221   */
92222   sqlite3VdbeJumpHere(v, j1);
92223   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92224   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92225   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92226   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92227   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92228   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92229
92230   /* Implement the main merge loop
92231   */
92232   sqlite3VdbeResolveLabel(v, labelCmpr);
92233   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92234   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92235                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92236   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92237
92238   /* Release temporary registers
92239   */
92240   if( regPrev ){
92241     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92242   }
92243
92244   /* Jump to the this point in order to terminate the query.
92245   */
92246   sqlite3VdbeResolveLabel(v, labelEnd);
92247
92248   /* Set the number of output columns
92249   */
92250   if( pDest->eDest==SRT_Output ){
92251     Select *pFirst = pPrior;
92252     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92253     generateColumnNames(pParse, 0, pFirst->pEList);
92254   }
92255
92256   /* Reassembly the compound query so that it will be freed correctly
92257   ** by the calling function */
92258   if( p->pPrior ){
92259     sqlite3SelectDelete(db, p->pPrior);
92260   }
92261   p->pPrior = pPrior;
92262
92263   /*** TBD:  Insert subroutine calls to close cursors on incomplete
92264   **** subqueries ****/
92265   explainComposite(pParse, p->op, iSub1, iSub2, 0);
92266   return SQLITE_OK;
92267 }
92268 #endif
92269
92270 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92271 /* Forward Declarations */
92272 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92273 static void substSelect(sqlite3*, Select *, int, ExprList *);
92274
92275 /*
92276 ** Scan through the expression pExpr.  Replace every reference to
92277 ** a column in table number iTable with a copy of the iColumn-th
92278 ** entry in pEList.  (But leave references to the ROWID column 
92279 ** unchanged.)
92280 **
92281 ** This routine is part of the flattening procedure.  A subquery
92282 ** whose result set is defined by pEList appears as entry in the
92283 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
92284 ** FORM clause entry is iTable.  This routine make the necessary 
92285 ** changes to pExpr so that it refers directly to the source table
92286 ** of the subquery rather the result set of the subquery.
92287 */
92288 static Expr *substExpr(
92289   sqlite3 *db,        /* Report malloc errors to this connection */
92290   Expr *pExpr,        /* Expr in which substitution occurs */
92291   int iTable,         /* Table to be substituted */
92292   ExprList *pEList    /* Substitute expressions */
92293 ){
92294   if( pExpr==0 ) return 0;
92295   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92296     if( pExpr->iColumn<0 ){
92297       pExpr->op = TK_NULL;
92298     }else{
92299       Expr *pNew;
92300       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92301       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92302       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92303       if( pNew && pExpr->pColl ){
92304         pNew->pColl = pExpr->pColl;
92305       }
92306       sqlite3ExprDelete(db, pExpr);
92307       pExpr = pNew;
92308     }
92309   }else{
92310     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92311     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92312     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92313       substSelect(db, pExpr->x.pSelect, iTable, pEList);
92314     }else{
92315       substExprList(db, pExpr->x.pList, iTable, pEList);
92316     }
92317   }
92318   return pExpr;
92319 }
92320 static void substExprList(
92321   sqlite3 *db,         /* Report malloc errors here */
92322   ExprList *pList,     /* List to scan and in which to make substitutes */
92323   int iTable,          /* Table to be substituted */
92324   ExprList *pEList     /* Substitute values */
92325 ){
92326   int i;
92327   if( pList==0 ) return;
92328   for(i=0; i<pList->nExpr; i++){
92329     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92330   }
92331 }
92332 static void substSelect(
92333   sqlite3 *db,         /* Report malloc errors here */
92334   Select *p,           /* SELECT statement in which to make substitutions */
92335   int iTable,          /* Table to be replaced */
92336   ExprList *pEList     /* Substitute values */
92337 ){
92338   SrcList *pSrc;
92339   struct SrcList_item *pItem;
92340   int i;
92341   if( !p ) return;
92342   substExprList(db, p->pEList, iTable, pEList);
92343   substExprList(db, p->pGroupBy, iTable, pEList);
92344   substExprList(db, p->pOrderBy, iTable, pEList);
92345   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
92346   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
92347   substSelect(db, p->pPrior, iTable, pEList);
92348   pSrc = p->pSrc;
92349   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
92350   if( ALWAYS(pSrc) ){
92351     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
92352       substSelect(db, pItem->pSelect, iTable, pEList);
92353     }
92354   }
92355 }
92356 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92357
92358 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92359 /*
92360 ** This routine attempts to flatten subqueries in order to speed
92361 ** execution.  It returns 1 if it makes changes and 0 if no flattening
92362 ** occurs.
92363 **
92364 ** To understand the concept of flattening, consider the following
92365 ** query:
92366 **
92367 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
92368 **
92369 ** The default way of implementing this query is to execute the
92370 ** subquery first and store the results in a temporary table, then
92371 ** run the outer query on that temporary table.  This requires two
92372 ** passes over the data.  Furthermore, because the temporary table
92373 ** has no indices, the WHERE clause on the outer query cannot be
92374 ** optimized.
92375 **
92376 ** This routine attempts to rewrite queries such as the above into
92377 ** a single flat select, like this:
92378 **
92379 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
92380 **
92381 ** The code generated for this simpification gives the same result
92382 ** but only has to scan the data once.  And because indices might 
92383 ** exist on the table t1, a complete scan of the data might be
92384 ** avoided.
92385 **
92386 ** Flattening is only attempted if all of the following are true:
92387 **
92388 **   (1)  The subquery and the outer query do not both use aggregates.
92389 **
92390 **   (2)  The subquery is not an aggregate or the outer query is not a join.
92391 **
92392 **   (3)  The subquery is not the right operand of a left outer join
92393 **        (Originally ticket #306.  Strengthened by ticket #3300)
92394 **
92395 **   (4)  The subquery is not DISTINCT.
92396 **
92397 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
92398 **        sub-queries that were excluded from this optimization. Restriction 
92399 **        (4) has since been expanded to exclude all DISTINCT subqueries.
92400 **
92401 **   (6)  The subquery does not use aggregates or the outer query is not
92402 **        DISTINCT.
92403 **
92404 **   (7)  The subquery has a FROM clause.
92405 **
92406 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
92407 **
92408 **   (9)  The subquery does not use LIMIT or the outer query does not use
92409 **        aggregates.
92410 **
92411 **  (10)  The subquery does not use aggregates or the outer query does not
92412 **        use LIMIT.
92413 **
92414 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
92415 **
92416 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
92417 **        a separate restriction deriving from ticket #350.
92418 **
92419 **  (13)  The subquery and outer query do not both use LIMIT.
92420 **
92421 **  (14)  The subquery does not use OFFSET.
92422 **
92423 **  (15)  The outer query is not part of a compound select or the
92424 **        subquery does not have a LIMIT clause.
92425 **        (See ticket #2339 and ticket [02a8e81d44]).
92426 **
92427 **  (16)  The outer query is not an aggregate or the subquery does
92428 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
92429 **        until we introduced the group_concat() function.  
92430 **
92431 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
92432 **        compound clause made up entirely of non-aggregate queries, and 
92433 **        the parent query:
92434 **
92435 **          * is not itself part of a compound select,
92436 **          * is not an aggregate or DISTINCT query, and
92437 **          * has no other tables or sub-selects in the FROM clause.
92438 **
92439 **        The parent and sub-query may contain WHERE clauses. Subject to
92440 **        rules (11), (13) and (14), they may also contain ORDER BY,
92441 **        LIMIT and OFFSET clauses.
92442 **
92443 **  (18)  If the sub-query is a compound select, then all terms of the
92444 **        ORDER by clause of the parent must be simple references to 
92445 **        columns of the sub-query.
92446 **
92447 **  (19)  The subquery does not use LIMIT or the outer query does not
92448 **        have a WHERE clause.
92449 **
92450 **  (20)  If the sub-query is a compound select, then it must not use
92451 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
92452 **        somewhat by saying that the terms of the ORDER BY clause must
92453 **        appear as unmodified result columns in the outer query.  But
92454 **        have other optimizations in mind to deal with that case.
92455 **
92456 **  (21)  The subquery does not use LIMIT or the outer query is not
92457 **        DISTINCT.  (See ticket [752e1646fc]).
92458 **
92459 ** In this routine, the "p" parameter is a pointer to the outer query.
92460 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
92461 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
92462 **
92463 ** If flattening is not attempted, this routine is a no-op and returns 0.
92464 ** If flattening is attempted this routine returns 1.
92465 **
92466 ** All of the expression analysis must occur on both the outer query and
92467 ** the subquery before this routine runs.
92468 */
92469 static int flattenSubquery(
92470   Parse *pParse,       /* Parsing context */
92471   Select *p,           /* The parent or outer SELECT statement */
92472   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
92473   int isAgg,           /* True if outer SELECT uses aggregate functions */
92474   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
92475 ){
92476   const char *zSavedAuthContext = pParse->zAuthContext;
92477   Select *pParent;
92478   Select *pSub;       /* The inner query or "subquery" */
92479   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
92480   SrcList *pSrc;      /* The FROM clause of the outer query */
92481   SrcList *pSubSrc;   /* The FROM clause of the subquery */
92482   ExprList *pList;    /* The result set of the outer query */
92483   int iParent;        /* VDBE cursor number of the pSub result set temp table */
92484   int i;              /* Loop counter */
92485   Expr *pWhere;                    /* The WHERE clause */
92486   struct SrcList_item *pSubitem;   /* The subquery */
92487   sqlite3 *db = pParse->db;
92488
92489   /* Check to see if flattening is permitted.  Return 0 if not.
92490   */
92491   assert( p!=0 );
92492   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
92493   if( db->flags & SQLITE_QueryFlattener ) return 0;
92494   pSrc = p->pSrc;
92495   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
92496   pSubitem = &pSrc->a[iFrom];
92497   iParent = pSubitem->iCursor;
92498   pSub = pSubitem->pSelect;
92499   assert( pSub!=0 );
92500   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
92501   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
92502   pSubSrc = pSub->pSrc;
92503   assert( pSubSrc );
92504   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
92505   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
92506   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
92507   ** became arbitrary expressions, we were forced to add restrictions (13)
92508   ** and (14). */
92509   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
92510   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
92511   if( p->pRightmost && pSub->pLimit ){
92512     return 0;                                            /* Restriction (15) */
92513   }
92514   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
92515   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
92516   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
92517      return 0;         /* Restrictions (8)(9) */
92518   }
92519   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
92520      return 0;         /* Restriction (6)  */
92521   }
92522   if( p->pOrderBy && pSub->pOrderBy ){
92523      return 0;                                           /* Restriction (11) */
92524   }
92525   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
92526   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
92527   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
92528      return 0;         /* Restriction (21) */
92529   }
92530
92531   /* OBSOLETE COMMENT 1:
92532   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
92533   ** not used as the right operand of an outer join.  Examples of why this
92534   ** is not allowed:
92535   **
92536   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
92537   **
92538   ** If we flatten the above, we would get
92539   **
92540   **         (t1 LEFT OUTER JOIN t2) JOIN t3
92541   **
92542   ** which is not at all the same thing.
92543   **
92544   ** OBSOLETE COMMENT 2:
92545   ** Restriction 12:  If the subquery is the right operand of a left outer
92546   ** join, make sure the subquery has no WHERE clause.
92547   ** An examples of why this is not allowed:
92548   **
92549   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
92550   **
92551   ** If we flatten the above, we would get
92552   **
92553   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
92554   **
92555   ** But the t2.x>0 test will always fail on a NULL row of t2, which
92556   ** effectively converts the OUTER JOIN into an INNER JOIN.
92557   **
92558   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
92559   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
92560   ** is fraught with danger.  Best to avoid the whole thing.  If the
92561   ** subquery is the right term of a LEFT JOIN, then do not flatten.
92562   */
92563   if( (pSubitem->jointype & JT_OUTER)!=0 ){
92564     return 0;
92565   }
92566
92567   /* Restriction 17: If the sub-query is a compound SELECT, then it must
92568   ** use only the UNION ALL operator. And none of the simple select queries
92569   ** that make up the compound SELECT are allowed to be aggregate or distinct
92570   ** queries.
92571   */
92572   if( pSub->pPrior ){
92573     if( pSub->pOrderBy ){
92574       return 0;  /* Restriction 20 */
92575     }
92576     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
92577       return 0;
92578     }
92579     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
92580       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92581       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92582       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
92583        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
92584        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
92585       ){
92586         return 0;
92587       }
92588     }
92589
92590     /* Restriction 18. */
92591     if( p->pOrderBy ){
92592       int ii;
92593       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
92594         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
92595       }
92596     }
92597   }
92598
92599   /***** If we reach this point, flattening is permitted. *****/
92600
92601   /* Authorize the subquery */
92602   pParse->zAuthContext = pSubitem->zName;
92603   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
92604   pParse->zAuthContext = zSavedAuthContext;
92605
92606   /* If the sub-query is a compound SELECT statement, then (by restrictions
92607   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
92608   ** be of the form:
92609   **
92610   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
92611   **
92612   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
92613   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
92614   ** OFFSET clauses and joins them to the left-hand-side of the original
92615   ** using UNION ALL operators. In this case N is the number of simple
92616   ** select statements in the compound sub-query.
92617   **
92618   ** Example:
92619   **
92620   **     SELECT a+1 FROM (
92621   **        SELECT x FROM tab
92622   **        UNION ALL
92623   **        SELECT y FROM tab
92624   **        UNION ALL
92625   **        SELECT abs(z*2) FROM tab2
92626   **     ) WHERE a!=5 ORDER BY 1
92627   **
92628   ** Transformed into:
92629   **
92630   **     SELECT x+1 FROM tab WHERE x+1!=5
92631   **     UNION ALL
92632   **     SELECT y+1 FROM tab WHERE y+1!=5
92633   **     UNION ALL
92634   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
92635   **     ORDER BY 1
92636   **
92637   ** We call this the "compound-subquery flattening".
92638   */
92639   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
92640     Select *pNew;
92641     ExprList *pOrderBy = p->pOrderBy;
92642     Expr *pLimit = p->pLimit;
92643     Select *pPrior = p->pPrior;
92644     p->pOrderBy = 0;
92645     p->pSrc = 0;
92646     p->pPrior = 0;
92647     p->pLimit = 0;
92648     pNew = sqlite3SelectDup(db, p, 0);
92649     p->pLimit = pLimit;
92650     p->pOrderBy = pOrderBy;
92651     p->pSrc = pSrc;
92652     p->op = TK_ALL;
92653     p->pRightmost = 0;
92654     if( pNew==0 ){
92655       pNew = pPrior;
92656     }else{
92657       pNew->pPrior = pPrior;
92658       pNew->pRightmost = 0;
92659     }
92660     p->pPrior = pNew;
92661     if( db->mallocFailed ) return 1;
92662   }
92663
92664   /* Begin flattening the iFrom-th entry of the FROM clause 
92665   ** in the outer query.
92666   */
92667   pSub = pSub1 = pSubitem->pSelect;
92668
92669   /* Delete the transient table structure associated with the
92670   ** subquery
92671   */
92672   sqlite3DbFree(db, pSubitem->zDatabase);
92673   sqlite3DbFree(db, pSubitem->zName);
92674   sqlite3DbFree(db, pSubitem->zAlias);
92675   pSubitem->zDatabase = 0;
92676   pSubitem->zName = 0;
92677   pSubitem->zAlias = 0;
92678   pSubitem->pSelect = 0;
92679
92680   /* Defer deleting the Table object associated with the
92681   ** subquery until code generation is
92682   ** complete, since there may still exist Expr.pTab entries that
92683   ** refer to the subquery even after flattening.  Ticket #3346.
92684   **
92685   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
92686   */
92687   if( ALWAYS(pSubitem->pTab!=0) ){
92688     Table *pTabToDel = pSubitem->pTab;
92689     if( pTabToDel->nRef==1 ){
92690       Parse *pToplevel = sqlite3ParseToplevel(pParse);
92691       pTabToDel->pNextZombie = pToplevel->pZombieTab;
92692       pToplevel->pZombieTab = pTabToDel;
92693     }else{
92694       pTabToDel->nRef--;
92695     }
92696     pSubitem->pTab = 0;
92697   }
92698
92699   /* The following loop runs once for each term in a compound-subquery
92700   ** flattening (as described above).  If we are doing a different kind
92701   ** of flattening - a flattening other than a compound-subquery flattening -
92702   ** then this loop only runs once.
92703   **
92704   ** This loop moves all of the FROM elements of the subquery into the
92705   ** the FROM clause of the outer query.  Before doing this, remember
92706   ** the cursor number for the original outer query FROM element in
92707   ** iParent.  The iParent cursor will never be used.  Subsequent code
92708   ** will scan expressions looking for iParent references and replace
92709   ** those references with expressions that resolve to the subquery FROM
92710   ** elements we are now copying in.
92711   */
92712   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
92713     int nSubSrc;
92714     u8 jointype = 0;
92715     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
92716     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
92717     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
92718
92719     if( pSrc ){
92720       assert( pParent==p );  /* First time through the loop */
92721       jointype = pSubitem->jointype;
92722     }else{
92723       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
92724       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
92725       if( pSrc==0 ){
92726         assert( db->mallocFailed );
92727         break;
92728       }
92729     }
92730
92731     /* The subquery uses a single slot of the FROM clause of the outer
92732     ** query.  If the subquery has more than one element in its FROM clause,
92733     ** then expand the outer query to make space for it to hold all elements
92734     ** of the subquery.
92735     **
92736     ** Example:
92737     **
92738     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
92739     **
92740     ** The outer query has 3 slots in its FROM clause.  One slot of the
92741     ** outer query (the middle slot) is used by the subquery.  The next
92742     ** block of code will expand the out query to 4 slots.  The middle
92743     ** slot is expanded to two slots in order to make space for the
92744     ** two elements in the FROM clause of the subquery.
92745     */
92746     if( nSubSrc>1 ){
92747       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
92748       if( db->mallocFailed ){
92749         break;
92750       }
92751     }
92752
92753     /* Transfer the FROM clause terms from the subquery into the
92754     ** outer query.
92755     */
92756     for(i=0; i<nSubSrc; i++){
92757       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
92758       pSrc->a[i+iFrom] = pSubSrc->a[i];
92759       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
92760     }
92761     pSrc->a[iFrom].jointype = jointype;
92762   
92763     /* Now begin substituting subquery result set expressions for 
92764     ** references to the iParent in the outer query.
92765     ** 
92766     ** Example:
92767     **
92768     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
92769     **   \                     \_____________ subquery __________/          /
92770     **    \_____________________ outer query ______________________________/
92771     **
92772     ** We look at every expression in the outer query and every place we see
92773     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
92774     */
92775     pList = pParent->pEList;
92776     for(i=0; i<pList->nExpr; i++){
92777       if( pList->a[i].zName==0 ){
92778         const char *zSpan = pList->a[i].zSpan;
92779         if( ALWAYS(zSpan) ){
92780           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
92781         }
92782       }
92783     }
92784     substExprList(db, pParent->pEList, iParent, pSub->pEList);
92785     if( isAgg ){
92786       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
92787       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92788     }
92789     if( pSub->pOrderBy ){
92790       assert( pParent->pOrderBy==0 );
92791       pParent->pOrderBy = pSub->pOrderBy;
92792       pSub->pOrderBy = 0;
92793     }else if( pParent->pOrderBy ){
92794       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
92795     }
92796     if( pSub->pWhere ){
92797       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
92798     }else{
92799       pWhere = 0;
92800     }
92801     if( subqueryIsAgg ){
92802       assert( pParent->pHaving==0 );
92803       pParent->pHaving = pParent->pWhere;
92804       pParent->pWhere = pWhere;
92805       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
92806       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
92807                                   sqlite3ExprDup(db, pSub->pHaving, 0));
92808       assert( pParent->pGroupBy==0 );
92809       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
92810     }else{
92811       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
92812       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
92813     }
92814   
92815     /* The flattened query is distinct if either the inner or the
92816     ** outer query is distinct. 
92817     */
92818     pParent->selFlags |= pSub->selFlags & SF_Distinct;
92819   
92820     /*
92821     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
92822     **
92823     ** One is tempted to try to add a and b to combine the limits.  But this
92824     ** does not work if either limit is negative.
92825     */
92826     if( pSub->pLimit ){
92827       pParent->pLimit = pSub->pLimit;
92828       pSub->pLimit = 0;
92829     }
92830   }
92831
92832   /* Finially, delete what is left of the subquery and return
92833   ** success.
92834   */
92835   sqlite3SelectDelete(db, pSub1);
92836
92837   return 1;
92838 }
92839 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92840
92841 /*
92842 ** Analyze the SELECT statement passed as an argument to see if it
92843 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
92844 ** it is, or 0 otherwise. At present, a query is considered to be
92845 ** a min()/max() query if:
92846 **
92847 **   1. There is a single object in the FROM clause.
92848 **
92849 **   2. There is a single expression in the result set, and it is
92850 **      either min(x) or max(x), where x is a column reference.
92851 */
92852 static u8 minMaxQuery(Select *p){
92853   Expr *pExpr;
92854   ExprList *pEList = p->pEList;
92855
92856   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
92857   pExpr = pEList->a[0].pExpr;
92858   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
92859   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
92860   pEList = pExpr->x.pList;
92861   if( pEList==0 || pEList->nExpr!=1 ) return 0;
92862   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
92863   assert( !ExprHasProperty(pExpr, EP_IntValue) );
92864   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
92865     return WHERE_ORDERBY_MIN;
92866   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
92867     return WHERE_ORDERBY_MAX;
92868   }
92869   return WHERE_ORDERBY_NORMAL;
92870 }
92871
92872 /*
92873 ** The select statement passed as the first argument is an aggregate query.
92874 ** The second argment is the associated aggregate-info object. This 
92875 ** function tests if the SELECT is of the form:
92876 **
92877 **   SELECT count(*) FROM <tbl>
92878 **
92879 ** where table is a database table, not a sub-select or view. If the query
92880 ** does match this pattern, then a pointer to the Table object representing
92881 ** <tbl> is returned. Otherwise, 0 is returned.
92882 */
92883 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
92884   Table *pTab;
92885   Expr *pExpr;
92886
92887   assert( !p->pGroupBy );
92888
92889   if( p->pWhere || p->pEList->nExpr!=1 
92890    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
92891   ){
92892     return 0;
92893   }
92894   pTab = p->pSrc->a[0].pTab;
92895   pExpr = p->pEList->a[0].pExpr;
92896   assert( pTab && !pTab->pSelect && pExpr );
92897
92898   if( IsVirtual(pTab) ) return 0;
92899   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
92900   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
92901   if( pExpr->flags&EP_Distinct ) return 0;
92902
92903   return pTab;
92904 }
92905
92906 /*
92907 ** If the source-list item passed as an argument was augmented with an
92908 ** INDEXED BY clause, then try to locate the specified index. If there
92909 ** was such a clause and the named index cannot be found, return 
92910 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
92911 ** pFrom->pIndex and return SQLITE_OK.
92912 */
92913 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
92914   if( pFrom->pTab && pFrom->zIndex ){
92915     Table *pTab = pFrom->pTab;
92916     char *zIndex = pFrom->zIndex;
92917     Index *pIdx;
92918     for(pIdx=pTab->pIndex; 
92919         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
92920         pIdx=pIdx->pNext
92921     );
92922     if( !pIdx ){
92923       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
92924       pParse->checkSchema = 1;
92925       return SQLITE_ERROR;
92926     }
92927     pFrom->pIndex = pIdx;
92928   }
92929   return SQLITE_OK;
92930 }
92931
92932 /*
92933 ** This routine is a Walker callback for "expanding" a SELECT statement.
92934 ** "Expanding" means to do the following:
92935 **
92936 **    (1)  Make sure VDBE cursor numbers have been assigned to every
92937 **         element of the FROM clause.
92938 **
92939 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
92940 **         defines FROM clause.  When views appear in the FROM clause,
92941 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
92942 **         that implements the view.  A copy is made of the view's SELECT
92943 **         statement so that we can freely modify or delete that statement
92944 **         without worrying about messing up the presistent representation
92945 **         of the view.
92946 **
92947 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
92948 **         on joins and the ON and USING clause of joins.
92949 **
92950 **    (4)  Scan the list of columns in the result set (pEList) looking
92951 **         for instances of the "*" operator or the TABLE.* operator.
92952 **         If found, expand each "*" to be every column in every table
92953 **         and TABLE.* to be every column in TABLE.
92954 **
92955 */
92956 static int selectExpander(Walker *pWalker, Select *p){
92957   Parse *pParse = pWalker->pParse;
92958   int i, j, k;
92959   SrcList *pTabList;
92960   ExprList *pEList;
92961   struct SrcList_item *pFrom;
92962   sqlite3 *db = pParse->db;
92963
92964   if( db->mallocFailed  ){
92965     return WRC_Abort;
92966   }
92967   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
92968     return WRC_Prune;
92969   }
92970   p->selFlags |= SF_Expanded;
92971   pTabList = p->pSrc;
92972   pEList = p->pEList;
92973
92974   /* Make sure cursor numbers have been assigned to all entries in
92975   ** the FROM clause of the SELECT statement.
92976   */
92977   sqlite3SrcListAssignCursors(pParse, pTabList);
92978
92979   /* Look up every table named in the FROM clause of the select.  If
92980   ** an entry of the FROM clause is a subquery instead of a table or view,
92981   ** then create a transient table structure to describe the subquery.
92982   */
92983   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
92984     Table *pTab;
92985     if( pFrom->pTab!=0 ){
92986       /* This statement has already been prepared.  There is no need
92987       ** to go further. */
92988       assert( i==0 );
92989       return WRC_Prune;
92990     }
92991     if( pFrom->zName==0 ){
92992 #ifndef SQLITE_OMIT_SUBQUERY
92993       Select *pSel = pFrom->pSelect;
92994       /* A sub-query in the FROM clause of a SELECT */
92995       assert( pSel!=0 );
92996       assert( pFrom->pTab==0 );
92997       sqlite3WalkSelect(pWalker, pSel);
92998       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
92999       if( pTab==0 ) return WRC_Abort;
93000       pTab->nRef = 1;
93001       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
93002       while( pSel->pPrior ){ pSel = pSel->pPrior; }
93003       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
93004       pTab->iPKey = -1;
93005       pTab->nRowEst = 1000000;
93006       pTab->tabFlags |= TF_Ephemeral;
93007 #endif
93008     }else{
93009       /* An ordinary table or view name in the FROM clause */
93010       assert( pFrom->pTab==0 );
93011       pFrom->pTab = pTab = 
93012         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93013       if( pTab==0 ) return WRC_Abort;
93014       pTab->nRef++;
93015 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93016       if( pTab->pSelect || IsVirtual(pTab) ){
93017         /* We reach here if the named table is a really a view */
93018         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93019         assert( pFrom->pSelect==0 );
93020         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93021         sqlite3WalkSelect(pWalker, pFrom->pSelect);
93022       }
93023 #endif
93024     }
93025
93026     /* Locate the index named by the INDEXED BY clause, if any. */
93027     if( sqlite3IndexedByLookup(pParse, pFrom) ){
93028       return WRC_Abort;
93029     }
93030   }
93031
93032   /* Process NATURAL keywords, and ON and USING clauses of joins.
93033   */
93034   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93035     return WRC_Abort;
93036   }
93037
93038   /* For every "*" that occurs in the column list, insert the names of
93039   ** all columns in all tables.  And for every TABLE.* insert the names
93040   ** of all columns in TABLE.  The parser inserted a special expression
93041   ** with the TK_ALL operator for each "*" that it found in the column list.
93042   ** The following code just has to locate the TK_ALL expressions and expand
93043   ** each one to the list of all columns in all tables.
93044   **
93045   ** The first loop just checks to see if there are any "*" operators
93046   ** that need expanding.
93047   */
93048   for(k=0; k<pEList->nExpr; k++){
93049     Expr *pE = pEList->a[k].pExpr;
93050     if( pE->op==TK_ALL ) break;
93051     assert( pE->op!=TK_DOT || pE->pRight!=0 );
93052     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93053     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93054   }
93055   if( k<pEList->nExpr ){
93056     /*
93057     ** If we get here it means the result set contains one or more "*"
93058     ** operators that need to be expanded.  Loop through each expression
93059     ** in the result set and expand them one by one.
93060     */
93061     struct ExprList_item *a = pEList->a;
93062     ExprList *pNew = 0;
93063     int flags = pParse->db->flags;
93064     int longNames = (flags & SQLITE_FullColNames)!=0
93065                       && (flags & SQLITE_ShortColNames)==0;
93066
93067     for(k=0; k<pEList->nExpr; k++){
93068       Expr *pE = a[k].pExpr;
93069       assert( pE->op!=TK_DOT || pE->pRight!=0 );
93070       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93071         /* This particular expression does not need to be expanded.
93072         */
93073         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93074         if( pNew ){
93075           pNew->a[pNew->nExpr-1].zName = a[k].zName;
93076           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93077           a[k].zName = 0;
93078           a[k].zSpan = 0;
93079         }
93080         a[k].pExpr = 0;
93081       }else{
93082         /* This expression is a "*" or a "TABLE.*" and needs to be
93083         ** expanded. */
93084         int tableSeen = 0;      /* Set to 1 when TABLE matches */
93085         char *zTName;            /* text of name of TABLE */
93086         if( pE->op==TK_DOT ){
93087           assert( pE->pLeft!=0 );
93088           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93089           zTName = pE->pLeft->u.zToken;
93090         }else{
93091           zTName = 0;
93092         }
93093         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93094           Table *pTab = pFrom->pTab;
93095           char *zTabName = pFrom->zAlias;
93096           if( zTabName==0 ){
93097             zTabName = pTab->zName;
93098           }
93099           if( db->mallocFailed ) break;
93100           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93101             continue;
93102           }
93103           tableSeen = 1;
93104           for(j=0; j<pTab->nCol; j++){
93105             Expr *pExpr, *pRight;
93106             char *zName = pTab->aCol[j].zName;
93107             char *zColname;  /* The computed column name */
93108             char *zToFree;   /* Malloced string that needs to be freed */
93109             Token sColname;  /* Computed column name as a token */
93110
93111             /* If a column is marked as 'hidden' (currently only possible
93112             ** for virtual tables), do not include it in the expanded
93113             ** result-set list.
93114             */
93115             if( IsHiddenColumn(&pTab->aCol[j]) ){
93116               assert(IsVirtual(pTab));
93117               continue;
93118             }
93119
93120             if( i>0 && zTName==0 ){
93121               if( (pFrom->jointype & JT_NATURAL)!=0
93122                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93123               ){
93124                 /* In a NATURAL join, omit the join columns from the 
93125                 ** table to the right of the join */
93126                 continue;
93127               }
93128               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93129                 /* In a join with a USING clause, omit columns in the
93130                 ** using clause from the table on the right. */
93131                 continue;
93132               }
93133             }
93134             pRight = sqlite3Expr(db, TK_ID, zName);
93135             zColname = zName;
93136             zToFree = 0;
93137             if( longNames || pTabList->nSrc>1 ){
93138               Expr *pLeft;
93139               pLeft = sqlite3Expr(db, TK_ID, zTabName);
93140               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93141               if( longNames ){
93142                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93143                 zToFree = zColname;
93144               }
93145             }else{
93146               pExpr = pRight;
93147             }
93148             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93149             sColname.z = zColname;
93150             sColname.n = sqlite3Strlen30(zColname);
93151             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93152             sqlite3DbFree(db, zToFree);
93153           }
93154         }
93155         if( !tableSeen ){
93156           if( zTName ){
93157             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93158           }else{
93159             sqlite3ErrorMsg(pParse, "no tables specified");
93160           }
93161         }
93162       }
93163     }
93164     sqlite3ExprListDelete(db, pEList);
93165     p->pEList = pNew;
93166   }
93167 #if SQLITE_MAX_COLUMN
93168   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93169     sqlite3ErrorMsg(pParse, "too many columns in result set");
93170   }
93171 #endif
93172   return WRC_Continue;
93173 }
93174
93175 /*
93176 ** No-op routine for the parse-tree walker.
93177 **
93178 ** When this routine is the Walker.xExprCallback then expression trees
93179 ** are walked without any actions being taken at each node.  Presumably,
93180 ** when this routine is used for Walker.xExprCallback then 
93181 ** Walker.xSelectCallback is set to do something useful for every 
93182 ** subquery in the parser tree.
93183 */
93184 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93185   UNUSED_PARAMETER2(NotUsed, NotUsed2);
93186   return WRC_Continue;
93187 }
93188
93189 /*
93190 ** This routine "expands" a SELECT statement and all of its subqueries.
93191 ** For additional information on what it means to "expand" a SELECT
93192 ** statement, see the comment on the selectExpand worker callback above.
93193 **
93194 ** Expanding a SELECT statement is the first step in processing a
93195 ** SELECT statement.  The SELECT statement must be expanded before
93196 ** name resolution is performed.
93197 **
93198 ** If anything goes wrong, an error message is written into pParse.
93199 ** The calling function can detect the problem by looking at pParse->nErr
93200 ** and/or pParse->db->mallocFailed.
93201 */
93202 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93203   Walker w;
93204   w.xSelectCallback = selectExpander;
93205   w.xExprCallback = exprWalkNoop;
93206   w.pParse = pParse;
93207   sqlite3WalkSelect(&w, pSelect);
93208 }
93209
93210
93211 #ifndef SQLITE_OMIT_SUBQUERY
93212 /*
93213 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93214 ** interface.
93215 **
93216 ** For each FROM-clause subquery, add Column.zType and Column.zColl
93217 ** information to the Table structure that represents the result set
93218 ** of that subquery.
93219 **
93220 ** The Table structure that represents the result set was constructed
93221 ** by selectExpander() but the type and collation information was omitted
93222 ** at that point because identifiers had not yet been resolved.  This
93223 ** routine is called after identifier resolution.
93224 */
93225 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93226   Parse *pParse;
93227   int i;
93228   SrcList *pTabList;
93229   struct SrcList_item *pFrom;
93230
93231   assert( p->selFlags & SF_Resolved );
93232   if( (p->selFlags & SF_HasTypeInfo)==0 ){
93233     p->selFlags |= SF_HasTypeInfo;
93234     pParse = pWalker->pParse;
93235     pTabList = p->pSrc;
93236     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93237       Table *pTab = pFrom->pTab;
93238       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93239         /* A sub-query in the FROM clause of a SELECT */
93240         Select *pSel = pFrom->pSelect;
93241         assert( pSel );
93242         while( pSel->pPrior ) pSel = pSel->pPrior;
93243         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93244       }
93245     }
93246   }
93247   return WRC_Continue;
93248 }
93249 #endif
93250
93251
93252 /*
93253 ** This routine adds datatype and collating sequence information to
93254 ** the Table structures of all FROM-clause subqueries in a
93255 ** SELECT statement.
93256 **
93257 ** Use this routine after name resolution.
93258 */
93259 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93260 #ifndef SQLITE_OMIT_SUBQUERY
93261   Walker w;
93262   w.xSelectCallback = selectAddSubqueryTypeInfo;
93263   w.xExprCallback = exprWalkNoop;
93264   w.pParse = pParse;
93265   sqlite3WalkSelect(&w, pSelect);
93266 #endif
93267 }
93268
93269
93270 /*
93271 ** This routine sets of a SELECT statement for processing.  The
93272 ** following is accomplished:
93273 **
93274 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
93275 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
93276 **     *  ON and USING clauses are shifted into WHERE statements
93277 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
93278 **     *  Identifiers in expression are matched to tables.
93279 **
93280 ** This routine acts recursively on all subqueries within the SELECT.
93281 */
93282 SQLITE_PRIVATE void sqlite3SelectPrep(
93283   Parse *pParse,         /* The parser context */
93284   Select *p,             /* The SELECT statement being coded. */
93285   NameContext *pOuterNC  /* Name context for container */
93286 ){
93287   sqlite3 *db;
93288   if( NEVER(p==0) ) return;
93289   db = pParse->db;
93290   if( p->selFlags & SF_HasTypeInfo ) return;
93291   sqlite3SelectExpand(pParse, p);
93292   if( pParse->nErr || db->mallocFailed ) return;
93293   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93294   if( pParse->nErr || db->mallocFailed ) return;
93295   sqlite3SelectAddTypeInfo(pParse, p);
93296 }
93297
93298 /*
93299 ** Reset the aggregate accumulator.
93300 **
93301 ** The aggregate accumulator is a set of memory cells that hold
93302 ** intermediate results while calculating an aggregate.  This
93303 ** routine simply stores NULLs in all of those memory cells.
93304 */
93305 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93306   Vdbe *v = pParse->pVdbe;
93307   int i;
93308   struct AggInfo_func *pFunc;
93309   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93310     return;
93311   }
93312   for(i=0; i<pAggInfo->nColumn; i++){
93313     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93314   }
93315   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93316     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93317     if( pFunc->iDistinct>=0 ){
93318       Expr *pE = pFunc->pExpr;
93319       assert( !ExprHasProperty(pE, EP_xIsSelect) );
93320       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93321         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93322            "argument");
93323         pFunc->iDistinct = -1;
93324       }else{
93325         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93326         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93327                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93328       }
93329     }
93330   }
93331 }
93332
93333 /*
93334 ** Invoke the OP_AggFinalize opcode for every aggregate function
93335 ** in the AggInfo structure.
93336 */
93337 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
93338   Vdbe *v = pParse->pVdbe;
93339   int i;
93340   struct AggInfo_func *pF;
93341   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93342     ExprList *pList = pF->pExpr->x.pList;
93343     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93344     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
93345                       (void*)pF->pFunc, P4_FUNCDEF);
93346   }
93347 }
93348
93349 /*
93350 ** Update the accumulator memory cells for an aggregate based on
93351 ** the current cursor position.
93352 */
93353 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
93354   Vdbe *v = pParse->pVdbe;
93355   int i;
93356   struct AggInfo_func *pF;
93357   struct AggInfo_col *pC;
93358
93359   pAggInfo->directMode = 1;
93360   sqlite3ExprCacheClear(pParse);
93361   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93362     int nArg;
93363     int addrNext = 0;
93364     int regAgg;
93365     ExprList *pList = pF->pExpr->x.pList;
93366     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93367     if( pList ){
93368       nArg = pList->nExpr;
93369       regAgg = sqlite3GetTempRange(pParse, nArg);
93370       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
93371     }else{
93372       nArg = 0;
93373       regAgg = 0;
93374     }
93375     if( pF->iDistinct>=0 ){
93376       addrNext = sqlite3VdbeMakeLabel(v);
93377       assert( nArg==1 );
93378       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
93379     }
93380     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
93381       CollSeq *pColl = 0;
93382       struct ExprList_item *pItem;
93383       int j;
93384       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
93385       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
93386         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93387       }
93388       if( !pColl ){
93389         pColl = pParse->db->pDfltColl;
93390       }
93391       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93392     }
93393     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
93394                       (void*)pF->pFunc, P4_FUNCDEF);
93395     sqlite3VdbeChangeP5(v, (u8)nArg);
93396     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
93397     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
93398     if( addrNext ){
93399       sqlite3VdbeResolveLabel(v, addrNext);
93400       sqlite3ExprCacheClear(pParse);
93401     }
93402   }
93403
93404   /* Before populating the accumulator registers, clear the column cache.
93405   ** Otherwise, if any of the required column values are already present 
93406   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
93407   ** to pC->iMem. But by the time the value is used, the original register
93408   ** may have been used, invalidating the underlying buffer holding the
93409   ** text or blob value. See ticket [883034dcb5].
93410   **
93411   ** Another solution would be to change the OP_SCopy used to copy cached
93412   ** values to an OP_Copy.
93413   */
93414   sqlite3ExprCacheClear(pParse);
93415   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
93416     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
93417   }
93418   pAggInfo->directMode = 0;
93419   sqlite3ExprCacheClear(pParse);
93420 }
93421
93422 /*
93423 ** Add a single OP_Explain instruction to the VDBE to explain a simple
93424 ** count(*) query ("SELECT count(*) FROM pTab").
93425 */
93426 #ifndef SQLITE_OMIT_EXPLAIN
93427 static void explainSimpleCount(
93428   Parse *pParse,                  /* Parse context */
93429   Table *pTab,                    /* Table being queried */
93430   Index *pIdx                     /* Index used to optimize scan, or NULL */
93431 ){
93432   if( pParse->explain==2 ){
93433     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
93434         pTab->zName, 
93435         pIdx ? "USING COVERING INDEX " : "",
93436         pIdx ? pIdx->zName : "",
93437         pTab->nRowEst
93438     );
93439     sqlite3VdbeAddOp4(
93440         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
93441     );
93442   }
93443 }
93444 #else
93445 # define explainSimpleCount(a,b,c)
93446 #endif
93447
93448 /*
93449 ** Generate code for the SELECT statement given in the p argument.  
93450 **
93451 ** The results are distributed in various ways depending on the
93452 ** contents of the SelectDest structure pointed to by argument pDest
93453 ** as follows:
93454 **
93455 **     pDest->eDest    Result
93456 **     ------------    -------------------------------------------
93457 **     SRT_Output      Generate a row of output (using the OP_ResultRow
93458 **                     opcode) for each row in the result set.
93459 **
93460 **     SRT_Mem         Only valid if the result is a single column.
93461 **                     Store the first column of the first result row
93462 **                     in register pDest->iParm then abandon the rest
93463 **                     of the query.  This destination implies "LIMIT 1".
93464 **
93465 **     SRT_Set         The result must be a single column.  Store each
93466 **                     row of result as the key in table pDest->iParm. 
93467 **                     Apply the affinity pDest->affinity before storing
93468 **                     results.  Used to implement "IN (SELECT ...)".
93469 **
93470 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
93471 **
93472 **     SRT_Except      Remove results from the temporary table pDest->iParm.
93473 **
93474 **     SRT_Table       Store results in temporary table pDest->iParm.
93475 **                     This is like SRT_EphemTab except that the table
93476 **                     is assumed to already be open.
93477 **
93478 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
93479 **                     the result there. The cursor is left open after
93480 **                     returning.  This is like SRT_Table except that
93481 **                     this destination uses OP_OpenEphemeral to create
93482 **                     the table first.
93483 **
93484 **     SRT_Coroutine   Generate a co-routine that returns a new row of
93485 **                     results each time it is invoked.  The entry point
93486 **                     of the co-routine is stored in register pDest->iParm.
93487 **
93488 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
93489 **                     set is not empty.
93490 **
93491 **     SRT_Discard     Throw the results away.  This is used by SELECT
93492 **                     statements within triggers whose only purpose is
93493 **                     the side-effects of functions.
93494 **
93495 ** This routine returns the number of errors.  If any errors are
93496 ** encountered, then an appropriate error message is left in
93497 ** pParse->zErrMsg.
93498 **
93499 ** This routine does NOT free the Select structure passed in.  The
93500 ** calling function needs to do that.
93501 */
93502 SQLITE_PRIVATE int sqlite3Select(
93503   Parse *pParse,         /* The parser context */
93504   Select *p,             /* The SELECT statement being coded. */
93505   SelectDest *pDest      /* What to do with the query results */
93506 ){
93507   int i, j;              /* Loop counters */
93508   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
93509   Vdbe *v;               /* The virtual machine under construction */
93510   int isAgg;             /* True for select lists like "count(*)" */
93511   ExprList *pEList;      /* List of columns to extract. */
93512   SrcList *pTabList;     /* List of tables to select from */
93513   Expr *pWhere;          /* The WHERE clause.  May be NULL */
93514   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
93515   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
93516   Expr *pHaving;         /* The HAVING clause.  May be NULL */
93517   int isDistinct;        /* True if the DISTINCT keyword is present */
93518   int distinct;          /* Table to use for the distinct set */
93519   int rc = 1;            /* Value to return from this function */
93520   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
93521   AggInfo sAggInfo;      /* Information used by aggregate queries */
93522   int iEnd;              /* Address of the end of the query */
93523   sqlite3 *db;           /* The database connection */
93524
93525 #ifndef SQLITE_OMIT_EXPLAIN
93526   int iRestoreSelectId = pParse->iSelectId;
93527   pParse->iSelectId = pParse->iNextSelectId++;
93528 #endif
93529
93530   db = pParse->db;
93531   if( p==0 || db->mallocFailed || pParse->nErr ){
93532     return 1;
93533   }
93534   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
93535   memset(&sAggInfo, 0, sizeof(sAggInfo));
93536
93537   if( IgnorableOrderby(pDest) ){
93538     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
93539            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
93540     /* If ORDER BY makes no difference in the output then neither does
93541     ** DISTINCT so it can be removed too. */
93542     sqlite3ExprListDelete(db, p->pOrderBy);
93543     p->pOrderBy = 0;
93544     p->selFlags &= ~SF_Distinct;
93545   }
93546   sqlite3SelectPrep(pParse, p, 0);
93547   pOrderBy = p->pOrderBy;
93548   pTabList = p->pSrc;
93549   pEList = p->pEList;
93550   if( pParse->nErr || db->mallocFailed ){
93551     goto select_end;
93552   }
93553   isAgg = (p->selFlags & SF_Aggregate)!=0;
93554   assert( pEList!=0 );
93555
93556   /* Begin generating code.
93557   */
93558   v = sqlite3GetVdbe(pParse);
93559   if( v==0 ) goto select_end;
93560
93561   /* If writing to memory or generating a set
93562   ** only a single column may be output.
93563   */
93564 #ifndef SQLITE_OMIT_SUBQUERY
93565   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
93566     goto select_end;
93567   }
93568 #endif
93569
93570   /* Generate code for all sub-queries in the FROM clause
93571   */
93572 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93573   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
93574     struct SrcList_item *pItem = &pTabList->a[i];
93575     SelectDest dest;
93576     Select *pSub = pItem->pSelect;
93577     int isAggSub;
93578
93579     if( pSub==0 || pItem->isPopulated ) continue;
93580
93581     /* Increment Parse.nHeight by the height of the largest expression
93582     ** tree refered to by this, the parent select. The child select
93583     ** may contain expression trees of at most
93584     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
93585     ** more conservative than necessary, but much easier than enforcing
93586     ** an exact limit.
93587     */
93588     pParse->nHeight += sqlite3SelectExprHeight(p);
93589
93590     /* Check to see if the subquery can be absorbed into the parent. */
93591     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
93592     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
93593       if( isAggSub ){
93594         isAgg = 1;
93595         p->selFlags |= SF_Aggregate;
93596       }
93597       i = -1;
93598     }else{
93599       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
93600       assert( pItem->isPopulated==0 );
93601       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
93602       sqlite3Select(pParse, pSub, &dest);
93603       pItem->isPopulated = 1;
93604       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
93605     }
93606     if( /*pParse->nErr ||*/ db->mallocFailed ){
93607       goto select_end;
93608     }
93609     pParse->nHeight -= sqlite3SelectExprHeight(p);
93610     pTabList = p->pSrc;
93611     if( !IgnorableOrderby(pDest) ){
93612       pOrderBy = p->pOrderBy;
93613     }
93614   }
93615   pEList = p->pEList;
93616 #endif
93617   pWhere = p->pWhere;
93618   pGroupBy = p->pGroupBy;
93619   pHaving = p->pHaving;
93620   isDistinct = (p->selFlags & SF_Distinct)!=0;
93621
93622 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93623   /* If there is are a sequence of queries, do the earlier ones first.
93624   */
93625   if( p->pPrior ){
93626     if( p->pRightmost==0 ){
93627       Select *pLoop, *pRight = 0;
93628       int cnt = 0;
93629       int mxSelect;
93630       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
93631         pLoop->pRightmost = p;
93632         pLoop->pNext = pRight;
93633         pRight = pLoop;
93634       }
93635       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
93636       if( mxSelect && cnt>mxSelect ){
93637         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
93638         goto select_end;
93639       }
93640     }
93641     rc = multiSelect(pParse, p, pDest);
93642     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
93643     return rc;
93644   }
93645 #endif
93646
93647   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
93648   ** GROUP BY might use an index, DISTINCT never does.
93649   */
93650   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
93651   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
93652     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
93653     pGroupBy = p->pGroupBy;
93654     p->selFlags &= ~SF_Distinct;
93655   }
93656
93657   /* If there is both a GROUP BY and an ORDER BY clause and they are
93658   ** identical, then disable the ORDER BY clause since the GROUP BY
93659   ** will cause elements to come out in the correct order.  This is
93660   ** an optimization - the correct answer should result regardless.
93661   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
93662   ** to disable this optimization for testing purposes.
93663   */
93664   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
93665          && (db->flags & SQLITE_GroupByOrder)==0 ){
93666     pOrderBy = 0;
93667   }
93668
93669   /* If there is an ORDER BY clause, then this sorting
93670   ** index might end up being unused if the data can be 
93671   ** extracted in pre-sorted order.  If that is the case, then the
93672   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
93673   ** we figure out that the sorting index is not needed.  The addrSortIndex
93674   ** variable is used to facilitate that change.
93675   */
93676   if( pOrderBy ){
93677     KeyInfo *pKeyInfo;
93678     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
93679     pOrderBy->iECursor = pParse->nTab++;
93680     p->addrOpenEphm[2] = addrSortIndex =
93681       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
93682                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
93683                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93684   }else{
93685     addrSortIndex = -1;
93686   }
93687
93688   /* If the output is destined for a temporary table, open that table.
93689   */
93690   if( pDest->eDest==SRT_EphemTab ){
93691     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
93692   }
93693
93694   /* Set the limiter.
93695   */
93696   iEnd = sqlite3VdbeMakeLabel(v);
93697   p->nSelectRow = (double)LARGEST_INT64;
93698   computeLimitRegisters(pParse, p, iEnd);
93699
93700   /* Open a virtual index to use for the distinct set.
93701   */
93702   if( p->selFlags & SF_Distinct ){
93703     KeyInfo *pKeyInfo;
93704     assert( isAgg || pGroupBy );
93705     distinct = pParse->nTab++;
93706     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
93707     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
93708                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93709     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93710   }else{
93711     distinct = -1;
93712   }
93713
93714   /* Aggregate and non-aggregate queries are handled differently */
93715   if( !isAgg && pGroupBy==0 ){
93716     /* This case is for non-aggregate queries
93717     ** Begin the database scan
93718     */
93719     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
93720     if( pWInfo==0 ) goto select_end;
93721     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
93722
93723     /* If sorting index that was created by a prior OP_OpenEphemeral 
93724     ** instruction ended up not being needed, then change the OP_OpenEphemeral
93725     ** into an OP_Noop.
93726     */
93727     if( addrSortIndex>=0 && pOrderBy==0 ){
93728       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
93729       p->addrOpenEphm[2] = -1;
93730     }
93731
93732     /* Use the standard inner loop
93733     */
93734     assert(!isDistinct);
93735     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
93736                     pWInfo->iContinue, pWInfo->iBreak);
93737
93738     /* End the database scan loop.
93739     */
93740     sqlite3WhereEnd(pWInfo);
93741   }else{
93742     /* This is the processing for aggregate queries */
93743     NameContext sNC;    /* Name context for processing aggregate information */
93744     int iAMem;          /* First Mem address for storing current GROUP BY */
93745     int iBMem;          /* First Mem address for previous GROUP BY */
93746     int iUseFlag;       /* Mem address holding flag indicating that at least
93747                         ** one row of the input to the aggregator has been
93748                         ** processed */
93749     int iAbortFlag;     /* Mem address which causes query abort if positive */
93750     int groupBySort;    /* Rows come from source in GROUP BY order */
93751     int addrEnd;        /* End of processing for this SELECT */
93752
93753     /* Remove any and all aliases between the result set and the
93754     ** GROUP BY clause.
93755     */
93756     if( pGroupBy ){
93757       int k;                        /* Loop counter */
93758       struct ExprList_item *pItem;  /* For looping over expression in a list */
93759
93760       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
93761         pItem->iAlias = 0;
93762       }
93763       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
93764         pItem->iAlias = 0;
93765       }
93766       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
93767     }else{
93768       p->nSelectRow = (double)1;
93769     }
93770
93771  
93772     /* Create a label to jump to when we want to abort the query */
93773     addrEnd = sqlite3VdbeMakeLabel(v);
93774
93775     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
93776     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
93777     ** SELECT statement.
93778     */
93779     memset(&sNC, 0, sizeof(sNC));
93780     sNC.pParse = pParse;
93781     sNC.pSrcList = pTabList;
93782     sNC.pAggInfo = &sAggInfo;
93783     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
93784     sAggInfo.pGroupBy = pGroupBy;
93785     sqlite3ExprAnalyzeAggList(&sNC, pEList);
93786     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
93787     if( pHaving ){
93788       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
93789     }
93790     sAggInfo.nAccumulator = sAggInfo.nColumn;
93791     for(i=0; i<sAggInfo.nFunc; i++){
93792       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
93793       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
93794     }
93795     if( db->mallocFailed ) goto select_end;
93796
93797     /* Processing for aggregates with GROUP BY is very different and
93798     ** much more complex than aggregates without a GROUP BY.
93799     */
93800     if( pGroupBy ){
93801       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
93802       int j1;             /* A-vs-B comparision jump */
93803       int addrOutputRow;  /* Start of subroutine that outputs a result row */
93804       int regOutputRow;   /* Return address register for output subroutine */
93805       int addrSetAbort;   /* Set the abort flag and return */
93806       int addrTopOfLoop;  /* Top of the input loop */
93807       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
93808       int addrReset;      /* Subroutine for resetting the accumulator */
93809       int regReset;       /* Return address register for reset subroutine */
93810
93811       /* If there is a GROUP BY clause we might need a sorting index to
93812       ** implement it.  Allocate that sorting index now.  If it turns out
93813       ** that we do not need it after all, the OpenEphemeral instruction
93814       ** will be converted into a Noop.  
93815       */
93816       sAggInfo.sortingIdx = pParse->nTab++;
93817       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
93818       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
93819           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
93820           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93821
93822       /* Initialize memory locations used by GROUP BY aggregate processing
93823       */
93824       iUseFlag = ++pParse->nMem;
93825       iAbortFlag = ++pParse->nMem;
93826       regOutputRow = ++pParse->nMem;
93827       addrOutputRow = sqlite3VdbeMakeLabel(v);
93828       regReset = ++pParse->nMem;
93829       addrReset = sqlite3VdbeMakeLabel(v);
93830       iAMem = pParse->nMem + 1;
93831       pParse->nMem += pGroupBy->nExpr;
93832       iBMem = pParse->nMem + 1;
93833       pParse->nMem += pGroupBy->nExpr;
93834       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
93835       VdbeComment((v, "clear abort flag"));
93836       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
93837       VdbeComment((v, "indicate accumulator empty"));
93838
93839       /* Begin a loop that will extract all source rows in GROUP BY order.
93840       ** This might involve two separate loops with an OP_Sort in between, or
93841       ** it might be a single loop that uses an index to extract information
93842       ** in the right order to begin with.
93843       */
93844       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
93845       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
93846       if( pWInfo==0 ) goto select_end;
93847       if( pGroupBy==0 ){
93848         /* The optimizer is able to deliver rows in group by order so
93849         ** we do not have to sort.  The OP_OpenEphemeral table will be
93850         ** cancelled later because we still need to use the pKeyInfo
93851         */
93852         pGroupBy = p->pGroupBy;
93853         groupBySort = 0;
93854       }else{
93855         /* Rows are coming out in undetermined order.  We have to push
93856         ** each row into a sorting index, terminate the first loop,
93857         ** then loop over the sorting index in order to get the output
93858         ** in sorted order
93859         */
93860         int regBase;
93861         int regRecord;
93862         int nCol;
93863         int nGroupBy;
93864
93865         explainTempTable(pParse, 
93866             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
93867
93868         groupBySort = 1;
93869         nGroupBy = pGroupBy->nExpr;
93870         nCol = nGroupBy + 1;
93871         j = nGroupBy+1;
93872         for(i=0; i<sAggInfo.nColumn; i++){
93873           if( sAggInfo.aCol[i].iSorterColumn>=j ){
93874             nCol++;
93875             j++;
93876           }
93877         }
93878         regBase = sqlite3GetTempRange(pParse, nCol);
93879         sqlite3ExprCacheClear(pParse);
93880         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
93881         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
93882         j = nGroupBy+1;
93883         for(i=0; i<sAggInfo.nColumn; i++){
93884           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
93885           if( pCol->iSorterColumn>=j ){
93886             int r1 = j + regBase;
93887             int r2;
93888
93889             r2 = sqlite3ExprCodeGetColumn(pParse, 
93890                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
93891             if( r1!=r2 ){
93892               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
93893             }
93894             j++;
93895           }
93896         }
93897         regRecord = sqlite3GetTempReg(pParse);
93898         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
93899         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
93900         sqlite3ReleaseTempReg(pParse, regRecord);
93901         sqlite3ReleaseTempRange(pParse, regBase, nCol);
93902         sqlite3WhereEnd(pWInfo);
93903         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
93904         VdbeComment((v, "GROUP BY sort"));
93905         sAggInfo.useSortingIdx = 1;
93906         sqlite3ExprCacheClear(pParse);
93907       }
93908
93909       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
93910       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
93911       ** Then compare the current GROUP BY terms against the GROUP BY terms
93912       ** from the previous row currently stored in a0, a1, a2...
93913       */
93914       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
93915       sqlite3ExprCacheClear(pParse);
93916       for(j=0; j<pGroupBy->nExpr; j++){
93917         if( groupBySort ){
93918           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
93919         }else{
93920           sAggInfo.directMode = 1;
93921           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
93922         }
93923       }
93924       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
93925                           (char*)pKeyInfo, P4_KEYINFO);
93926       j1 = sqlite3VdbeCurrentAddr(v);
93927       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
93928
93929       /* Generate code that runs whenever the GROUP BY changes.
93930       ** Changes in the GROUP BY are detected by the previous code
93931       ** block.  If there were no changes, this block is skipped.
93932       **
93933       ** This code copies current group by terms in b0,b1,b2,...
93934       ** over to a0,a1,a2.  It then calls the output subroutine
93935       ** and resets the aggregate accumulator registers in preparation
93936       ** for the next GROUP BY batch.
93937       */
93938       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
93939       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
93940       VdbeComment((v, "output one row"));
93941       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
93942       VdbeComment((v, "check abort flag"));
93943       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
93944       VdbeComment((v, "reset accumulator"));
93945
93946       /* Update the aggregate accumulators based on the content of
93947       ** the current row
93948       */
93949       sqlite3VdbeJumpHere(v, j1);
93950       updateAccumulator(pParse, &sAggInfo);
93951       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
93952       VdbeComment((v, "indicate data in accumulator"));
93953
93954       /* End of the loop
93955       */
93956       if( groupBySort ){
93957         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
93958       }else{
93959         sqlite3WhereEnd(pWInfo);
93960         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
93961       }
93962
93963       /* Output the final row of result
93964       */
93965       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
93966       VdbeComment((v, "output final row"));
93967
93968       /* Jump over the subroutines
93969       */
93970       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
93971
93972       /* Generate a subroutine that outputs a single row of the result
93973       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
93974       ** is less than or equal to zero, the subroutine is a no-op.  If
93975       ** the processing calls for the query to abort, this subroutine
93976       ** increments the iAbortFlag memory location before returning in
93977       ** order to signal the caller to abort.
93978       */
93979       addrSetAbort = sqlite3VdbeCurrentAddr(v);
93980       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
93981       VdbeComment((v, "set abort flag"));
93982       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93983       sqlite3VdbeResolveLabel(v, addrOutputRow);
93984       addrOutputRow = sqlite3VdbeCurrentAddr(v);
93985       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
93986       VdbeComment((v, "Groupby result generator entry point"));
93987       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93988       finalizeAggFunctions(pParse, &sAggInfo);
93989       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
93990       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
93991                       distinct, pDest,
93992                       addrOutputRow+1, addrSetAbort);
93993       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
93994       VdbeComment((v, "end groupby result generator"));
93995
93996       /* Generate a subroutine that will reset the group-by accumulator
93997       */
93998       sqlite3VdbeResolveLabel(v, addrReset);
93999       resetAccumulator(pParse, &sAggInfo);
94000       sqlite3VdbeAddOp1(v, OP_Return, regReset);
94001      
94002     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
94003     else {
94004       ExprList *pDel = 0;
94005 #ifndef SQLITE_OMIT_BTREECOUNT
94006       Table *pTab;
94007       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
94008         /* If isSimpleCount() returns a pointer to a Table structure, then
94009         ** the SQL statement is of the form:
94010         **
94011         **   SELECT count(*) FROM <tbl>
94012         **
94013         ** where the Table structure returned represents table <tbl>.
94014         **
94015         ** This statement is so common that it is optimized specially. The
94016         ** OP_Count instruction is executed either on the intkey table that
94017         ** contains the data for table <tbl> or on one of its indexes. It
94018         ** is better to execute the op on an index, as indexes are almost
94019         ** always spread across less pages than their corresponding tables.
94020         */
94021         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94022         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
94023         Index *pIdx;                         /* Iterator variable */
94024         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
94025         Index *pBest = 0;                    /* Best index found so far */
94026         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
94027
94028         sqlite3CodeVerifySchema(pParse, iDb);
94029         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94030
94031         /* Search for the index that has the least amount of columns. If
94032         ** there is such an index, and it has less columns than the table
94033         ** does, then we can assume that it consumes less space on disk and
94034         ** will therefore be cheaper to scan to determine the query result.
94035         ** In this case set iRoot to the root page number of the index b-tree
94036         ** and pKeyInfo to the KeyInfo structure required to navigate the
94037         ** index.
94038         **
94039         ** In practice the KeyInfo structure will not be used. It is only 
94040         ** passed to keep OP_OpenRead happy.
94041         */
94042         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94043           if( !pBest || pIdx->nColumn<pBest->nColumn ){
94044             pBest = pIdx;
94045           }
94046         }
94047         if( pBest && pBest->nColumn<pTab->nCol ){
94048           iRoot = pBest->tnum;
94049           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94050         }
94051
94052         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94053         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94054         if( pKeyInfo ){
94055           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94056         }
94057         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94058         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94059         explainSimpleCount(pParse, pTab, pBest);
94060       }else
94061 #endif /* SQLITE_OMIT_BTREECOUNT */
94062       {
94063         /* Check if the query is of one of the following forms:
94064         **
94065         **   SELECT min(x) FROM ...
94066         **   SELECT max(x) FROM ...
94067         **
94068         ** If it is, then ask the code in where.c to attempt to sort results
94069         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
94070         ** If where.c is able to produce results sorted in this order, then
94071         ** add vdbe code to break out of the processing loop after the 
94072         ** first iteration (since the first iteration of the loop is 
94073         ** guaranteed to operate on the row with the minimum or maximum 
94074         ** value of x, the only row required).
94075         **
94076         ** A special flag must be passed to sqlite3WhereBegin() to slightly
94077         ** modify behaviour as follows:
94078         **
94079         **   + If the query is a "SELECT min(x)", then the loop coded by
94080         **     where.c should not iterate over any values with a NULL value
94081         **     for x.
94082         **
94083         **   + The optimizer code in where.c (the thing that decides which
94084         **     index or indices to use) should place a different priority on 
94085         **     satisfying the 'ORDER BY' clause than it does in other cases.
94086         **     Refer to code and comments in where.c for details.
94087         */
94088         ExprList *pMinMax = 0;
94089         u8 flag = minMaxQuery(p);
94090         if( flag ){
94091           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94092           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94093           pDel = pMinMax;
94094           if( pMinMax && !db->mallocFailed ){
94095             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94096             pMinMax->a[0].pExpr->op = TK_COLUMN;
94097           }
94098         }
94099   
94100         /* This case runs if the aggregate has no GROUP BY clause.  The
94101         ** processing is much simpler since there is only a single row
94102         ** of output.
94103         */
94104         resetAccumulator(pParse, &sAggInfo);
94105         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94106         if( pWInfo==0 ){
94107           sqlite3ExprListDelete(db, pDel);
94108           goto select_end;
94109         }
94110         updateAccumulator(pParse, &sAggInfo);
94111         if( !pMinMax && flag ){
94112           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94113           VdbeComment((v, "%s() by index",
94114                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
94115         }
94116         sqlite3WhereEnd(pWInfo);
94117         finalizeAggFunctions(pParse, &sAggInfo);
94118       }
94119
94120       pOrderBy = 0;
94121       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94122       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
94123                       pDest, addrEnd, addrEnd);
94124       sqlite3ExprListDelete(db, pDel);
94125     }
94126     sqlite3VdbeResolveLabel(v, addrEnd);
94127     
94128   } /* endif aggregate query */
94129
94130   if( distinct>=0 ){
94131     explainTempTable(pParse, "DISTINCT");
94132   }
94133
94134   /* If there is an ORDER BY clause, then we need to sort the results
94135   ** and send them to the callback one by one.
94136   */
94137   if( pOrderBy ){
94138     explainTempTable(pParse, "ORDER BY");
94139     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94140   }
94141
94142   /* Jump here to skip this query
94143   */
94144   sqlite3VdbeResolveLabel(v, iEnd);
94145
94146   /* The SELECT was successfully coded.   Set the return code to 0
94147   ** to indicate no errors.
94148   */
94149   rc = 0;
94150
94151   /* Control jumps to here if an error is encountered above, or upon
94152   ** successful coding of the SELECT.
94153   */
94154 select_end:
94155   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94156
94157   /* Identify column names if results of the SELECT are to be output.
94158   */
94159   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94160     generateColumnNames(pParse, pTabList, pEList);
94161   }
94162
94163   sqlite3DbFree(db, sAggInfo.aCol);
94164   sqlite3DbFree(db, sAggInfo.aFunc);
94165   return rc;
94166 }
94167
94168 #if defined(SQLITE_DEBUG)
94169 /*
94170 *******************************************************************************
94171 ** The following code is used for testing and debugging only.  The code
94172 ** that follows does not appear in normal builds.
94173 **
94174 ** These routines are used to print out the content of all or part of a 
94175 ** parse structures such as Select or Expr.  Such printouts are useful
94176 ** for helping to understand what is happening inside the code generator
94177 ** during the execution of complex SELECT statements.
94178 **
94179 ** These routine are not called anywhere from within the normal
94180 ** code base.  Then are intended to be called from within the debugger
94181 ** or from temporary "printf" statements inserted for debugging.
94182 */
94183 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94184   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94185     sqlite3DebugPrintf("(%s", p->u.zToken);
94186   }else{
94187     sqlite3DebugPrintf("(%d", p->op);
94188   }
94189   if( p->pLeft ){
94190     sqlite3DebugPrintf(" ");
94191     sqlite3PrintExpr(p->pLeft);
94192   }
94193   if( p->pRight ){
94194     sqlite3DebugPrintf(" ");
94195     sqlite3PrintExpr(p->pRight);
94196   }
94197   sqlite3DebugPrintf(")");
94198 }
94199 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94200   int i;
94201   for(i=0; i<pList->nExpr; i++){
94202     sqlite3PrintExpr(pList->a[i].pExpr);
94203     if( i<pList->nExpr-1 ){
94204       sqlite3DebugPrintf(", ");
94205     }
94206   }
94207 }
94208 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94209   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94210   sqlite3PrintExprList(p->pEList);
94211   sqlite3DebugPrintf("\n");
94212   if( p->pSrc ){
94213     char *zPrefix;
94214     int i;
94215     zPrefix = "FROM";
94216     for(i=0; i<p->pSrc->nSrc; i++){
94217       struct SrcList_item *pItem = &p->pSrc->a[i];
94218       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94219       zPrefix = "";
94220       if( pItem->pSelect ){
94221         sqlite3DebugPrintf("(\n");
94222         sqlite3PrintSelect(pItem->pSelect, indent+10);
94223         sqlite3DebugPrintf("%*s)", indent+8, "");
94224       }else if( pItem->zName ){
94225         sqlite3DebugPrintf("%s", pItem->zName);
94226       }
94227       if( pItem->pTab ){
94228         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94229       }
94230       if( pItem->zAlias ){
94231         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94232       }
94233       if( i<p->pSrc->nSrc-1 ){
94234         sqlite3DebugPrintf(",");
94235       }
94236       sqlite3DebugPrintf("\n");
94237     }
94238   }
94239   if( p->pWhere ){
94240     sqlite3DebugPrintf("%*s WHERE ", indent, "");
94241     sqlite3PrintExpr(p->pWhere);
94242     sqlite3DebugPrintf("\n");
94243   }
94244   if( p->pGroupBy ){
94245     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94246     sqlite3PrintExprList(p->pGroupBy);
94247     sqlite3DebugPrintf("\n");
94248   }
94249   if( p->pHaving ){
94250     sqlite3DebugPrintf("%*s HAVING ", indent, "");
94251     sqlite3PrintExpr(p->pHaving);
94252     sqlite3DebugPrintf("\n");
94253   }
94254   if( p->pOrderBy ){
94255     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94256     sqlite3PrintExprList(p->pOrderBy);
94257     sqlite3DebugPrintf("\n");
94258   }
94259 }
94260 /* End of the structure debug printing code
94261 *****************************************************************************/
94262 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94263
94264 /************** End of select.c **********************************************/
94265 /************** Begin file table.c *******************************************/
94266 /*
94267 ** 2001 September 15
94268 **
94269 ** The author disclaims copyright to this source code.  In place of
94270 ** a legal notice, here is a blessing:
94271 **
94272 **    May you do good and not evil.
94273 **    May you find forgiveness for yourself and forgive others.
94274 **    May you share freely, never taking more than you give.
94275 **
94276 *************************************************************************
94277 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
94278 ** interface routines.  These are just wrappers around the main
94279 ** interface routine of sqlite3_exec().
94280 **
94281 ** These routines are in a separate files so that they will not be linked
94282 ** if they are not used.
94283 */
94284
94285 #ifndef SQLITE_OMIT_GET_TABLE
94286
94287 /*
94288 ** This structure is used to pass data from sqlite3_get_table() through
94289 ** to the callback function is uses to build the result.
94290 */
94291 typedef struct TabResult {
94292   char **azResult;   /* Accumulated output */
94293   char *zErrMsg;     /* Error message text, if an error occurs */
94294   int nAlloc;        /* Slots allocated for azResult[] */
94295   int nRow;          /* Number of rows in the result */
94296   int nColumn;       /* Number of columns in the result */
94297   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
94298   int rc;            /* Return code from sqlite3_exec() */
94299 } TabResult;
94300
94301 /*
94302 ** This routine is called once for each row in the result table.  Its job
94303 ** is to fill in the TabResult structure appropriately, allocating new
94304 ** memory as necessary.
94305 */
94306 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94307   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
94308   int need;                         /* Slots needed in p->azResult[] */
94309   int i;                            /* Loop counter */
94310   char *z;                          /* A single column of result */
94311
94312   /* Make sure there is enough space in p->azResult to hold everything
94313   ** we need to remember from this invocation of the callback.
94314   */
94315   if( p->nRow==0 && argv!=0 ){
94316     need = nCol*2;
94317   }else{
94318     need = nCol;
94319   }
94320   if( p->nData + need > p->nAlloc ){
94321     char **azNew;
94322     p->nAlloc = p->nAlloc*2 + need;
94323     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94324     if( azNew==0 ) goto malloc_failed;
94325     p->azResult = azNew;
94326   }
94327
94328   /* If this is the first row, then generate an extra row containing
94329   ** the names of all columns.
94330   */
94331   if( p->nRow==0 ){
94332     p->nColumn = nCol;
94333     for(i=0; i<nCol; i++){
94334       z = sqlite3_mprintf("%s", colv[i]);
94335       if( z==0 ) goto malloc_failed;
94336       p->azResult[p->nData++] = z;
94337     }
94338   }else if( p->nColumn!=nCol ){
94339     sqlite3_free(p->zErrMsg);
94340     p->zErrMsg = sqlite3_mprintf(
94341        "sqlite3_get_table() called with two or more incompatible queries"
94342     );
94343     p->rc = SQLITE_ERROR;
94344     return 1;
94345   }
94346
94347   /* Copy over the row data
94348   */
94349   if( argv!=0 ){
94350     for(i=0; i<nCol; i++){
94351       if( argv[i]==0 ){
94352         z = 0;
94353       }else{
94354         int n = sqlite3Strlen30(argv[i])+1;
94355         z = sqlite3_malloc( n );
94356         if( z==0 ) goto malloc_failed;
94357         memcpy(z, argv[i], n);
94358       }
94359       p->azResult[p->nData++] = z;
94360     }
94361     p->nRow++;
94362   }
94363   return 0;
94364
94365 malloc_failed:
94366   p->rc = SQLITE_NOMEM;
94367   return 1;
94368 }
94369
94370 /*
94371 ** Query the database.  But instead of invoking a callback for each row,
94372 ** malloc() for space to hold the result and return the entire results
94373 ** at the conclusion of the call.
94374 **
94375 ** The result that is written to ***pazResult is held in memory obtained
94376 ** from malloc().  But the caller cannot free this memory directly.  
94377 ** Instead, the entire table should be passed to sqlite3_free_table() when
94378 ** the calling procedure is finished using it.
94379 */
94380 SQLITE_API int sqlite3_get_table(
94381   sqlite3 *db,                /* The database on which the SQL executes */
94382   const char *zSql,           /* The SQL to be executed */
94383   char ***pazResult,          /* Write the result table here */
94384   int *pnRow,                 /* Write the number of rows in the result here */
94385   int *pnColumn,              /* Write the number of columns of result here */
94386   char **pzErrMsg             /* Write error messages here */
94387 ){
94388   int rc;
94389   TabResult res;
94390
94391   *pazResult = 0;
94392   if( pnColumn ) *pnColumn = 0;
94393   if( pnRow ) *pnRow = 0;
94394   if( pzErrMsg ) *pzErrMsg = 0;
94395   res.zErrMsg = 0;
94396   res.nRow = 0;
94397   res.nColumn = 0;
94398   res.nData = 1;
94399   res.nAlloc = 20;
94400   res.rc = SQLITE_OK;
94401   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
94402   if( res.azResult==0 ){
94403      db->errCode = SQLITE_NOMEM;
94404      return SQLITE_NOMEM;
94405   }
94406   res.azResult[0] = 0;
94407   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
94408   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
94409   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
94410   if( (rc&0xff)==SQLITE_ABORT ){
94411     sqlite3_free_table(&res.azResult[1]);
94412     if( res.zErrMsg ){
94413       if( pzErrMsg ){
94414         sqlite3_free(*pzErrMsg);
94415         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
94416       }
94417       sqlite3_free(res.zErrMsg);
94418     }
94419     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
94420     return res.rc;
94421   }
94422   sqlite3_free(res.zErrMsg);
94423   if( rc!=SQLITE_OK ){
94424     sqlite3_free_table(&res.azResult[1]);
94425     return rc;
94426   }
94427   if( res.nAlloc>res.nData ){
94428     char **azNew;
94429     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
94430     if( azNew==0 ){
94431       sqlite3_free_table(&res.azResult[1]);
94432       db->errCode = SQLITE_NOMEM;
94433       return SQLITE_NOMEM;
94434     }
94435     res.azResult = azNew;
94436   }
94437   *pazResult = &res.azResult[1];
94438   if( pnColumn ) *pnColumn = res.nColumn;
94439   if( pnRow ) *pnRow = res.nRow;
94440   return rc;
94441 }
94442
94443 /*
94444 ** This routine frees the space the sqlite3_get_table() malloced.
94445 */
94446 SQLITE_API void sqlite3_free_table(
94447   char **azResult            /* Result returned from from sqlite3_get_table() */
94448 ){
94449   if( azResult ){
94450     int i, n;
94451     azResult--;
94452     assert( azResult!=0 );
94453     n = SQLITE_PTR_TO_INT(azResult[0]);
94454     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
94455     sqlite3_free(azResult);
94456   }
94457 }
94458
94459 #endif /* SQLITE_OMIT_GET_TABLE */
94460
94461 /************** End of table.c ***********************************************/
94462 /************** Begin file trigger.c *****************************************/
94463 /*
94464 **
94465 ** The author disclaims copyright to this source code.  In place of
94466 ** a legal notice, here is a blessing:
94467 **
94468 **    May you do good and not evil.
94469 **    May you find forgiveness for yourself and forgive others.
94470 **    May you share freely, never taking more than you give.
94471 **
94472 *************************************************************************
94473 ** This file contains the implementation for TRIGGERs
94474 */
94475
94476 #ifndef SQLITE_OMIT_TRIGGER
94477 /*
94478 ** Delete a linked list of TriggerStep structures.
94479 */
94480 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
94481   while( pTriggerStep ){
94482     TriggerStep * pTmp = pTriggerStep;
94483     pTriggerStep = pTriggerStep->pNext;
94484
94485     sqlite3ExprDelete(db, pTmp->pWhere);
94486     sqlite3ExprListDelete(db, pTmp->pExprList);
94487     sqlite3SelectDelete(db, pTmp->pSelect);
94488     sqlite3IdListDelete(db, pTmp->pIdList);
94489
94490     sqlite3DbFree(db, pTmp);
94491   }
94492 }
94493
94494 /*
94495 ** Given table pTab, return a list of all the triggers attached to 
94496 ** the table. The list is connected by Trigger.pNext pointers.
94497 **
94498 ** All of the triggers on pTab that are in the same database as pTab
94499 ** are already attached to pTab->pTrigger.  But there might be additional
94500 ** triggers on pTab in the TEMP schema.  This routine prepends all
94501 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
94502 ** and returns the combined list.
94503 **
94504 ** To state it another way:  This routine returns a list of all triggers
94505 ** that fire off of pTab.  The list will include any TEMP triggers on
94506 ** pTab as well as the triggers lised in pTab->pTrigger.
94507 */
94508 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
94509   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
94510   Trigger *pList = 0;                  /* List of triggers to return */
94511
94512   if( pParse->disableTriggers ){
94513     return 0;
94514   }
94515
94516   if( pTmpSchema!=pTab->pSchema ){
94517     HashElem *p;
94518     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
94519     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
94520       Trigger *pTrig = (Trigger *)sqliteHashData(p);
94521       if( pTrig->pTabSchema==pTab->pSchema
94522        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
94523       ){
94524         pTrig->pNext = (pList ? pList : pTab->pTrigger);
94525         pList = pTrig;
94526       }
94527     }
94528   }
94529
94530   return (pList ? pList : pTab->pTrigger);
94531 }
94532
94533 /*
94534 ** This is called by the parser when it sees a CREATE TRIGGER statement
94535 ** up to the point of the BEGIN before the trigger actions.  A Trigger
94536 ** structure is generated based on the information available and stored
94537 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
94538 ** sqlite3FinishTrigger() function is called to complete the trigger
94539 ** construction process.
94540 */
94541 SQLITE_PRIVATE void sqlite3BeginTrigger(
94542   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
94543   Token *pName1,      /* The name of the trigger */
94544   Token *pName2,      /* The name of the trigger */
94545   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
94546   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
94547   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
94548   SrcList *pTableName,/* The name of the table/view the trigger applies to */
94549   Expr *pWhen,        /* WHEN clause */
94550   int isTemp,         /* True if the TEMPORARY keyword is present */
94551   int noErr           /* Suppress errors if the trigger already exists */
94552 ){
94553   Trigger *pTrigger = 0;  /* The new trigger */
94554   Table *pTab;            /* Table that the trigger fires off of */
94555   char *zName = 0;        /* Name of the trigger */
94556   sqlite3 *db = pParse->db;  /* The database connection */
94557   int iDb;                /* The database to store the trigger in */
94558   Token *pName;           /* The unqualified db name */
94559   DbFixer sFix;           /* State vector for the DB fixer */
94560   int iTabDb;             /* Index of the database holding pTab */
94561
94562   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
94563   assert( pName2!=0 );
94564   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
94565   assert( op>0 && op<0xff );
94566   if( isTemp ){
94567     /* If TEMP was specified, then the trigger name may not be qualified. */
94568     if( pName2->n>0 ){
94569       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
94570       goto trigger_cleanup;
94571     }
94572     iDb = 1;
94573     pName = pName1;
94574   }else{
94575     /* Figure out the db that the the trigger will be created in */
94576     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94577     if( iDb<0 ){
94578       goto trigger_cleanup;
94579     }
94580   }
94581
94582   /* If the trigger name was unqualified, and the table is a temp table,
94583   ** then set iDb to 1 to create the trigger in the temporary database.
94584   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
94585   ** exist, the error is caught by the block below.
94586   */
94587   if( !pTableName || db->mallocFailed ){
94588     goto trigger_cleanup;
94589   }
94590   pTab = sqlite3SrcListLookup(pParse, pTableName);
94591   if( db->init.busy==0 && pName2->n==0 && pTab
94592         && pTab->pSchema==db->aDb[1].pSchema ){
94593     iDb = 1;
94594   }
94595
94596   /* Ensure the table name matches database name and that the table exists */
94597   if( db->mallocFailed ) goto trigger_cleanup;
94598   assert( pTableName->nSrc==1 );
94599   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
94600       sqlite3FixSrcList(&sFix, pTableName) ){
94601     goto trigger_cleanup;
94602   }
94603   pTab = sqlite3SrcListLookup(pParse, pTableName);
94604   if( !pTab ){
94605     /* The table does not exist. */
94606     if( db->init.iDb==1 ){
94607       /* Ticket #3810.
94608       ** Normally, whenever a table is dropped, all associated triggers are
94609       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
94610       ** and the table is dropped by a different database connection, the
94611       ** trigger is not visible to the database connection that does the
94612       ** drop so the trigger cannot be dropped.  This results in an
94613       ** "orphaned trigger" - a trigger whose associated table is missing.
94614       */
94615       db->init.orphanTrigger = 1;
94616     }
94617     goto trigger_cleanup;
94618   }
94619   if( IsVirtual(pTab) ){
94620     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
94621     goto trigger_cleanup;
94622   }
94623
94624   /* Check that the trigger name is not reserved and that no trigger of the
94625   ** specified name exists */
94626   zName = sqlite3NameFromToken(db, pName);
94627   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
94628     goto trigger_cleanup;
94629   }
94630   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94631   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
94632                       zName, sqlite3Strlen30(zName)) ){
94633     if( !noErr ){
94634       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
94635     }else{
94636       assert( !db->init.busy );
94637       sqlite3CodeVerifySchema(pParse, iDb);
94638     }
94639     goto trigger_cleanup;
94640   }
94641
94642   /* Do not create a trigger on a system table */
94643   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
94644     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
94645     pParse->nErr++;
94646     goto trigger_cleanup;
94647   }
94648
94649   /* INSTEAD of triggers are only for views and views only support INSTEAD
94650   ** of triggers.
94651   */
94652   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
94653     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
94654         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
94655     goto trigger_cleanup;
94656   }
94657   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
94658     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
94659         " trigger on table: %S", pTableName, 0);
94660     goto trigger_cleanup;
94661   }
94662   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94663
94664 #ifndef SQLITE_OMIT_AUTHORIZATION
94665   {
94666     int code = SQLITE_CREATE_TRIGGER;
94667     const char *zDb = db->aDb[iTabDb].zName;
94668     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
94669     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
94670     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
94671       goto trigger_cleanup;
94672     }
94673     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
94674       goto trigger_cleanup;
94675     }
94676   }
94677 #endif
94678
94679   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
94680   ** cannot appear on views.  So we might as well translate every
94681   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
94682   ** elsewhere.
94683   */
94684   if (tr_tm == TK_INSTEAD){
94685     tr_tm = TK_BEFORE;
94686   }
94687
94688   /* Build the Trigger object */
94689   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
94690   if( pTrigger==0 ) goto trigger_cleanup;
94691   pTrigger->zName = zName;
94692   zName = 0;
94693   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
94694   pTrigger->pSchema = db->aDb[iDb].pSchema;
94695   pTrigger->pTabSchema = pTab->pSchema;
94696   pTrigger->op = (u8)op;
94697   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
94698   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
94699   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
94700   assert( pParse->pNewTrigger==0 );
94701   pParse->pNewTrigger = pTrigger;
94702
94703 trigger_cleanup:
94704   sqlite3DbFree(db, zName);
94705   sqlite3SrcListDelete(db, pTableName);
94706   sqlite3IdListDelete(db, pColumns);
94707   sqlite3ExprDelete(db, pWhen);
94708   if( !pParse->pNewTrigger ){
94709     sqlite3DeleteTrigger(db, pTrigger);
94710   }else{
94711     assert( pParse->pNewTrigger==pTrigger );
94712   }
94713 }
94714
94715 /*
94716 ** This routine is called after all of the trigger actions have been parsed
94717 ** in order to complete the process of building the trigger.
94718 */
94719 SQLITE_PRIVATE void sqlite3FinishTrigger(
94720   Parse *pParse,          /* Parser context */
94721   TriggerStep *pStepList, /* The triggered program */
94722   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
94723 ){
94724   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
94725   char *zName;                            /* Name of trigger */
94726   sqlite3 *db = pParse->db;               /* The database */
94727   DbFixer sFix;                           /* Fixer object */
94728   int iDb;                                /* Database containing the trigger */
94729   Token nameToken;                        /* Trigger name for error reporting */
94730
94731   pParse->pNewTrigger = 0;
94732   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
94733   zName = pTrig->zName;
94734   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94735   pTrig->step_list = pStepList;
94736   while( pStepList ){
94737     pStepList->pTrig = pTrig;
94738     pStepList = pStepList->pNext;
94739   }
94740   nameToken.z = pTrig->zName;
94741   nameToken.n = sqlite3Strlen30(nameToken.z);
94742   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
94743           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
94744     goto triggerfinish_cleanup;
94745   }
94746
94747   /* if we are not initializing,
94748   ** build the sqlite_master entry
94749   */
94750   if( !db->init.busy ){
94751     Vdbe *v;
94752     char *z;
94753
94754     /* Make an entry in the sqlite_master table */
94755     v = sqlite3GetVdbe(pParse);
94756     if( v==0 ) goto triggerfinish_cleanup;
94757     sqlite3BeginWriteOperation(pParse, 0, iDb);
94758     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
94759     sqlite3NestedParse(pParse,
94760        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
94761        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
94762        pTrig->table, z);
94763     sqlite3DbFree(db, z);
94764     sqlite3ChangeCookie(pParse, iDb);
94765     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
94766         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
94767     );
94768   }
94769
94770   if( db->init.busy ){
94771     Trigger *pLink = pTrig;
94772     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
94773     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94774     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
94775     if( pTrig ){
94776       db->mallocFailed = 1;
94777     }else if( pLink->pSchema==pLink->pTabSchema ){
94778       Table *pTab;
94779       int n = sqlite3Strlen30(pLink->table);
94780       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
94781       assert( pTab!=0 );
94782       pLink->pNext = pTab->pTrigger;
94783       pTab->pTrigger = pLink;
94784     }
94785   }
94786
94787 triggerfinish_cleanup:
94788   sqlite3DeleteTrigger(db, pTrig);
94789   assert( !pParse->pNewTrigger );
94790   sqlite3DeleteTriggerStep(db, pStepList);
94791 }
94792
94793 /*
94794 ** Turn a SELECT statement (that the pSelect parameter points to) into
94795 ** a trigger step.  Return a pointer to a TriggerStep structure.
94796 **
94797 ** The parser calls this routine when it finds a SELECT statement in
94798 ** body of a TRIGGER.  
94799 */
94800 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
94801   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
94802   if( pTriggerStep==0 ) {
94803     sqlite3SelectDelete(db, pSelect);
94804     return 0;
94805   }
94806   pTriggerStep->op = TK_SELECT;
94807   pTriggerStep->pSelect = pSelect;
94808   pTriggerStep->orconf = OE_Default;
94809   return pTriggerStep;
94810 }
94811
94812 /*
94813 ** Allocate space to hold a new trigger step.  The allocated space
94814 ** holds both the TriggerStep object and the TriggerStep.target.z string.
94815 **
94816 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
94817 */
94818 static TriggerStep *triggerStepAllocate(
94819   sqlite3 *db,                /* Database connection */
94820   u8 op,                      /* Trigger opcode */
94821   Token *pName                /* The target name */
94822 ){
94823   TriggerStep *pTriggerStep;
94824
94825   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
94826   if( pTriggerStep ){
94827     char *z = (char*)&pTriggerStep[1];
94828     memcpy(z, pName->z, pName->n);
94829     pTriggerStep->target.z = z;
94830     pTriggerStep->target.n = pName->n;
94831     pTriggerStep->op = op;
94832   }
94833   return pTriggerStep;
94834 }
94835
94836 /*
94837 ** Build a trigger step out of an INSERT statement.  Return a pointer
94838 ** to the new trigger step.
94839 **
94840 ** The parser calls this routine when it sees an INSERT inside the
94841 ** body of a trigger.
94842 */
94843 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
94844   sqlite3 *db,        /* The database connection */
94845   Token *pTableName,  /* Name of the table into which we insert */
94846   IdList *pColumn,    /* List of columns in pTableName to insert into */
94847   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
94848   Select *pSelect,    /* A SELECT statement that supplies values */
94849   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
94850 ){
94851   TriggerStep *pTriggerStep;
94852
94853   assert(pEList == 0 || pSelect == 0);
94854   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
94855
94856   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
94857   if( pTriggerStep ){
94858     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
94859     pTriggerStep->pIdList = pColumn;
94860     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
94861     pTriggerStep->orconf = orconf;
94862   }else{
94863     sqlite3IdListDelete(db, pColumn);
94864   }
94865   sqlite3ExprListDelete(db, pEList);
94866   sqlite3SelectDelete(db, pSelect);
94867
94868   return pTriggerStep;
94869 }
94870
94871 /*
94872 ** Construct a trigger step that implements an UPDATE statement and return
94873 ** a pointer to that trigger step.  The parser calls this routine when it
94874 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
94875 */
94876 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
94877   sqlite3 *db,         /* The database connection */
94878   Token *pTableName,   /* Name of the table to be updated */
94879   ExprList *pEList,    /* The SET clause: list of column and new values */
94880   Expr *pWhere,        /* The WHERE clause */
94881   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
94882 ){
94883   TriggerStep *pTriggerStep;
94884
94885   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
94886   if( pTriggerStep ){
94887     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
94888     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
94889     pTriggerStep->orconf = orconf;
94890   }
94891   sqlite3ExprListDelete(db, pEList);
94892   sqlite3ExprDelete(db, pWhere);
94893   return pTriggerStep;
94894 }
94895
94896 /*
94897 ** Construct a trigger step that implements a DELETE statement and return
94898 ** a pointer to that trigger step.  The parser calls this routine when it
94899 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
94900 */
94901 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
94902   sqlite3 *db,            /* Database connection */
94903   Token *pTableName,      /* The table from which rows are deleted */
94904   Expr *pWhere            /* The WHERE clause */
94905 ){
94906   TriggerStep *pTriggerStep;
94907
94908   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
94909   if( pTriggerStep ){
94910     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
94911     pTriggerStep->orconf = OE_Default;
94912   }
94913   sqlite3ExprDelete(db, pWhere);
94914   return pTriggerStep;
94915 }
94916
94917 /* 
94918 ** Recursively delete a Trigger structure
94919 */
94920 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
94921   if( pTrigger==0 ) return;
94922   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
94923   sqlite3DbFree(db, pTrigger->zName);
94924   sqlite3DbFree(db, pTrigger->table);
94925   sqlite3ExprDelete(db, pTrigger->pWhen);
94926   sqlite3IdListDelete(db, pTrigger->pColumns);
94927   sqlite3DbFree(db, pTrigger);
94928 }
94929
94930 /*
94931 ** This function is called to drop a trigger from the database schema. 
94932 **
94933 ** This may be called directly from the parser and therefore identifies
94934 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
94935 ** same job as this routine except it takes a pointer to the trigger
94936 ** instead of the trigger name.
94937 **/
94938 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
94939   Trigger *pTrigger = 0;
94940   int i;
94941   const char *zDb;
94942   const char *zName;
94943   int nName;
94944   sqlite3 *db = pParse->db;
94945
94946   if( db->mallocFailed ) goto drop_trigger_cleanup;
94947   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
94948     goto drop_trigger_cleanup;
94949   }
94950
94951   assert( pName->nSrc==1 );
94952   zDb = pName->a[0].zDatabase;
94953   zName = pName->a[0].zName;
94954   nName = sqlite3Strlen30(zName);
94955   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
94956   for(i=OMIT_TEMPDB; i<db->nDb; i++){
94957     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
94958     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
94959     assert( sqlite3SchemaMutexHeld(db, j, 0) );
94960     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
94961     if( pTrigger ) break;
94962   }
94963   if( !pTrigger ){
94964     if( !noErr ){
94965       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
94966     }else{
94967       sqlite3CodeVerifyNamedSchema(pParse, zDb);
94968     }
94969     pParse->checkSchema = 1;
94970     goto drop_trigger_cleanup;
94971   }
94972   sqlite3DropTriggerPtr(pParse, pTrigger);
94973
94974 drop_trigger_cleanup:
94975   sqlite3SrcListDelete(db, pName);
94976 }
94977
94978 /*
94979 ** Return a pointer to the Table structure for the table that a trigger
94980 ** is set on.
94981 */
94982 static Table *tableOfTrigger(Trigger *pTrigger){
94983   int n = sqlite3Strlen30(pTrigger->table);
94984   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
94985 }
94986
94987
94988 /*
94989 ** Drop a trigger given a pointer to that trigger. 
94990 */
94991 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
94992   Table   *pTable;
94993   Vdbe *v;
94994   sqlite3 *db = pParse->db;
94995   int iDb;
94996
94997   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
94998   assert( iDb>=0 && iDb<db->nDb );
94999   pTable = tableOfTrigger(pTrigger);
95000   assert( pTable );
95001   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
95002 #ifndef SQLITE_OMIT_AUTHORIZATION
95003   {
95004     int code = SQLITE_DROP_TRIGGER;
95005     const char *zDb = db->aDb[iDb].zName;
95006     const char *zTab = SCHEMA_TABLE(iDb);
95007     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
95008     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
95009       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95010       return;
95011     }
95012   }
95013 #endif
95014
95015   /* Generate code to destroy the database record of the trigger.
95016   */
95017   assert( pTable!=0 );
95018   if( (v = sqlite3GetVdbe(pParse))!=0 ){
95019     int base;
95020     static const VdbeOpList dropTrigger[] = {
95021       { OP_Rewind,     0, ADDR(9),  0},
95022       { OP_String8,    0, 1,        0}, /* 1 */
95023       { OP_Column,     0, 1,        2},
95024       { OP_Ne,         2, ADDR(8),  1},
95025       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
95026       { OP_Column,     0, 0,        2},
95027       { OP_Ne,         2, ADDR(8),  1},
95028       { OP_Delete,     0, 0,        0},
95029       { OP_Next,       0, ADDR(1),  0}, /* 8 */
95030     };
95031
95032     sqlite3BeginWriteOperation(pParse, 0, iDb);
95033     sqlite3OpenMasterTable(pParse, iDb);
95034     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
95035     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95036     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95037     sqlite3ChangeCookie(pParse, iDb);
95038     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95039     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95040     if( pParse->nMem<3 ){
95041       pParse->nMem = 3;
95042     }
95043   }
95044 }
95045
95046 /*
95047 ** Remove a trigger from the hash tables of the sqlite* pointer.
95048 */
95049 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95050   Trigger *pTrigger;
95051   Hash *pHash;
95052
95053   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95054   pHash = &(db->aDb[iDb].pSchema->trigHash);
95055   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95056   if( ALWAYS(pTrigger) ){
95057     if( pTrigger->pSchema==pTrigger->pTabSchema ){
95058       Table *pTab = tableOfTrigger(pTrigger);
95059       Trigger **pp;
95060       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95061       *pp = (*pp)->pNext;
95062     }
95063     sqlite3DeleteTrigger(db, pTrigger);
95064     db->flags |= SQLITE_InternChanges;
95065   }
95066 }
95067
95068 /*
95069 ** pEList is the SET clause of an UPDATE statement.  Each entry
95070 ** in pEList is of the format <id>=<expr>.  If any of the entries
95071 ** in pEList have an <id> which matches an identifier in pIdList,
95072 ** then return TRUE.  If pIdList==NULL, then it is considered a
95073 ** wildcard that matches anything.  Likewise if pEList==NULL then
95074 ** it matches anything so always return true.  Return false only
95075 ** if there is no match.
95076 */
95077 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95078   int e;
95079   if( pIdList==0 || NEVER(pEList==0) ) return 1;
95080   for(e=0; e<pEList->nExpr; e++){
95081     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95082   }
95083   return 0; 
95084 }
95085
95086 /*
95087 ** Return a list of all triggers on table pTab if there exists at least
95088 ** one trigger that must be fired when an operation of type 'op' is 
95089 ** performed on the table, and, if that operation is an UPDATE, if at
95090 ** least one of the columns in pChanges is being modified.
95091 */
95092 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95093   Parse *pParse,          /* Parse context */
95094   Table *pTab,            /* The table the contains the triggers */
95095   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95096   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
95097   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95098 ){
95099   int mask = 0;
95100   Trigger *pList = 0;
95101   Trigger *p;
95102
95103   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95104     pList = sqlite3TriggerList(pParse, pTab);
95105   }
95106   assert( pList==0 || IsVirtual(pTab)==0 );
95107   for(p=pList; p; p=p->pNext){
95108     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95109       mask |= p->tr_tm;
95110     }
95111   }
95112   if( pMask ){
95113     *pMask = mask;
95114   }
95115   return (mask ? pList : 0);
95116 }
95117
95118 /*
95119 ** Convert the pStep->target token into a SrcList and return a pointer
95120 ** to that SrcList.
95121 **
95122 ** This routine adds a specific database name, if needed, to the target when
95123 ** forming the SrcList.  This prevents a trigger in one database from
95124 ** referring to a target in another database.  An exception is when the
95125 ** trigger is in TEMP in which case it can refer to any other database it
95126 ** wants.
95127 */
95128 static SrcList *targetSrcList(
95129   Parse *pParse,       /* The parsing context */
95130   TriggerStep *pStep   /* The trigger containing the target token */
95131 ){
95132   int iDb;             /* Index of the database to use */
95133   SrcList *pSrc;       /* SrcList to be returned */
95134
95135   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95136   if( pSrc ){
95137     assert( pSrc->nSrc>0 );
95138     assert( pSrc->a!=0 );
95139     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95140     if( iDb==0 || iDb>=2 ){
95141       sqlite3 *db = pParse->db;
95142       assert( iDb<pParse->db->nDb );
95143       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95144     }
95145   }
95146   return pSrc;
95147 }
95148
95149 /*
95150 ** Generate VDBE code for the statements inside the body of a single 
95151 ** trigger.
95152 */
95153 static int codeTriggerProgram(
95154   Parse *pParse,            /* The parser context */
95155   TriggerStep *pStepList,   /* List of statements inside the trigger body */
95156   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
95157 ){
95158   TriggerStep *pStep;
95159   Vdbe *v = pParse->pVdbe;
95160   sqlite3 *db = pParse->db;
95161
95162   assert( pParse->pTriggerTab && pParse->pToplevel );
95163   assert( pStepList );
95164   assert( v!=0 );
95165   for(pStep=pStepList; pStep; pStep=pStep->pNext){
95166     /* Figure out the ON CONFLICT policy that will be used for this step
95167     ** of the trigger program. If the statement that caused this trigger
95168     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95169     ** the ON CONFLICT policy that was specified as part of the trigger
95170     ** step statement. Example:
95171     **
95172     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95173     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95174     **   END;
95175     **
95176     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
95177     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
95178     */
95179     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95180
95181     switch( pStep->op ){
95182       case TK_UPDATE: {
95183         sqlite3Update(pParse, 
95184           targetSrcList(pParse, pStep),
95185           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95186           sqlite3ExprDup(db, pStep->pWhere, 0), 
95187           pParse->eOrconf
95188         );
95189         break;
95190       }
95191       case TK_INSERT: {
95192         sqlite3Insert(pParse, 
95193           targetSrcList(pParse, pStep),
95194           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95195           sqlite3SelectDup(db, pStep->pSelect, 0), 
95196           sqlite3IdListDup(db, pStep->pIdList), 
95197           pParse->eOrconf
95198         );
95199         break;
95200       }
95201       case TK_DELETE: {
95202         sqlite3DeleteFrom(pParse, 
95203           targetSrcList(pParse, pStep),
95204           sqlite3ExprDup(db, pStep->pWhere, 0)
95205         );
95206         break;
95207       }
95208       default: assert( pStep->op==TK_SELECT ); {
95209         SelectDest sDest;
95210         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95211         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95212         sqlite3Select(pParse, pSelect, &sDest);
95213         sqlite3SelectDelete(db, pSelect);
95214         break;
95215       }
95216     } 
95217     if( pStep->op!=TK_SELECT ){
95218       sqlite3VdbeAddOp0(v, OP_ResetCount);
95219     }
95220   }
95221
95222   return 0;
95223 }
95224
95225 #ifdef SQLITE_DEBUG
95226 /*
95227 ** This function is used to add VdbeComment() annotations to a VDBE
95228 ** program. It is not used in production code, only for debugging.
95229 */
95230 static const char *onErrorText(int onError){
95231   switch( onError ){
95232     case OE_Abort:    return "abort";
95233     case OE_Rollback: return "rollback";
95234     case OE_Fail:     return "fail";
95235     case OE_Replace:  return "replace";
95236     case OE_Ignore:   return "ignore";
95237     case OE_Default:  return "default";
95238   }
95239   return "n/a";
95240 }
95241 #endif
95242
95243 /*
95244 ** Parse context structure pFrom has just been used to create a sub-vdbe
95245 ** (trigger program). If an error has occurred, transfer error information
95246 ** from pFrom to pTo.
95247 */
95248 static void transferParseError(Parse *pTo, Parse *pFrom){
95249   assert( pFrom->zErrMsg==0 || pFrom->nErr );
95250   assert( pTo->zErrMsg==0 || pTo->nErr );
95251   if( pTo->nErr==0 ){
95252     pTo->zErrMsg = pFrom->zErrMsg;
95253     pTo->nErr = pFrom->nErr;
95254   }else{
95255     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95256   }
95257 }
95258
95259 /*
95260 ** Create and populate a new TriggerPrg object with a sub-program 
95261 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
95262 */
95263 static TriggerPrg *codeRowTrigger(
95264   Parse *pParse,       /* Current parse context */
95265   Trigger *pTrigger,   /* Trigger to code */
95266   Table *pTab,         /* The table pTrigger is attached to */
95267   int orconf           /* ON CONFLICT policy to code trigger program with */
95268 ){
95269   Parse *pTop = sqlite3ParseToplevel(pParse);
95270   sqlite3 *db = pParse->db;   /* Database handle */
95271   TriggerPrg *pPrg;           /* Value to return */
95272   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
95273   Vdbe *v;                    /* Temporary VM */
95274   NameContext sNC;            /* Name context for sub-vdbe */
95275   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
95276   Parse *pSubParse;           /* Parse context for sub-vdbe */
95277   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
95278
95279   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95280   assert( pTop->pVdbe );
95281
95282   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95283   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
95284   ** list of the top-level Parse object sooner rather than later.  */
95285   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95286   if( !pPrg ) return 0;
95287   pPrg->pNext = pTop->pTriggerPrg;
95288   pTop->pTriggerPrg = pPrg;
95289   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95290   if( !pProgram ) return 0;
95291   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95292   pPrg->pTrigger = pTrigger;
95293   pPrg->orconf = orconf;
95294   pPrg->aColmask[0] = 0xffffffff;
95295   pPrg->aColmask[1] = 0xffffffff;
95296
95297   /* Allocate and populate a new Parse context to use for coding the 
95298   ** trigger sub-program.  */
95299   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95300   if( !pSubParse ) return 0;
95301   memset(&sNC, 0, sizeof(sNC));
95302   sNC.pParse = pSubParse;
95303   pSubParse->db = db;
95304   pSubParse->pTriggerTab = pTab;
95305   pSubParse->pToplevel = pTop;
95306   pSubParse->zAuthContext = pTrigger->zName;
95307   pSubParse->eTriggerOp = pTrigger->op;
95308   pSubParse->nQueryLoop = pParse->nQueryLoop;
95309
95310   v = sqlite3GetVdbe(pSubParse);
95311   if( v ){
95312     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
95313       pTrigger->zName, onErrorText(orconf),
95314       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95315         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95316         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95317         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95318       pTab->zName
95319     ));
95320 #ifndef SQLITE_OMIT_TRACE
95321     sqlite3VdbeChangeP4(v, -1, 
95322       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95323     );
95324 #endif
95325
95326     /* If one was specified, code the WHEN clause. If it evaluates to false
95327     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
95328     ** OP_Halt inserted at the end of the program.  */
95329     if( pTrigger->pWhen ){
95330       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
95331       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
95332        && db->mallocFailed==0 
95333       ){
95334         iEndTrigger = sqlite3VdbeMakeLabel(v);
95335         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
95336       }
95337       sqlite3ExprDelete(db, pWhen);
95338     }
95339
95340     /* Code the trigger program into the sub-vdbe. */
95341     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
95342
95343     /* Insert an OP_Halt at the end of the sub-program. */
95344     if( iEndTrigger ){
95345       sqlite3VdbeResolveLabel(v, iEndTrigger);
95346     }
95347     sqlite3VdbeAddOp0(v, OP_Halt);
95348     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
95349
95350     transferParseError(pParse, pSubParse);
95351     if( db->mallocFailed==0 ){
95352       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
95353     }
95354     pProgram->nMem = pSubParse->nMem;
95355     pProgram->nCsr = pSubParse->nTab;
95356     pProgram->token = (void *)pTrigger;
95357     pPrg->aColmask[0] = pSubParse->oldmask;
95358     pPrg->aColmask[1] = pSubParse->newmask;
95359     sqlite3VdbeDelete(v);
95360   }
95361
95362   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
95363   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
95364   sqlite3StackFree(db, pSubParse);
95365
95366   return pPrg;
95367 }
95368     
95369 /*
95370 ** Return a pointer to a TriggerPrg object containing the sub-program for
95371 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
95372 ** TriggerPrg object exists, a new object is allocated and populated before
95373 ** being returned.
95374 */
95375 static TriggerPrg *getRowTrigger(
95376   Parse *pParse,       /* Current parse context */
95377   Trigger *pTrigger,   /* Trigger to code */
95378   Table *pTab,         /* The table trigger pTrigger is attached to */
95379   int orconf           /* ON CONFLICT algorithm. */
95380 ){
95381   Parse *pRoot = sqlite3ParseToplevel(pParse);
95382   TriggerPrg *pPrg;
95383
95384   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95385
95386   /* It may be that this trigger has already been coded (or is in the
95387   ** process of being coded). If this is the case, then an entry with
95388   ** a matching TriggerPrg.pTrigger field will be present somewhere
95389   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
95390   for(pPrg=pRoot->pTriggerPrg; 
95391       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
95392       pPrg=pPrg->pNext
95393   );
95394
95395   /* If an existing TriggerPrg could not be located, create a new one. */
95396   if( !pPrg ){
95397     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
95398   }
95399
95400   return pPrg;
95401 }
95402
95403 /*
95404 ** Generate code for the trigger program associated with trigger p on 
95405 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
95406 ** function are the same as those described in the header function for
95407 ** sqlite3CodeRowTrigger()
95408 */
95409 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
95410   Parse *pParse,       /* Parse context */
95411   Trigger *p,          /* Trigger to code */
95412   Table *pTab,         /* The table to code triggers from */
95413   int reg,             /* Reg array containing OLD.* and NEW.* values */
95414   int orconf,          /* ON CONFLICT policy */
95415   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95416 ){
95417   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
95418   TriggerPrg *pPrg;
95419   pPrg = getRowTrigger(pParse, p, pTab, orconf);
95420   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
95421
95422   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
95423   ** is a pointer to the sub-vdbe containing the trigger program.  */
95424   if( pPrg ){
95425     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
95426
95427     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
95428     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
95429     VdbeComment(
95430         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
95431
95432     /* Set the P5 operand of the OP_Program instruction to non-zero if
95433     ** recursive invocation of this trigger program is disallowed. Recursive
95434     ** invocation is disallowed if (a) the sub-program is really a trigger,
95435     ** not a foreign key action, and (b) the flag to enable recursive triggers
95436     ** is clear.  */
95437     sqlite3VdbeChangeP5(v, (u8)bRecursive);
95438   }
95439 }
95440
95441 /*
95442 ** This is called to code the required FOR EACH ROW triggers for an operation
95443 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
95444 ** is given by the op paramater. The tr_tm parameter determines whether the
95445 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
95446 ** parameter pChanges is passed the list of columns being modified.
95447 **
95448 ** If there are no triggers that fire at the specified time for the specified
95449 ** operation on pTab, this function is a no-op.
95450 **
95451 ** The reg argument is the address of the first in an array of registers 
95452 ** that contain the values substituted for the new.* and old.* references
95453 ** in the trigger program. If N is the number of columns in table pTab
95454 ** (a copy of pTab->nCol), then registers are populated as follows:
95455 **
95456 **   Register       Contains
95457 **   ------------------------------------------------------
95458 **   reg+0          OLD.rowid
95459 **   reg+1          OLD.* value of left-most column of pTab
95460 **   ...            ...
95461 **   reg+N          OLD.* value of right-most column of pTab
95462 **   reg+N+1        NEW.rowid
95463 **   reg+N+2        OLD.* value of left-most column of pTab
95464 **   ...            ...
95465 **   reg+N+N+1      NEW.* value of right-most column of pTab
95466 **
95467 ** For ON DELETE triggers, the registers containing the NEW.* values will
95468 ** never be accessed by the trigger program, so they are not allocated or 
95469 ** populated by the caller (there is no data to populate them with anyway). 
95470 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
95471 ** are never accessed, and so are not allocated by the caller. So, for an
95472 ** ON INSERT trigger, the value passed to this function as parameter reg
95473 ** is not a readable register, although registers (reg+N) through 
95474 ** (reg+N+N+1) are.
95475 **
95476 ** Parameter orconf is the default conflict resolution algorithm for the
95477 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
95478 ** is the instruction that control should jump to if a trigger program
95479 ** raises an IGNORE exception.
95480 */
95481 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
95482   Parse *pParse,       /* Parse context */
95483   Trigger *pTrigger,   /* List of triggers on table pTab */
95484   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
95485   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95486   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
95487   Table *pTab,         /* The table to code triggers from */
95488   int reg,             /* The first in an array of registers (see above) */
95489   int orconf,          /* ON CONFLICT policy */
95490   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
95491 ){
95492   Trigger *p;          /* Used to iterate through pTrigger list */
95493
95494   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
95495   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
95496   assert( (op==TK_UPDATE)==(pChanges!=0) );
95497
95498   for(p=pTrigger; p; p=p->pNext){
95499
95500     /* Sanity checking:  The schema for the trigger and for the table are
95501     ** always defined.  The trigger must be in the same schema as the table
95502     ** or else it must be a TEMP trigger. */
95503     assert( p->pSchema!=0 );
95504     assert( p->pTabSchema!=0 );
95505     assert( p->pSchema==p->pTabSchema 
95506          || p->pSchema==pParse->db->aDb[1].pSchema );
95507
95508     /* Determine whether we should code this trigger */
95509     if( p->op==op 
95510      && p->tr_tm==tr_tm 
95511      && checkColumnOverlap(p->pColumns, pChanges)
95512     ){
95513       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
95514     }
95515   }
95516 }
95517
95518 /*
95519 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
95520 ** This function returns a 32-bit bitmask indicating which columns of the 
95521 ** old.* or new.* tables actually are used by triggers. This information 
95522 ** may be used by the caller, for example, to avoid having to load the entire
95523 ** old.* record into memory when executing an UPDATE or DELETE command.
95524 **
95525 ** Bit 0 of the returned mask is set if the left-most column of the
95526 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
95527 ** the second leftmost column value is required, and so on. If there
95528 ** are more than 32 columns in the table, and at least one of the columns
95529 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
95530 **
95531 ** It is not possible to determine if the old.rowid or new.rowid column is 
95532 ** accessed by triggers. The caller must always assume that it is.
95533 **
95534 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
95535 ** applies to the old.* table. If 1, the new.* table.
95536 **
95537 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
95538 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
95539 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
95540 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
95541 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
95542 */
95543 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
95544   Parse *pParse,       /* Parse context */
95545   Trigger *pTrigger,   /* List of triggers on table pTab */
95546   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
95547   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
95548   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95549   Table *pTab,         /* The table to code triggers from */
95550   int orconf           /* Default ON CONFLICT policy for trigger steps */
95551 ){
95552   const int op = pChanges ? TK_UPDATE : TK_DELETE;
95553   u32 mask = 0;
95554   Trigger *p;
95555
95556   assert( isNew==1 || isNew==0 );
95557   for(p=pTrigger; p; p=p->pNext){
95558     if( p->op==op && (tr_tm&p->tr_tm)
95559      && checkColumnOverlap(p->pColumns,pChanges)
95560     ){
95561       TriggerPrg *pPrg;
95562       pPrg = getRowTrigger(pParse, p, pTab, orconf);
95563       if( pPrg ){
95564         mask |= pPrg->aColmask[isNew];
95565       }
95566     }
95567   }
95568
95569   return mask;
95570 }
95571
95572 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
95573
95574 /************** End of trigger.c *********************************************/
95575 /************** Begin file update.c ******************************************/
95576 /*
95577 ** 2001 September 15
95578 **
95579 ** The author disclaims copyright to this source code.  In place of
95580 ** a legal notice, here is a blessing:
95581 **
95582 **    May you do good and not evil.
95583 **    May you find forgiveness for yourself and forgive others.
95584 **    May you share freely, never taking more than you give.
95585 **
95586 *************************************************************************
95587 ** This file contains C code routines that are called by the parser
95588 ** to handle UPDATE statements.
95589 */
95590
95591 #ifndef SQLITE_OMIT_VIRTUALTABLE
95592 /* Forward declaration */
95593 static void updateVirtualTable(
95594   Parse *pParse,       /* The parsing context */
95595   SrcList *pSrc,       /* The virtual table to be modified */
95596   Table *pTab,         /* The virtual table */
95597   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
95598   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
95599   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
95600   Expr *pWhere         /* WHERE clause of the UPDATE statement */
95601 );
95602 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95603
95604 /*
95605 ** The most recently coded instruction was an OP_Column to retrieve the
95606 ** i-th column of table pTab. This routine sets the P4 parameter of the 
95607 ** OP_Column to the default value, if any.
95608 **
95609 ** The default value of a column is specified by a DEFAULT clause in the 
95610 ** column definition. This was either supplied by the user when the table
95611 ** was created, or added later to the table definition by an ALTER TABLE
95612 ** command. If the latter, then the row-records in the table btree on disk
95613 ** may not contain a value for the column and the default value, taken
95614 ** from the P4 parameter of the OP_Column instruction, is returned instead.
95615 ** If the former, then all row-records are guaranteed to include a value
95616 ** for the column and the P4 value is not required.
95617 **
95618 ** Column definitions created by an ALTER TABLE command may only have 
95619 ** literal default values specified: a number, null or a string. (If a more
95620 ** complicated default expression value was provided, it is evaluated 
95621 ** when the ALTER TABLE is executed and one of the literal values written
95622 ** into the sqlite_master table.)
95623 **
95624 ** Therefore, the P4 parameter is only required if the default value for
95625 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
95626 ** function is capable of transforming these types of expressions into
95627 ** sqlite3_value objects.
95628 **
95629 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
95630 ** on register iReg. This is used when an equivalent integer value is 
95631 ** stored in place of an 8-byte floating point value in order to save 
95632 ** space.
95633 */
95634 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
95635   assert( pTab!=0 );
95636   if( !pTab->pSelect ){
95637     sqlite3_value *pValue;
95638     u8 enc = ENC(sqlite3VdbeDb(v));
95639     Column *pCol = &pTab->aCol[i];
95640     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
95641     assert( i<pTab->nCol );
95642     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
95643                          pCol->affinity, &pValue);
95644     if( pValue ){
95645       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
95646     }
95647 #ifndef SQLITE_OMIT_FLOATING_POINT
95648     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
95649       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
95650     }
95651 #endif
95652   }
95653 }
95654
95655 /*
95656 ** Process an UPDATE statement.
95657 **
95658 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
95659 **          \_______/ \________/     \______/       \________________/
95660 *            onError   pTabList      pChanges             pWhere
95661 */
95662 SQLITE_PRIVATE void sqlite3Update(
95663   Parse *pParse,         /* The parser context */
95664   SrcList *pTabList,     /* The table in which we should change things */
95665   ExprList *pChanges,    /* Things to be changed */
95666   Expr *pWhere,          /* The WHERE clause.  May be null */
95667   int onError            /* How to handle constraint errors */
95668 ){
95669   int i, j;              /* Loop counters */
95670   Table *pTab;           /* The table to be updated */
95671   int addr = 0;          /* VDBE instruction address of the start of the loop */
95672   WhereInfo *pWInfo;     /* Information about the WHERE clause */
95673   Vdbe *v;               /* The virtual database engine */
95674   Index *pIdx;           /* For looping over indices */
95675   int nIdx;              /* Number of indices that need updating */
95676   int iCur;              /* VDBE Cursor number of pTab */
95677   sqlite3 *db;           /* The database structure */
95678   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
95679   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
95680                          ** an expression for the i-th column of the table.
95681                          ** aXRef[i]==-1 if the i-th column is not changed. */
95682   int chngRowid;         /* True if the record number is being changed */
95683   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
95684   int openAll = 0;       /* True if all indices need to be opened */
95685   AuthContext sContext;  /* The authorization context */
95686   NameContext sNC;       /* The name-context to resolve expressions in */
95687   int iDb;               /* Database containing the table being updated */
95688   int okOnePass;         /* True for one-pass algorithm without the FIFO */
95689   int hasFK;             /* True if foreign key processing is required */
95690
95691 #ifndef SQLITE_OMIT_TRIGGER
95692   int isView;            /* True when updating a view (INSTEAD OF trigger) */
95693   Trigger *pTrigger;     /* List of triggers on pTab, if required */
95694   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95695 #endif
95696   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
95697
95698   /* Register Allocations */
95699   int regRowCount = 0;   /* A count of rows changed */
95700   int regOldRowid;       /* The old rowid */
95701   int regNewRowid;       /* The new rowid */
95702   int regNew;
95703   int regOld = 0;
95704   int regRowSet = 0;     /* Rowset of rows to be updated */
95705
95706   memset(&sContext, 0, sizeof(sContext));
95707   db = pParse->db;
95708   if( pParse->nErr || db->mallocFailed ){
95709     goto update_cleanup;
95710   }
95711   assert( pTabList->nSrc==1 );
95712
95713   /* Locate the table which we want to update. 
95714   */
95715   pTab = sqlite3SrcListLookup(pParse, pTabList);
95716   if( pTab==0 ) goto update_cleanup;
95717   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95718
95719   /* Figure out if we have any triggers and if the table being
95720   ** updated is a view.
95721   */
95722 #ifndef SQLITE_OMIT_TRIGGER
95723   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
95724   isView = pTab->pSelect!=0;
95725   assert( pTrigger || tmask==0 );
95726 #else
95727 # define pTrigger 0
95728 # define isView 0
95729 # define tmask 0
95730 #endif
95731 #ifdef SQLITE_OMIT_VIEW
95732 # undef isView
95733 # define isView 0
95734 #endif
95735
95736   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95737     goto update_cleanup;
95738   }
95739   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
95740     goto update_cleanup;
95741   }
95742   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
95743   if( aXRef==0 ) goto update_cleanup;
95744   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
95745
95746   /* Allocate a cursors for the main database table and for all indices.
95747   ** The index cursors might not be used, but if they are used they
95748   ** need to occur right after the database cursor.  So go ahead and
95749   ** allocate enough space, just in case.
95750   */
95751   pTabList->a[0].iCursor = iCur = pParse->nTab++;
95752   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95753     pParse->nTab++;
95754   }
95755
95756   /* Initialize the name-context */
95757   memset(&sNC, 0, sizeof(sNC));
95758   sNC.pParse = pParse;
95759   sNC.pSrcList = pTabList;
95760
95761   /* Resolve the column names in all the expressions of the
95762   ** of the UPDATE statement.  Also find the column index
95763   ** for each column to be updated in the pChanges array.  For each
95764   ** column to be updated, make sure we have authorization to change
95765   ** that column.
95766   */
95767   chngRowid = 0;
95768   for(i=0; i<pChanges->nExpr; i++){
95769     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
95770       goto update_cleanup;
95771     }
95772     for(j=0; j<pTab->nCol; j++){
95773       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
95774         if( j==pTab->iPKey ){
95775           chngRowid = 1;
95776           pRowidExpr = pChanges->a[i].pExpr;
95777         }
95778         aXRef[j] = i;
95779         break;
95780       }
95781     }
95782     if( j>=pTab->nCol ){
95783       if( sqlite3IsRowid(pChanges->a[i].zName) ){
95784         chngRowid = 1;
95785         pRowidExpr = pChanges->a[i].pExpr;
95786       }else{
95787         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
95788         pParse->checkSchema = 1;
95789         goto update_cleanup;
95790       }
95791     }
95792 #ifndef SQLITE_OMIT_AUTHORIZATION
95793     {
95794       int rc;
95795       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
95796                            pTab->aCol[j].zName, db->aDb[iDb].zName);
95797       if( rc==SQLITE_DENY ){
95798         goto update_cleanup;
95799       }else if( rc==SQLITE_IGNORE ){
95800         aXRef[j] = -1;
95801       }
95802     }
95803 #endif
95804   }
95805
95806   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
95807
95808   /* Allocate memory for the array aRegIdx[].  There is one entry in the
95809   ** array for each index associated with table being updated.  Fill in
95810   ** the value with a register number for indices that are to be used
95811   ** and with zero for unused indices.
95812   */
95813   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
95814   if( nIdx>0 ){
95815     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
95816     if( aRegIdx==0 ) goto update_cleanup;
95817   }
95818   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
95819     int reg;
95820     if( chngRowid ){
95821       reg = ++pParse->nMem;
95822     }else{
95823       reg = 0;
95824       for(i=0; i<pIdx->nColumn; i++){
95825         if( aXRef[pIdx->aiColumn[i]]>=0 ){
95826           reg = ++pParse->nMem;
95827           break;
95828         }
95829       }
95830     }
95831     aRegIdx[j] = reg;
95832   }
95833
95834   /* Begin generating code. */
95835   v = sqlite3GetVdbe(pParse);
95836   if( v==0 ) goto update_cleanup;
95837   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
95838   sqlite3BeginWriteOperation(pParse, 1, iDb);
95839
95840 #ifndef SQLITE_OMIT_VIRTUALTABLE
95841   /* Virtual tables must be handled separately */
95842   if( IsVirtual(pTab) ){
95843     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
95844                        pWhere);
95845     pWhere = 0;
95846     pTabList = 0;
95847     goto update_cleanup;
95848   }
95849 #endif
95850
95851   /* Allocate required registers. */
95852   regOldRowid = regNewRowid = ++pParse->nMem;
95853   if( pTrigger || hasFK ){
95854     regOld = pParse->nMem + 1;
95855     pParse->nMem += pTab->nCol;
95856   }
95857   if( chngRowid || pTrigger || hasFK ){
95858     regNewRowid = ++pParse->nMem;
95859   }
95860   regNew = pParse->nMem + 1;
95861   pParse->nMem += pTab->nCol;
95862
95863   /* Start the view context. */
95864   if( isView ){
95865     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
95866   }
95867
95868   /* If we are trying to update a view, realize that view into
95869   ** a ephemeral table.
95870   */
95871 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95872   if( isView ){
95873     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
95874   }
95875 #endif
95876
95877   /* Resolve the column names in all the expressions in the
95878   ** WHERE clause.
95879   */
95880   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
95881     goto update_cleanup;
95882   }
95883
95884   /* Begin the database scan
95885   */
95886   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
95887   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
95888   if( pWInfo==0 ) goto update_cleanup;
95889   okOnePass = pWInfo->okOnePass;
95890
95891   /* Remember the rowid of every item to be updated.
95892   */
95893   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
95894   if( !okOnePass ){
95895     regRowSet = ++pParse->nMem;
95896     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
95897   }
95898
95899   /* End the database scan loop.
95900   */
95901   sqlite3WhereEnd(pWInfo);
95902
95903   /* Initialize the count of updated rows
95904   */
95905   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
95906     regRowCount = ++pParse->nMem;
95907     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
95908   }
95909
95910   if( !isView ){
95911     /* 
95912     ** Open every index that needs updating.  Note that if any
95913     ** index could potentially invoke a REPLACE conflict resolution 
95914     ** action, then we need to open all indices because we might need
95915     ** to be deleting some records.
95916     */
95917     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
95918     if( onError==OE_Replace ){
95919       openAll = 1;
95920     }else{
95921       openAll = 0;
95922       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95923         if( pIdx->onError==OE_Replace ){
95924           openAll = 1;
95925           break;
95926         }
95927       }
95928     }
95929     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
95930       if( openAll || aRegIdx[i]>0 ){
95931         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
95932         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
95933                        (char*)pKey, P4_KEYINFO_HANDOFF);
95934         assert( pParse->nTab>iCur+i+1 );
95935       }
95936     }
95937   }
95938
95939   /* Top of the update loop */
95940   if( okOnePass ){
95941     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
95942     addr = sqlite3VdbeAddOp0(v, OP_Goto);
95943     sqlite3VdbeJumpHere(v, a1);
95944   }else{
95945     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
95946   }
95947
95948   /* Make cursor iCur point to the record that is being updated. If
95949   ** this record does not exist for some reason (deleted by a trigger,
95950   ** for example, then jump to the next iteration of the RowSet loop.  */
95951   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
95952
95953   /* If the record number will change, set register regNewRowid to
95954   ** contain the new value. If the record number is not being modified,
95955   ** then regNewRowid is the same register as regOldRowid, which is
95956   ** already populated.  */
95957   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
95958   if( chngRowid ){
95959     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
95960     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
95961   }
95962
95963   /* If there are triggers on this table, populate an array of registers 
95964   ** with the required old.* column data.  */
95965   if( hasFK || pTrigger ){
95966     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
95967     oldmask |= sqlite3TriggerColmask(pParse, 
95968         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
95969     );
95970     for(i=0; i<pTab->nCol; i++){
95971       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
95972         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
95973       }else{
95974         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
95975       }
95976     }
95977     if( chngRowid==0 ){
95978       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
95979     }
95980   }
95981
95982   /* Populate the array of registers beginning at regNew with the new
95983   ** row data. This array is used to check constaints, create the new
95984   ** table and index records, and as the values for any new.* references
95985   ** made by triggers.
95986   **
95987   ** If there are one or more BEFORE triggers, then do not populate the
95988   ** registers associated with columns that are (a) not modified by
95989   ** this UPDATE statement and (b) not accessed by new.* references. The
95990   ** values for registers not modified by the UPDATE must be reloaded from 
95991   ** the database after the BEFORE triggers are fired anyway (as the trigger 
95992   ** may have modified them). So not loading those that are not going to
95993   ** be used eliminates some redundant opcodes.
95994   */
95995   newmask = sqlite3TriggerColmask(
95996       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
95997   );
95998   for(i=0; i<pTab->nCol; i++){
95999     if( i==pTab->iPKey ){
96000       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
96001     }else{
96002       j = aXRef[i];
96003       if( j>=0 ){
96004         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
96005       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
96006         /* This branch loads the value of a column that will not be changed 
96007         ** into a register. This is done if there are no BEFORE triggers, or
96008         ** if there are one or more BEFORE triggers that use this value via
96009         ** a new.* reference in a trigger program.
96010         */
96011         testcase( i==31 );
96012         testcase( i==32 );
96013         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96014         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96015       }
96016     }
96017   }
96018
96019   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96020   ** verified. One could argue that this is wrong.
96021   */
96022   if( tmask&TRIGGER_BEFORE ){
96023     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96024     sqlite3TableAffinityStr(v, pTab);
96025     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96026         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96027
96028     /* The row-trigger may have deleted the row being updated. In this
96029     ** case, jump to the next row. No updates or AFTER triggers are 
96030     ** required. This behaviour - what happens when the row being updated
96031     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96032     ** documentation.
96033     */
96034     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96035
96036     /* If it did not delete it, the row-trigger may still have modified 
96037     ** some of the columns of the row being updated. Load the values for 
96038     ** all columns not modified by the update statement into their 
96039     ** registers in case this has happened.
96040     */
96041     for(i=0; i<pTab->nCol; i++){
96042       if( aXRef[i]<0 && i!=pTab->iPKey ){
96043         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96044         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96045       }
96046     }
96047   }
96048
96049   if( !isView ){
96050     int j1;                       /* Address of jump instruction */
96051
96052     /* Do constraint checks. */
96053     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96054         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96055
96056     /* Do FK constraint checks. */
96057     if( hasFK ){
96058       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96059     }
96060
96061     /* Delete the index entries associated with the current record.  */
96062     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96063     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96064   
96065     /* If changing the record number, delete the old record.  */
96066     if( hasFK || chngRowid ){
96067       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96068     }
96069     sqlite3VdbeJumpHere(v, j1);
96070
96071     if( hasFK ){
96072       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96073     }
96074   
96075     /* Insert the new index entries and the new record. */
96076     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96077
96078     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96079     ** handle rows (possibly in other tables) that refer via a foreign key
96080     ** to the row just updated. */ 
96081     if( hasFK ){
96082       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96083     }
96084   }
96085
96086   /* Increment the row counter 
96087   */
96088   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96089     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96090   }
96091
96092   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96093       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96094
96095   /* Repeat the above with the next record to be updated, until
96096   ** all record selected by the WHERE clause have been updated.
96097   */
96098   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96099   sqlite3VdbeJumpHere(v, addr);
96100
96101   /* Close all tables */
96102   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96103     if( openAll || aRegIdx[i]>0 ){
96104       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96105     }
96106   }
96107   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96108
96109   /* Update the sqlite_sequence table by storing the content of the
96110   ** maximum rowid counter values recorded while inserting into
96111   ** autoincrement tables.
96112   */
96113   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96114     sqlite3AutoincrementEnd(pParse);
96115   }
96116
96117   /*
96118   ** Return the number of rows that were changed. If this routine is 
96119   ** generating code because of a call to sqlite3NestedParse(), do not
96120   ** invoke the callback function.
96121   */
96122   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96123     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96124     sqlite3VdbeSetNumCols(v, 1);
96125     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96126   }
96127
96128 update_cleanup:
96129   sqlite3AuthContextPop(&sContext);
96130   sqlite3DbFree(db, aRegIdx);
96131   sqlite3DbFree(db, aXRef);
96132   sqlite3SrcListDelete(db, pTabList);
96133   sqlite3ExprListDelete(db, pChanges);
96134   sqlite3ExprDelete(db, pWhere);
96135   return;
96136 }
96137 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96138 ** thely may interfere with compilation of other functions in this file
96139 ** (or in another file, if this file becomes part of the amalgamation).  */
96140 #ifdef isView
96141  #undef isView
96142 #endif
96143 #ifdef pTrigger
96144  #undef pTrigger
96145 #endif
96146
96147 #ifndef SQLITE_OMIT_VIRTUALTABLE
96148 /*
96149 ** Generate code for an UPDATE of a virtual table.
96150 **
96151 ** The strategy is that we create an ephemerial table that contains
96152 ** for each row to be changed:
96153 **
96154 **   (A)  The original rowid of that row.
96155 **   (B)  The revised rowid for the row. (note1)
96156 **   (C)  The content of every column in the row.
96157 **
96158 ** Then we loop over this ephemeral table and for each row in
96159 ** the ephermeral table call VUpdate.
96160 **
96161 ** When finished, drop the ephemeral table.
96162 **
96163 ** (note1) Actually, if we know in advance that (A) is always the same
96164 ** as (B) we only store (A), then duplicate (A) when pulling
96165 ** it out of the ephemeral table before calling VUpdate.
96166 */
96167 static void updateVirtualTable(
96168   Parse *pParse,       /* The parsing context */
96169   SrcList *pSrc,       /* The virtual table to be modified */
96170   Table *pTab,         /* The virtual table */
96171   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
96172   Expr *pRowid,        /* Expression used to recompute the rowid */
96173   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
96174   Expr *pWhere         /* WHERE clause of the UPDATE statement */
96175 ){
96176   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
96177   ExprList *pEList = 0;     /* The result set of the SELECT statement */
96178   Select *pSelect = 0;      /* The SELECT statement */
96179   Expr *pExpr;              /* Temporary expression */
96180   int ephemTab;             /* Table holding the result of the SELECT */
96181   int i;                    /* Loop counter */
96182   int addr;                 /* Address of top of loop */
96183   int iReg;                 /* First register in set passed to OP_VUpdate */
96184   sqlite3 *db = pParse->db; /* Database connection */
96185   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96186   SelectDest dest;
96187
96188   /* Construct the SELECT statement that will find the new values for
96189   ** all updated rows. 
96190   */
96191   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96192   if( pRowid ){
96193     pEList = sqlite3ExprListAppend(pParse, pEList,
96194                                    sqlite3ExprDup(db, pRowid, 0));
96195   }
96196   assert( pTab->iPKey<0 );
96197   for(i=0; i<pTab->nCol; i++){
96198     if( aXRef[i]>=0 ){
96199       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96200     }else{
96201       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96202     }
96203     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96204   }
96205   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96206   
96207   /* Create the ephemeral table into which the update results will
96208   ** be stored.
96209   */
96210   assert( v );
96211   ephemTab = pParse->nTab++;
96212   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96213   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96214
96215   /* fill the ephemeral table 
96216   */
96217   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96218   sqlite3Select(pParse, pSelect, &dest);
96219
96220   /* Generate code to scan the ephemeral table and call VUpdate. */
96221   iReg = ++pParse->nMem;
96222   pParse->nMem += pTab->nCol+1;
96223   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96224   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
96225   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96226   for(i=0; i<pTab->nCol; i++){
96227     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96228   }
96229   sqlite3VtabMakeWritable(pParse, pTab);
96230   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96231   sqlite3MayAbort(pParse);
96232   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96233   sqlite3VdbeJumpHere(v, addr);
96234   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96235
96236   /* Cleanup */
96237   sqlite3SelectDelete(db, pSelect);  
96238 }
96239 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96240
96241 /************** End of update.c **********************************************/
96242 /************** Begin file vacuum.c ******************************************/
96243 /*
96244 ** 2003 April 6
96245 **
96246 ** The author disclaims copyright to this source code.  In place of
96247 ** a legal notice, here is a blessing:
96248 **
96249 **    May you do good and not evil.
96250 **    May you find forgiveness for yourself and forgive others.
96251 **    May you share freely, never taking more than you give.
96252 **
96253 *************************************************************************
96254 ** This file contains code used to implement the VACUUM command.
96255 **
96256 ** Most of the code in this file may be omitted by defining the
96257 ** SQLITE_OMIT_VACUUM macro.
96258 */
96259
96260 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96261 /*
96262 ** Finalize a prepared statement.  If there was an error, store the
96263 ** text of the error message in *pzErrMsg.  Return the result code.
96264 */
96265 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96266   int rc;
96267   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96268   if( rc ){
96269     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96270   }
96271   return rc;
96272 }
96273
96274 /*
96275 ** Execute zSql on database db. Return an error code.
96276 */
96277 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96278   sqlite3_stmt *pStmt;
96279   VVA_ONLY( int rc; )
96280   if( !zSql ){
96281     return SQLITE_NOMEM;
96282   }
96283   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96284     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96285     return sqlite3_errcode(db);
96286   }
96287   VVA_ONLY( rc = ) sqlite3_step(pStmt);
96288   assert( rc!=SQLITE_ROW );
96289   return vacuumFinalize(db, pStmt, pzErrMsg);
96290 }
96291
96292 /*
96293 ** Execute zSql on database db. The statement returns exactly
96294 ** one column. Execute this as SQL on the same database.
96295 */
96296 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96297   sqlite3_stmt *pStmt;
96298   int rc;
96299
96300   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96301   if( rc!=SQLITE_OK ) return rc;
96302
96303   while( SQLITE_ROW==sqlite3_step(pStmt) ){
96304     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96305     if( rc!=SQLITE_OK ){
96306       vacuumFinalize(db, pStmt, pzErrMsg);
96307       return rc;
96308     }
96309   }
96310
96311   return vacuumFinalize(db, pStmt, pzErrMsg);
96312 }
96313
96314 /*
96315 ** The non-standard VACUUM command is used to clean up the database,
96316 ** collapse free space, etc.  It is modelled after the VACUUM command
96317 ** in PostgreSQL.
96318 **
96319 ** In version 1.0.x of SQLite, the VACUUM command would call
96320 ** gdbm_reorganize() on all the database tables.  But beginning
96321 ** with 2.0.0, SQLite no longer uses GDBM so this command has
96322 ** become a no-op.
96323 */
96324 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96325   Vdbe *v = sqlite3GetVdbe(pParse);
96326   if( v ){
96327     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
96328   }
96329   return;
96330 }
96331
96332 /*
96333 ** This routine implements the OP_Vacuum opcode of the VDBE.
96334 */
96335 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
96336   int rc = SQLITE_OK;     /* Return code from service routines */
96337   Btree *pMain;           /* The database being vacuumed */
96338   Btree *pTemp;           /* The temporary database we vacuum into */
96339   char *zSql = 0;         /* SQL statements */
96340   int saved_flags;        /* Saved value of the db->flags */
96341   int saved_nChange;      /* Saved value of db->nChange */
96342   int saved_nTotalChange; /* Saved value of db->nTotalChange */
96343   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
96344   Db *pDb = 0;            /* Database to detach at end of vacuum */
96345   int isMemDb;            /* True if vacuuming a :memory: database */
96346   int nRes;               /* Bytes of reserved space at the end of each page */
96347   int nDb;                /* Number of attached databases */
96348
96349   if( !db->autoCommit ){
96350     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
96351     return SQLITE_ERROR;
96352   }
96353   if( db->activeVdbeCnt>1 ){
96354     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
96355     return SQLITE_ERROR;
96356   }
96357
96358   /* Save the current value of the database flags so that it can be 
96359   ** restored before returning. Then set the writable-schema flag, and
96360   ** disable CHECK and foreign key constraints.  */
96361   saved_flags = db->flags;
96362   saved_nChange = db->nChange;
96363   saved_nTotalChange = db->nTotalChange;
96364   saved_xTrace = db->xTrace;
96365   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
96366   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
96367   db->xTrace = 0;
96368
96369   pMain = db->aDb[0].pBt;
96370   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
96371
96372   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
96373   ** can be set to 'off' for this file, as it is not recovered if a crash
96374   ** occurs anyway. The integrity of the database is maintained by a
96375   ** (possibly synchronous) transaction opened on the main database before
96376   ** sqlite3BtreeCopyFile() is called.
96377   **
96378   ** An optimisation would be to use a non-journaled pager.
96379   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
96380   ** that actually made the VACUUM run slower.  Very little journalling
96381   ** actually occurs when doing a vacuum since the vacuum_db is initially
96382   ** empty.  Only the journal header is written.  Apparently it takes more
96383   ** time to parse and run the PRAGMA to turn journalling off than it does
96384   ** to write the journal header file.
96385   */
96386   nDb = db->nDb;
96387   if( sqlite3TempInMemory(db) ){
96388     zSql = "ATTACH ':memory:' AS vacuum_db;";
96389   }else{
96390     zSql = "ATTACH '' AS vacuum_db;";
96391   }
96392   rc = execSql(db, pzErrMsg, zSql);
96393   if( db->nDb>nDb ){
96394     pDb = &db->aDb[db->nDb-1];
96395     assert( strcmp(pDb->zName,"vacuum_db")==0 );
96396   }
96397   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96398   pTemp = db->aDb[db->nDb-1].pBt;
96399
96400   /* The call to execSql() to attach the temp database has left the file
96401   ** locked (as there was more than one active statement when the transaction
96402   ** to read the schema was concluded. Unlock it here so that this doesn't
96403   ** cause problems for the call to BtreeSetPageSize() below.  */
96404   sqlite3BtreeCommit(pTemp);
96405
96406   nRes = sqlite3BtreeGetReserve(pMain);
96407
96408   /* A VACUUM cannot change the pagesize of an encrypted database. */
96409 #ifdef SQLITE_HAS_CODEC
96410   if( db->nextPagesize ){
96411     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96412     int nKey;
96413     char *zKey;
96414     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96415     if( nKey ) db->nextPagesize = 0;
96416   }
96417 #endif
96418
96419   /* Do not attempt to change the page size for a WAL database */
96420   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
96421                                                ==PAGER_JOURNALMODE_WAL ){
96422     db->nextPagesize = 0;
96423   }
96424
96425   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
96426    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
96427    || NEVER(db->mallocFailed)
96428   ){
96429     rc = SQLITE_NOMEM;
96430     goto end_of_vacuum;
96431   }
96432   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
96433   if( rc!=SQLITE_OK ){
96434     goto end_of_vacuum;
96435   }
96436
96437 #ifndef SQLITE_OMIT_AUTOVACUUM
96438   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
96439                                            sqlite3BtreeGetAutoVacuum(pMain));
96440 #endif
96441
96442   /* Begin a transaction */
96443   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
96444   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96445
96446   /* Query the schema of the main database. Create a mirror schema
96447   ** in the temporary database.
96448   */
96449   rc = execExecSql(db, pzErrMsg,
96450       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
96451       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
96452       "   AND rootpage>0"
96453   );
96454   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96455   rc = execExecSql(db, pzErrMsg,
96456       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
96457       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
96458   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96459   rc = execExecSql(db, pzErrMsg,
96460       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
96461       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
96462   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96463
96464   /* Loop through the tables in the main database. For each, do
96465   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
96466   ** the contents to the temporary database.
96467   */
96468   rc = execExecSql(db, pzErrMsg,
96469       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96470       "|| ' SELECT * FROM main.' || quote(name) || ';'"
96471       "FROM main.sqlite_master "
96472       "WHERE type = 'table' AND name!='sqlite_sequence' "
96473       "  AND rootpage>0"
96474   );
96475   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96476
96477   /* Copy over the sequence table
96478   */
96479   rc = execExecSql(db, pzErrMsg,
96480       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
96481       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
96482   );
96483   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96484   rc = execExecSql(db, pzErrMsg,
96485       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96486       "|| ' SELECT * FROM main.' || quote(name) || ';' "
96487       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
96488   );
96489   if( rc!=SQLITE_OK ) goto end_of_vacuum;
96490
96491
96492   /* Copy the triggers, views, and virtual tables from the main database
96493   ** over to the temporary database.  None of these objects has any
96494   ** associated storage, so all we have to do is copy their entries
96495   ** from the SQLITE_MASTER table.
96496   */
96497   rc = execSql(db, pzErrMsg,
96498       "INSERT INTO vacuum_db.sqlite_master "
96499       "  SELECT type, name, tbl_name, rootpage, sql"
96500       "    FROM main.sqlite_master"
96501       "   WHERE type='view' OR type='trigger'"
96502       "      OR (type='table' AND rootpage=0)"
96503   );
96504   if( rc ) goto end_of_vacuum;
96505
96506   /* At this point, unless the main db was completely empty, there is now a
96507   ** transaction open on the vacuum database, but not on the main database.
96508   ** Open a btree level transaction on the main database. This allows a
96509   ** call to sqlite3BtreeCopyFile(). The main database btree level
96510   ** transaction is then committed, so the SQL level never knows it was
96511   ** opened for writing. This way, the SQL transaction used to create the
96512   ** temporary database never needs to be committed.
96513   */
96514   {
96515     u32 meta;
96516     int i;
96517
96518     /* This array determines which meta meta values are preserved in the
96519     ** vacuum.  Even entries are the meta value number and odd entries
96520     ** are an increment to apply to the meta value after the vacuum.
96521     ** The increment is used to increase the schema cookie so that other
96522     ** connections to the same database will know to reread the schema.
96523     */
96524     static const unsigned char aCopy[] = {
96525        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
96526        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
96527        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
96528        BTREE_USER_VERSION,       0,  /* Preserve the user version */
96529     };
96530
96531     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
96532     assert( 1==sqlite3BtreeIsInTrans(pMain) );
96533
96534     /* Copy Btree meta values */
96535     for(i=0; i<ArraySize(aCopy); i+=2){
96536       /* GetMeta() and UpdateMeta() cannot fail in this context because
96537       ** we already have page 1 loaded into cache and marked dirty. */
96538       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
96539       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
96540       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
96541     }
96542
96543     rc = sqlite3BtreeCopyFile(pMain, pTemp);
96544     if( rc!=SQLITE_OK ) goto end_of_vacuum;
96545     rc = sqlite3BtreeCommit(pTemp);
96546     if( rc!=SQLITE_OK ) goto end_of_vacuum;
96547 #ifndef SQLITE_OMIT_AUTOVACUUM
96548     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
96549 #endif
96550   }
96551
96552   assert( rc==SQLITE_OK );
96553   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
96554
96555 end_of_vacuum:
96556   /* Restore the original value of db->flags */
96557   db->flags = saved_flags;
96558   db->nChange = saved_nChange;
96559   db->nTotalChange = saved_nTotalChange;
96560   db->xTrace = saved_xTrace;
96561   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
96562
96563   /* Currently there is an SQL level transaction open on the vacuum
96564   ** database. No locks are held on any other files (since the main file
96565   ** was committed at the btree level). So it safe to end the transaction
96566   ** by manually setting the autoCommit flag to true and detaching the
96567   ** vacuum database. The vacuum_db journal file is deleted when the pager
96568   ** is closed by the DETACH.
96569   */
96570   db->autoCommit = 1;
96571
96572   if( pDb ){
96573     sqlite3BtreeClose(pDb->pBt);
96574     pDb->pBt = 0;
96575     pDb->pSchema = 0;
96576   }
96577
96578   /* This both clears the schemas and reduces the size of the db->aDb[]
96579   ** array. */ 
96580   sqlite3ResetInternalSchema(db, -1);
96581
96582   return rc;
96583 }
96584
96585 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
96586
96587 /************** End of vacuum.c **********************************************/
96588 /************** Begin file vtab.c ********************************************/
96589 /*
96590 ** 2006 June 10
96591 **
96592 ** The author disclaims copyright to this source code.  In place of
96593 ** a legal notice, here is a blessing:
96594 **
96595 **    May you do good and not evil.
96596 **    May you find forgiveness for yourself and forgive others.
96597 **    May you share freely, never taking more than you give.
96598 **
96599 *************************************************************************
96600 ** This file contains code used to help implement virtual tables.
96601 */
96602 #ifndef SQLITE_OMIT_VIRTUALTABLE
96603
96604 /*
96605 ** The actual function that does the work of creating a new module.
96606 ** This function implements the sqlite3_create_module() and
96607 ** sqlite3_create_module_v2() interfaces.
96608 */
96609 static int createModule(
96610   sqlite3 *db,                    /* Database in which module is registered */
96611   const char *zName,              /* Name assigned to this module */
96612   const sqlite3_module *pModule,  /* The definition of the module */
96613   void *pAux,                     /* Context pointer for xCreate/xConnect */
96614   void (*xDestroy)(void *)        /* Module destructor function */
96615 ){
96616   int rc, nName;
96617   Module *pMod;
96618
96619   sqlite3_mutex_enter(db->mutex);
96620   nName = sqlite3Strlen30(zName);
96621   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
96622   if( pMod ){
96623     Module *pDel;
96624     char *zCopy = (char *)(&pMod[1]);
96625     memcpy(zCopy, zName, nName+1);
96626     pMod->zName = zCopy;
96627     pMod->pModule = pModule;
96628     pMod->pAux = pAux;
96629     pMod->xDestroy = xDestroy;
96630     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
96631     if( pDel && pDel->xDestroy ){
96632       pDel->xDestroy(pDel->pAux);
96633     }
96634     sqlite3DbFree(db, pDel);
96635     if( pDel==pMod ){
96636       db->mallocFailed = 1;
96637     }
96638     sqlite3ResetInternalSchema(db, -1);
96639   }else if( xDestroy ){
96640     xDestroy(pAux);
96641   }
96642   rc = sqlite3ApiExit(db, SQLITE_OK);
96643   sqlite3_mutex_leave(db->mutex);
96644   return rc;
96645 }
96646
96647
96648 /*
96649 ** External API function used to create a new virtual-table module.
96650 */
96651 SQLITE_API int sqlite3_create_module(
96652   sqlite3 *db,                    /* Database in which module is registered */
96653   const char *zName,              /* Name assigned to this module */
96654   const sqlite3_module *pModule,  /* The definition of the module */
96655   void *pAux                      /* Context pointer for xCreate/xConnect */
96656 ){
96657   return createModule(db, zName, pModule, pAux, 0);
96658 }
96659
96660 /*
96661 ** External API function used to create a new virtual-table module.
96662 */
96663 SQLITE_API int sqlite3_create_module_v2(
96664   sqlite3 *db,                    /* Database in which module is registered */
96665   const char *zName,              /* Name assigned to this module */
96666   const sqlite3_module *pModule,  /* The definition of the module */
96667   void *pAux,                     /* Context pointer for xCreate/xConnect */
96668   void (*xDestroy)(void *)        /* Module destructor function */
96669 ){
96670   return createModule(db, zName, pModule, pAux, xDestroy);
96671 }
96672
96673 /*
96674 ** Lock the virtual table so that it cannot be disconnected.
96675 ** Locks nest.  Every lock should have a corresponding unlock.
96676 ** If an unlock is omitted, resources leaks will occur.  
96677 **
96678 ** If a disconnect is attempted while a virtual table is locked,
96679 ** the disconnect is deferred until all locks have been removed.
96680 */
96681 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
96682   pVTab->nRef++;
96683 }
96684
96685
96686 /*
96687 ** pTab is a pointer to a Table structure representing a virtual-table.
96688 ** Return a pointer to the VTable object used by connection db to access 
96689 ** this virtual-table, if one has been created, or NULL otherwise.
96690 */
96691 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
96692   VTable *pVtab;
96693   assert( IsVirtual(pTab) );
96694   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
96695   return pVtab;
96696 }
96697
96698 /*
96699 ** Decrement the ref-count on a virtual table object. When the ref-count
96700 ** reaches zero, call the xDisconnect() method to delete the object.
96701 */
96702 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
96703   sqlite3 *db = pVTab->db;
96704
96705   assert( db );
96706   assert( pVTab->nRef>0 );
96707   assert( sqlite3SafetyCheckOk(db) );
96708
96709   pVTab->nRef--;
96710   if( pVTab->nRef==0 ){
96711     sqlite3_vtab *p = pVTab->pVtab;
96712     if( p ){
96713       p->pModule->xDisconnect(p);
96714     }
96715     sqlite3DbFree(db, pVTab);
96716   }
96717 }
96718
96719 /*
96720 ** Table p is a virtual table. This function moves all elements in the
96721 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
96722 ** database connections to be disconnected at the next opportunity. 
96723 ** Except, if argument db is not NULL, then the entry associated with
96724 ** connection db is left in the p->pVTable list.
96725 */
96726 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
96727   VTable *pRet = 0;
96728   VTable *pVTable = p->pVTable;
96729   p->pVTable = 0;
96730
96731   /* Assert that the mutex (if any) associated with the BtShared database 
96732   ** that contains table p is held by the caller. See header comments 
96733   ** above function sqlite3VtabUnlockList() for an explanation of why
96734   ** this makes it safe to access the sqlite3.pDisconnect list of any
96735   ** database connection that may have an entry in the p->pVTable list.
96736   */
96737   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
96738
96739   while( pVTable ){
96740     sqlite3 *db2 = pVTable->db;
96741     VTable *pNext = pVTable->pNext;
96742     assert( db2 );
96743     if( db2==db ){
96744       pRet = pVTable;
96745       p->pVTable = pRet;
96746       pRet->pNext = 0;
96747     }else{
96748       pVTable->pNext = db2->pDisconnect;
96749       db2->pDisconnect = pVTable;
96750     }
96751     pVTable = pNext;
96752   }
96753
96754   assert( !db || pRet );
96755   return pRet;
96756 }
96757
96758
96759 /*
96760 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
96761 **
96762 ** This function may only be called when the mutexes associated with all
96763 ** shared b-tree databases opened using connection db are held by the 
96764 ** caller. This is done to protect the sqlite3.pDisconnect list. The
96765 ** sqlite3.pDisconnect list is accessed only as follows:
96766 **
96767 **   1) By this function. In this case, all BtShared mutexes and the mutex
96768 **      associated with the database handle itself must be held.
96769 **
96770 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
96771 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
96772 **      associated with the database the virtual table is stored in is held
96773 **      or, if the virtual table is stored in a non-sharable database, then
96774 **      the database handle mutex is held.
96775 **
96776 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
96777 ** by multiple threads. It is thread-safe.
96778 */
96779 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
96780   VTable *p = db->pDisconnect;
96781   db->pDisconnect = 0;
96782
96783   assert( sqlite3BtreeHoldsAllMutexes(db) );
96784   assert( sqlite3_mutex_held(db->mutex) );
96785
96786   if( p ){
96787     sqlite3ExpirePreparedStatements(db);
96788     do {
96789       VTable *pNext = p->pNext;
96790       sqlite3VtabUnlock(p);
96791       p = pNext;
96792     }while( p );
96793   }
96794 }
96795
96796 /*
96797 ** Clear any and all virtual-table information from the Table record.
96798 ** This routine is called, for example, just before deleting the Table
96799 ** record.
96800 **
96801 ** Since it is a virtual-table, the Table structure contains a pointer
96802 ** to the head of a linked list of VTable structures. Each VTable 
96803 ** structure is associated with a single sqlite3* user of the schema.
96804 ** The reference count of the VTable structure associated with database 
96805 ** connection db is decremented immediately (which may lead to the 
96806 ** structure being xDisconnected and free). Any other VTable structures
96807 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
96808 ** database connection.
96809 */
96810 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
96811   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
96812   if( p->azModuleArg ){
96813     int i;
96814     for(i=0; i<p->nModuleArg; i++){
96815       sqlite3DbFree(db, p->azModuleArg[i]);
96816     }
96817     sqlite3DbFree(db, p->azModuleArg);
96818   }
96819 }
96820
96821 /*
96822 ** Add a new module argument to pTable->azModuleArg[].
96823 ** The string is not copied - the pointer is stored.  The
96824 ** string will be freed automatically when the table is
96825 ** deleted.
96826 */
96827 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
96828   int i = pTable->nModuleArg++;
96829   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
96830   char **azModuleArg;
96831   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
96832   if( azModuleArg==0 ){
96833     int j;
96834     for(j=0; j<i; j++){
96835       sqlite3DbFree(db, pTable->azModuleArg[j]);
96836     }
96837     sqlite3DbFree(db, zArg);
96838     sqlite3DbFree(db, pTable->azModuleArg);
96839     pTable->nModuleArg = 0;
96840   }else{
96841     azModuleArg[i] = zArg;
96842     azModuleArg[i+1] = 0;
96843   }
96844   pTable->azModuleArg = azModuleArg;
96845 }
96846
96847 /*
96848 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
96849 ** statement.  The module name has been parsed, but the optional list
96850 ** of parameters that follow the module name are still pending.
96851 */
96852 SQLITE_PRIVATE void sqlite3VtabBeginParse(
96853   Parse *pParse,        /* Parsing context */
96854   Token *pName1,        /* Name of new table, or database name */
96855   Token *pName2,        /* Name of new table or NULL */
96856   Token *pModuleName    /* Name of the module for the virtual table */
96857 ){
96858   int iDb;              /* The database the table is being created in */
96859   Table *pTable;        /* The new virtual table */
96860   sqlite3 *db;          /* Database connection */
96861
96862   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
96863   pTable = pParse->pNewTable;
96864   if( pTable==0 ) return;
96865   assert( 0==pTable->pIndex );
96866
96867   db = pParse->db;
96868   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
96869   assert( iDb>=0 );
96870
96871   pTable->tabFlags |= TF_Virtual;
96872   pTable->nModuleArg = 0;
96873   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
96874   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
96875   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
96876   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
96877
96878 #ifndef SQLITE_OMIT_AUTHORIZATION
96879   /* Creating a virtual table invokes the authorization callback twice.
96880   ** The first invocation, to obtain permission to INSERT a row into the
96881   ** sqlite_master table, has already been made by sqlite3StartTable().
96882   ** The second call, to obtain permission to create the table, is made now.
96883   */
96884   if( pTable->azModuleArg ){
96885     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
96886             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
96887   }
96888 #endif
96889 }
96890
96891 /*
96892 ** This routine takes the module argument that has been accumulating
96893 ** in pParse->zArg[] and appends it to the list of arguments on the
96894 ** virtual table currently under construction in pParse->pTable.
96895 */
96896 static void addArgumentToVtab(Parse *pParse){
96897   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
96898     const char *z = (const char*)pParse->sArg.z;
96899     int n = pParse->sArg.n;
96900     sqlite3 *db = pParse->db;
96901     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
96902   }
96903 }
96904
96905 /*
96906 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
96907 ** has been completely parsed.
96908 */
96909 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
96910   Table *pTab = pParse->pNewTable;  /* The table being constructed */
96911   sqlite3 *db = pParse->db;         /* The database connection */
96912
96913   if( pTab==0 ) return;
96914   addArgumentToVtab(pParse);
96915   pParse->sArg.z = 0;
96916   if( pTab->nModuleArg<1 ) return;
96917   
96918   /* If the CREATE VIRTUAL TABLE statement is being entered for the
96919   ** first time (in other words if the virtual table is actually being
96920   ** created now instead of just being read out of sqlite_master) then
96921   ** do additional initialization work and store the statement text
96922   ** in the sqlite_master table.
96923   */
96924   if( !db->init.busy ){
96925     char *zStmt;
96926     char *zWhere;
96927     int iDb;
96928     Vdbe *v;
96929
96930     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
96931     if( pEnd ){
96932       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
96933     }
96934     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
96935
96936     /* A slot for the record has already been allocated in the 
96937     ** SQLITE_MASTER table.  We just need to update that slot with all
96938     ** the information we've collected.  
96939     **
96940     ** The VM register number pParse->regRowid holds the rowid of an
96941     ** entry in the sqlite_master table tht was created for this vtab
96942     ** by sqlite3StartTable().
96943     */
96944     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96945     sqlite3NestedParse(pParse,
96946       "UPDATE %Q.%s "
96947          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
96948        "WHERE rowid=#%d",
96949       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
96950       pTab->zName,
96951       pTab->zName,
96952       zStmt,
96953       pParse->regRowid
96954     );
96955     sqlite3DbFree(db, zStmt);
96956     v = sqlite3GetVdbe(pParse);
96957     sqlite3ChangeCookie(pParse, iDb);
96958
96959     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
96960     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
96961     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
96962     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
96963                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
96964   }
96965
96966   /* If we are rereading the sqlite_master table create the in-memory
96967   ** record of the table. The xConnect() method is not called until
96968   ** the first time the virtual table is used in an SQL statement. This
96969   ** allows a schema that contains virtual tables to be loaded before
96970   ** the required virtual table implementations are registered.  */
96971   else {
96972     Table *pOld;
96973     Schema *pSchema = pTab->pSchema;
96974     const char *zName = pTab->zName;
96975     int nName = sqlite3Strlen30(zName);
96976     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
96977     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
96978     if( pOld ){
96979       db->mallocFailed = 1;
96980       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
96981       return;
96982     }
96983     pParse->pNewTable = 0;
96984   }
96985 }
96986
96987 /*
96988 ** The parser calls this routine when it sees the first token
96989 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
96990 */
96991 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
96992   addArgumentToVtab(pParse);
96993   pParse->sArg.z = 0;
96994   pParse->sArg.n = 0;
96995 }
96996
96997 /*
96998 ** The parser calls this routine for each token after the first token
96999 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
97000 */
97001 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
97002   Token *pArg = &pParse->sArg;
97003   if( pArg->z==0 ){
97004     pArg->z = p->z;
97005     pArg->n = p->n;
97006   }else{
97007     assert(pArg->z < p->z);
97008     pArg->n = (int)(&p->z[p->n] - pArg->z);
97009   }
97010 }
97011
97012 /*
97013 ** Invoke a virtual table constructor (either xCreate or xConnect). The
97014 ** pointer to the function to invoke is passed as the fourth parameter
97015 ** to this procedure.
97016 */
97017 static int vtabCallConstructor(
97018   sqlite3 *db, 
97019   Table *pTab,
97020   Module *pMod,
97021   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97022   char **pzErr
97023 ){
97024   VTable *pVTable;
97025   int rc;
97026   const char *const*azArg = (const char *const*)pTab->azModuleArg;
97027   int nArg = pTab->nModuleArg;
97028   char *zErr = 0;
97029   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97030
97031   if( !zModuleName ){
97032     return SQLITE_NOMEM;
97033   }
97034
97035   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97036   if( !pVTable ){
97037     sqlite3DbFree(db, zModuleName);
97038     return SQLITE_NOMEM;
97039   }
97040   pVTable->db = db;
97041   pVTable->pMod = pMod;
97042
97043   assert( !db->pVTab );
97044   assert( xConstruct );
97045   db->pVTab = pTab;
97046
97047   /* Invoke the virtual table constructor */
97048   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97049   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97050
97051   if( SQLITE_OK!=rc ){
97052     if( zErr==0 ){
97053       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97054     }else {
97055       *pzErr = sqlite3MPrintf(db, "%s", zErr);
97056       sqlite3_free(zErr);
97057     }
97058     sqlite3DbFree(db, pVTable);
97059   }else if( ALWAYS(pVTable->pVtab) ){
97060     /* Justification of ALWAYS():  A correct vtab constructor must allocate
97061     ** the sqlite3_vtab object if successful.  */
97062     pVTable->pVtab->pModule = pMod->pModule;
97063     pVTable->nRef = 1;
97064     if( db->pVTab ){
97065       const char *zFormat = "vtable constructor did not declare schema: %s";
97066       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97067       sqlite3VtabUnlock(pVTable);
97068       rc = SQLITE_ERROR;
97069     }else{
97070       int iCol;
97071       /* If everything went according to plan, link the new VTable structure
97072       ** into the linked list headed by pTab->pVTable. Then loop through the 
97073       ** columns of the table to see if any of them contain the token "hidden".
97074       ** If so, set the Column.isHidden flag and remove the token from
97075       ** the type string.  */
97076       pVTable->pNext = pTab->pVTable;
97077       pTab->pVTable = pVTable;
97078
97079       for(iCol=0; iCol<pTab->nCol; iCol++){
97080         char *zType = pTab->aCol[iCol].zType;
97081         int nType;
97082         int i = 0;
97083         if( !zType ) continue;
97084         nType = sqlite3Strlen30(zType);
97085         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97086           for(i=0; i<nType; i++){
97087             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97088              && (zType[i+7]=='\0' || zType[i+7]==' ')
97089             ){
97090               i++;
97091               break;
97092             }
97093           }
97094         }
97095         if( i<nType ){
97096           int j;
97097           int nDel = 6 + (zType[i+6] ? 1 : 0);
97098           for(j=i; (j+nDel)<=nType; j++){
97099             zType[j] = zType[j+nDel];
97100           }
97101           if( zType[i]=='\0' && i>0 ){
97102             assert(zType[i-1]==' ');
97103             zType[i-1] = '\0';
97104           }
97105           pTab->aCol[iCol].isHidden = 1;
97106         }
97107       }
97108     }
97109   }
97110
97111   sqlite3DbFree(db, zModuleName);
97112   db->pVTab = 0;
97113   return rc;
97114 }
97115
97116 /*
97117 ** This function is invoked by the parser to call the xConnect() method
97118 ** of the virtual table pTab. If an error occurs, an error code is returned 
97119 ** and an error left in pParse.
97120 **
97121 ** This call is a no-op if table pTab is not a virtual table.
97122 */
97123 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97124   sqlite3 *db = pParse->db;
97125   const char *zMod;
97126   Module *pMod;
97127   int rc;
97128
97129   assert( pTab );
97130   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97131     return SQLITE_OK;
97132   }
97133
97134   /* Locate the required virtual table module */
97135   zMod = pTab->azModuleArg[0];
97136   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97137
97138   if( !pMod ){
97139     const char *zModule = pTab->azModuleArg[0];
97140     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97141     rc = SQLITE_ERROR;
97142   }else{
97143     char *zErr = 0;
97144     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97145     if( rc!=SQLITE_OK ){
97146       sqlite3ErrorMsg(pParse, "%s", zErr);
97147     }
97148     sqlite3DbFree(db, zErr);
97149   }
97150
97151   return rc;
97152 }
97153
97154 /*
97155 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
97156 */
97157 static int addToVTrans(sqlite3 *db, VTable *pVTab){
97158   const int ARRAY_INCR = 5;
97159
97160   /* Grow the sqlite3.aVTrans array if required */
97161   if( (db->nVTrans%ARRAY_INCR)==0 ){
97162     VTable **aVTrans;
97163     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97164     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97165     if( !aVTrans ){
97166       return SQLITE_NOMEM;
97167     }
97168     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97169     db->aVTrans = aVTrans;
97170   }
97171
97172   /* Add pVtab to the end of sqlite3.aVTrans */
97173   db->aVTrans[db->nVTrans++] = pVTab;
97174   sqlite3VtabLock(pVTab);
97175   return SQLITE_OK;
97176 }
97177
97178 /*
97179 ** This function is invoked by the vdbe to call the xCreate method
97180 ** of the virtual table named zTab in database iDb. 
97181 **
97182 ** If an error occurs, *pzErr is set to point an an English language
97183 ** description of the error and an SQLITE_XXX error code is returned.
97184 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97185 */
97186 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97187   int rc = SQLITE_OK;
97188   Table *pTab;
97189   Module *pMod;
97190   const char *zMod;
97191
97192   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97193   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97194
97195   /* Locate the required virtual table module */
97196   zMod = pTab->azModuleArg[0];
97197   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97198
97199   /* If the module has been registered and includes a Create method, 
97200   ** invoke it now. If the module has not been registered, return an 
97201   ** error. Otherwise, do nothing.
97202   */
97203   if( !pMod ){
97204     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97205     rc = SQLITE_ERROR;
97206   }else{
97207     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97208   }
97209
97210   /* Justification of ALWAYS():  The xConstructor method is required to
97211   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97212   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97213       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
97214   }
97215
97216   return rc;
97217 }
97218
97219 /*
97220 ** This function is used to set the schema of a virtual table.  It is only
97221 ** valid to call this function from within the xCreate() or xConnect() of a
97222 ** virtual table module.
97223 */
97224 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97225   Parse *pParse;
97226
97227   int rc = SQLITE_OK;
97228   Table *pTab;
97229   char *zErr = 0;
97230
97231   sqlite3_mutex_enter(db->mutex);
97232   pTab = db->pVTab;
97233   if( !pTab ){
97234     sqlite3Error(db, SQLITE_MISUSE, 0);
97235     sqlite3_mutex_leave(db->mutex);
97236     return SQLITE_MISUSE_BKPT;
97237   }
97238   assert( (pTab->tabFlags & TF_Virtual)!=0 );
97239
97240   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97241   if( pParse==0 ){
97242     rc = SQLITE_NOMEM;
97243   }else{
97244     pParse->declareVtab = 1;
97245     pParse->db = db;
97246     pParse->nQueryLoop = 1;
97247   
97248     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
97249      && pParse->pNewTable
97250      && !db->mallocFailed
97251      && !pParse->pNewTable->pSelect
97252      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97253     ){
97254       if( !pTab->aCol ){
97255         pTab->aCol = pParse->pNewTable->aCol;
97256         pTab->nCol = pParse->pNewTable->nCol;
97257         pParse->pNewTable->nCol = 0;
97258         pParse->pNewTable->aCol = 0;
97259       }
97260       db->pVTab = 0;
97261     }else{
97262       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97263       sqlite3DbFree(db, zErr);
97264       rc = SQLITE_ERROR;
97265     }
97266     pParse->declareVtab = 0;
97267   
97268     if( pParse->pVdbe ){
97269       sqlite3VdbeFinalize(pParse->pVdbe);
97270     }
97271     sqlite3DeleteTable(db, pParse->pNewTable);
97272     sqlite3StackFree(db, pParse);
97273   }
97274
97275   assert( (rc&0xff)==rc );
97276   rc = sqlite3ApiExit(db, rc);
97277   sqlite3_mutex_leave(db->mutex);
97278   return rc;
97279 }
97280
97281 /*
97282 ** This function is invoked by the vdbe to call the xDestroy method
97283 ** of the virtual table named zTab in database iDb. This occurs
97284 ** when a DROP TABLE is mentioned.
97285 **
97286 ** This call is a no-op if zTab is not a virtual table.
97287 */
97288 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97289   int rc = SQLITE_OK;
97290   Table *pTab;
97291
97292   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97293   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97294     VTable *p = vtabDisconnectAll(db, pTab);
97295
97296     assert( rc==SQLITE_OK );
97297     rc = p->pMod->pModule->xDestroy(p->pVtab);
97298
97299     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97300     if( rc==SQLITE_OK ){
97301       assert( pTab->pVTable==p && p->pNext==0 );
97302       p->pVtab = 0;
97303       pTab->pVTable = 0;
97304       sqlite3VtabUnlock(p);
97305     }
97306   }
97307
97308   return rc;
97309 }
97310
97311 /*
97312 ** This function invokes either the xRollback or xCommit method
97313 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
97314 ** called is identified by the second argument, "offset", which is
97315 ** the offset of the method to call in the sqlite3_module structure.
97316 **
97317 ** The array is cleared after invoking the callbacks. 
97318 */
97319 static void callFinaliser(sqlite3 *db, int offset){
97320   int i;
97321   if( db->aVTrans ){
97322     for(i=0; i<db->nVTrans; i++){
97323       VTable *pVTab = db->aVTrans[i];
97324       sqlite3_vtab *p = pVTab->pVtab;
97325       if( p ){
97326         int (*x)(sqlite3_vtab *);
97327         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
97328         if( x ) x(p);
97329       }
97330       sqlite3VtabUnlock(pVTab);
97331     }
97332     sqlite3DbFree(db, db->aVTrans);
97333     db->nVTrans = 0;
97334     db->aVTrans = 0;
97335   }
97336 }
97337
97338 /*
97339 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
97340 ** array. Return the error code for the first error that occurs, or
97341 ** SQLITE_OK if all xSync operations are successful.
97342 **
97343 ** Set *pzErrmsg to point to a buffer that should be released using 
97344 ** sqlite3DbFree() containing an error message, if one is available.
97345 */
97346 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
97347   int i;
97348   int rc = SQLITE_OK;
97349   VTable **aVTrans = db->aVTrans;
97350
97351   db->aVTrans = 0;
97352   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
97353     int (*x)(sqlite3_vtab *);
97354     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
97355     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
97356       rc = x(pVtab);
97357       sqlite3DbFree(db, *pzErrmsg);
97358       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
97359       sqlite3_free(pVtab->zErrMsg);
97360     }
97361   }
97362   db->aVTrans = aVTrans;
97363   return rc;
97364 }
97365
97366 /*
97367 ** Invoke the xRollback method of all virtual tables in the 
97368 ** sqlite3.aVTrans array. Then clear the array itself.
97369 */
97370 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
97371   callFinaliser(db, offsetof(sqlite3_module,xRollback));
97372   return SQLITE_OK;
97373 }
97374
97375 /*
97376 ** Invoke the xCommit method of all virtual tables in the 
97377 ** sqlite3.aVTrans array. Then clear the array itself.
97378 */
97379 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
97380   callFinaliser(db, offsetof(sqlite3_module,xCommit));
97381   return SQLITE_OK;
97382 }
97383
97384 /*
97385 ** If the virtual table pVtab supports the transaction interface
97386 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
97387 ** not currently open, invoke the xBegin method now.
97388 **
97389 ** If the xBegin call is successful, place the sqlite3_vtab pointer
97390 ** in the sqlite3.aVTrans array.
97391 */
97392 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
97393   int rc = SQLITE_OK;
97394   const sqlite3_module *pModule;
97395
97396   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
97397   ** than zero, then this function is being called from within a
97398   ** virtual module xSync() callback. It is illegal to write to 
97399   ** virtual module tables in this case, so return SQLITE_LOCKED.
97400   */
97401   if( sqlite3VtabInSync(db) ){
97402     return SQLITE_LOCKED;
97403   }
97404   if( !pVTab ){
97405     return SQLITE_OK;
97406   } 
97407   pModule = pVTab->pVtab->pModule;
97408
97409   if( pModule->xBegin ){
97410     int i;
97411
97412
97413     /* If pVtab is already in the aVTrans array, return early */
97414     for(i=0; i<db->nVTrans; i++){
97415       if( db->aVTrans[i]==pVTab ){
97416         return SQLITE_OK;
97417       }
97418     }
97419
97420     /* Invoke the xBegin method */
97421     rc = pModule->xBegin(pVTab->pVtab);
97422     if( rc==SQLITE_OK ){
97423       rc = addToVTrans(db, pVTab);
97424     }
97425   }
97426   return rc;
97427 }
97428
97429 /*
97430 ** The first parameter (pDef) is a function implementation.  The
97431 ** second parameter (pExpr) is the first argument to this function.
97432 ** If pExpr is a column in a virtual table, then let the virtual
97433 ** table implementation have an opportunity to overload the function.
97434 **
97435 ** This routine is used to allow virtual table implementations to
97436 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
97437 **
97438 ** Return either the pDef argument (indicating no change) or a 
97439 ** new FuncDef structure that is marked as ephemeral using the
97440 ** SQLITE_FUNC_EPHEM flag.
97441 */
97442 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
97443   sqlite3 *db,    /* Database connection for reporting malloc problems */
97444   FuncDef *pDef,  /* Function to possibly overload */
97445   int nArg,       /* Number of arguments to the function */
97446   Expr *pExpr     /* First argument to the function */
97447 ){
97448   Table *pTab;
97449   sqlite3_vtab *pVtab;
97450   sqlite3_module *pMod;
97451   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
97452   void *pArg = 0;
97453   FuncDef *pNew;
97454   int rc = 0;
97455   char *zLowerName;
97456   unsigned char *z;
97457
97458
97459   /* Check to see the left operand is a column in a virtual table */
97460   if( NEVER(pExpr==0) ) return pDef;
97461   if( pExpr->op!=TK_COLUMN ) return pDef;
97462   pTab = pExpr->pTab;
97463   if( NEVER(pTab==0) ) return pDef;
97464   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
97465   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
97466   assert( pVtab!=0 );
97467   assert( pVtab->pModule!=0 );
97468   pMod = (sqlite3_module *)pVtab->pModule;
97469   if( pMod->xFindFunction==0 ) return pDef;
97470  
97471   /* Call the xFindFunction method on the virtual table implementation
97472   ** to see if the implementation wants to overload this function 
97473   */
97474   zLowerName = sqlite3DbStrDup(db, pDef->zName);
97475   if( zLowerName ){
97476     for(z=(unsigned char*)zLowerName; *z; z++){
97477       *z = sqlite3UpperToLower[*z];
97478     }
97479     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
97480     sqlite3DbFree(db, zLowerName);
97481   }
97482   if( rc==0 ){
97483     return pDef;
97484   }
97485
97486   /* Create a new ephemeral function definition for the overloaded
97487   ** function */
97488   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
97489                              + sqlite3Strlen30(pDef->zName) + 1);
97490   if( pNew==0 ){
97491     return pDef;
97492   }
97493   *pNew = *pDef;
97494   pNew->zName = (char *)&pNew[1];
97495   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
97496   pNew->xFunc = xFunc;
97497   pNew->pUserData = pArg;
97498   pNew->flags |= SQLITE_FUNC_EPHEM;
97499   return pNew;
97500 }
97501
97502 /*
97503 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
97504 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
97505 ** array if it is missing.  If pTab is already in the array, this routine
97506 ** is a no-op.
97507 */
97508 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
97509   Parse *pToplevel = sqlite3ParseToplevel(pParse);
97510   int i, n;
97511   Table **apVtabLock;
97512
97513   assert( IsVirtual(pTab) );
97514   for(i=0; i<pToplevel->nVtabLock; i++){
97515     if( pTab==pToplevel->apVtabLock[i] ) return;
97516   }
97517   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
97518   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
97519   if( apVtabLock ){
97520     pToplevel->apVtabLock = apVtabLock;
97521     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
97522   }else{
97523     pToplevel->db->mallocFailed = 1;
97524   }
97525 }
97526
97527 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97528
97529 /************** End of vtab.c ************************************************/
97530 /************** Begin file where.c *******************************************/
97531 /*
97532 ** 2001 September 15
97533 **
97534 ** The author disclaims copyright to this source code.  In place of
97535 ** a legal notice, here is a blessing:
97536 **
97537 **    May you do good and not evil.
97538 **    May you find forgiveness for yourself and forgive others.
97539 **    May you share freely, never taking more than you give.
97540 **
97541 *************************************************************************
97542 ** This module contains C code that generates VDBE code used to process
97543 ** the WHERE clause of SQL statements.  This module is responsible for
97544 ** generating the code that loops through a table looking for applicable
97545 ** rows.  Indices are selected and used to speed the search when doing
97546 ** so is applicable.  Because this module is responsible for selecting
97547 ** indices, you might also think of this module as the "query optimizer".
97548 */
97549
97550
97551 /*
97552 ** Trace output macros
97553 */
97554 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
97555 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
97556 #endif
97557 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
97558 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
97559 #else
97560 # define WHERETRACE(X)
97561 #endif
97562
97563 /* Forward reference
97564 */
97565 typedef struct WhereClause WhereClause;
97566 typedef struct WhereMaskSet WhereMaskSet;
97567 typedef struct WhereOrInfo WhereOrInfo;
97568 typedef struct WhereAndInfo WhereAndInfo;
97569 typedef struct WhereCost WhereCost;
97570
97571 /*
97572 ** The query generator uses an array of instances of this structure to
97573 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
97574 ** clause subexpression is separated from the others by AND operators,
97575 ** usually, or sometimes subexpressions separated by OR.
97576 **
97577 ** All WhereTerms are collected into a single WhereClause structure.  
97578 ** The following identity holds:
97579 **
97580 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
97581 **
97582 ** When a term is of the form:
97583 **
97584 **              X <op> <expr>
97585 **
97586 ** where X is a column name and <op> is one of certain operators,
97587 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
97588 ** cursor number and column number for X.  WhereTerm.eOperator records
97589 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
97590 ** use of a bitmask encoding for the operator allows us to search
97591 ** quickly for terms that match any of several different operators.
97592 **
97593 ** A WhereTerm might also be two or more subterms connected by OR:
97594 **
97595 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
97596 **
97597 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
97598 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
97599 ** is collected about the
97600 **
97601 ** If a term in the WHERE clause does not match either of the two previous
97602 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
97603 ** to the original subexpression content and wtFlags is set up appropriately
97604 ** but no other fields in the WhereTerm object are meaningful.
97605 **
97606 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
97607 ** but they do so indirectly.  A single WhereMaskSet structure translates
97608 ** cursor number into bits and the translated bit is stored in the prereq
97609 ** fields.  The translation is used in order to maximize the number of
97610 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
97611 ** spread out over the non-negative integers.  For example, the cursor
97612 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
97613 ** translates these sparse cursor numbers into consecutive integers
97614 ** beginning with 0 in order to make the best possible use of the available
97615 ** bits in the Bitmask.  So, in the example above, the cursor numbers
97616 ** would be mapped into integers 0 through 7.
97617 **
97618 ** The number of terms in a join is limited by the number of bits
97619 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
97620 ** is only able to process joins with 64 or fewer tables.
97621 */
97622 typedef struct WhereTerm WhereTerm;
97623 struct WhereTerm {
97624   Expr *pExpr;            /* Pointer to the subexpression that is this term */
97625   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
97626   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
97627   union {
97628     int leftColumn;         /* Column number of X in "X <op> <expr>" */
97629     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
97630     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
97631   } u;
97632   u16 eOperator;          /* A WO_xx value describing <op> */
97633   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
97634   u8 nChild;              /* Number of children that must disable us */
97635   WhereClause *pWC;       /* The clause this term is part of */
97636   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
97637   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
97638 };
97639
97640 /*
97641 ** Allowed values of WhereTerm.wtFlags
97642 */
97643 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
97644 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
97645 #define TERM_CODED      0x04   /* This term is already coded */
97646 #define TERM_COPIED     0x08   /* Has a child */
97647 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
97648 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
97649 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
97650 #ifdef SQLITE_ENABLE_STAT2
97651 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
97652 #else
97653 #  define TERM_VNULL    0x00   /* Disabled if not using stat2 */
97654 #endif
97655
97656 /*
97657 ** An instance of the following structure holds all information about a
97658 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
97659 */
97660 struct WhereClause {
97661   Parse *pParse;           /* The parser context */
97662   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
97663   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
97664   u8 op;                   /* Split operator.  TK_AND or TK_OR */
97665   int nTerm;               /* Number of terms */
97666   int nSlot;               /* Number of entries in a[] */
97667   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
97668 #if defined(SQLITE_SMALL_STACK)
97669   WhereTerm aStatic[1];    /* Initial static space for a[] */
97670 #else
97671   WhereTerm aStatic[8];    /* Initial static space for a[] */
97672 #endif
97673 };
97674
97675 /*
97676 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
97677 ** a dynamically allocated instance of the following structure.
97678 */
97679 struct WhereOrInfo {
97680   WhereClause wc;          /* Decomposition into subterms */
97681   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
97682 };
97683
97684 /*
97685 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
97686 ** a dynamically allocated instance of the following structure.
97687 */
97688 struct WhereAndInfo {
97689   WhereClause wc;          /* The subexpression broken out */
97690 };
97691
97692 /*
97693 ** An instance of the following structure keeps track of a mapping
97694 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
97695 **
97696 ** The VDBE cursor numbers are small integers contained in 
97697 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
97698 ** clause, the cursor numbers might not begin with 0 and they might
97699 ** contain gaps in the numbering sequence.  But we want to make maximum
97700 ** use of the bits in our bitmasks.  This structure provides a mapping
97701 ** from the sparse cursor numbers into consecutive integers beginning
97702 ** with 0.
97703 **
97704 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
97705 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
97706 **
97707 ** For example, if the WHERE clause expression used these VDBE
97708 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
97709 ** would map those cursor numbers into bits 0 through 5.
97710 **
97711 ** Note that the mapping is not necessarily ordered.  In the example
97712 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
97713 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
97714 ** does not really matter.  What is important is that sparse cursor
97715 ** numbers all get mapped into bit numbers that begin with 0 and contain
97716 ** no gaps.
97717 */
97718 struct WhereMaskSet {
97719   int n;                        /* Number of assigned cursor values */
97720   int ix[BMS];                  /* Cursor assigned to each bit */
97721 };
97722
97723 /*
97724 ** A WhereCost object records a lookup strategy and the estimated
97725 ** cost of pursuing that strategy.
97726 */
97727 struct WhereCost {
97728   WherePlan plan;    /* The lookup strategy */
97729   double rCost;      /* Overall cost of pursuing this search strategy */
97730   Bitmask used;      /* Bitmask of cursors used by this plan */
97731 };
97732
97733 /*
97734 ** Bitmasks for the operators that indices are able to exploit.  An
97735 ** OR-ed combination of these values can be used when searching for
97736 ** terms in the where clause.
97737 */
97738 #define WO_IN     0x001
97739 #define WO_EQ     0x002
97740 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
97741 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
97742 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
97743 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
97744 #define WO_MATCH  0x040
97745 #define WO_ISNULL 0x080
97746 #define WO_OR     0x100       /* Two or more OR-connected terms */
97747 #define WO_AND    0x200       /* Two or more AND-connected terms */
97748 #define WO_NOOP   0x800       /* This term does not restrict search space */
97749
97750 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
97751 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
97752
97753 /*
97754 ** Value for wsFlags returned by bestIndex() and stored in
97755 ** WhereLevel.wsFlags.  These flags determine which search
97756 ** strategies are appropriate.
97757 **
97758 ** The least significant 12 bits is reserved as a mask for WO_ values above.
97759 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
97760 ** But if the table is the right table of a left join, WhereLevel.wsFlags
97761 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
97762 ** the "op" parameter to findTerm when we are resolving equality constraints.
97763 ** ISNULL constraints will then not be used on the right table of a left
97764 ** join.  Tickets #2177 and #2189.
97765 */
97766 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
97767 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
97768 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
97769 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
97770 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
97771 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
97772 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
97773 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
97774 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
97775 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
97776 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
97777 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
97778 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
97779 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
97780 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
97781 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
97782 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
97783 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
97784 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
97785
97786 /*
97787 ** Initialize a preallocated WhereClause structure.
97788 */
97789 static void whereClauseInit(
97790   WhereClause *pWC,        /* The WhereClause to be initialized */
97791   Parse *pParse,           /* The parsing context */
97792   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
97793 ){
97794   pWC->pParse = pParse;
97795   pWC->pMaskSet = pMaskSet;
97796   pWC->nTerm = 0;
97797   pWC->nSlot = ArraySize(pWC->aStatic);
97798   pWC->a = pWC->aStatic;
97799   pWC->vmask = 0;
97800 }
97801
97802 /* Forward reference */
97803 static void whereClauseClear(WhereClause*);
97804
97805 /*
97806 ** Deallocate all memory associated with a WhereOrInfo object.
97807 */
97808 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
97809   whereClauseClear(&p->wc);
97810   sqlite3DbFree(db, p);
97811 }
97812
97813 /*
97814 ** Deallocate all memory associated with a WhereAndInfo object.
97815 */
97816 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
97817   whereClauseClear(&p->wc);
97818   sqlite3DbFree(db, p);
97819 }
97820
97821 /*
97822 ** Deallocate a WhereClause structure.  The WhereClause structure
97823 ** itself is not freed.  This routine is the inverse of whereClauseInit().
97824 */
97825 static void whereClauseClear(WhereClause *pWC){
97826   int i;
97827   WhereTerm *a;
97828   sqlite3 *db = pWC->pParse->db;
97829   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
97830     if( a->wtFlags & TERM_DYNAMIC ){
97831       sqlite3ExprDelete(db, a->pExpr);
97832     }
97833     if( a->wtFlags & TERM_ORINFO ){
97834       whereOrInfoDelete(db, a->u.pOrInfo);
97835     }else if( a->wtFlags & TERM_ANDINFO ){
97836       whereAndInfoDelete(db, a->u.pAndInfo);
97837     }
97838   }
97839   if( pWC->a!=pWC->aStatic ){
97840     sqlite3DbFree(db, pWC->a);
97841   }
97842 }
97843
97844 /*
97845 ** Add a single new WhereTerm entry to the WhereClause object pWC.
97846 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
97847 ** The index in pWC->a[] of the new WhereTerm is returned on success.
97848 ** 0 is returned if the new WhereTerm could not be added due to a memory
97849 ** allocation error.  The memory allocation failure will be recorded in
97850 ** the db->mallocFailed flag so that higher-level functions can detect it.
97851 **
97852 ** This routine will increase the size of the pWC->a[] array as necessary.
97853 **
97854 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
97855 ** for freeing the expression p is assumed by the WhereClause object pWC.
97856 ** This is true even if this routine fails to allocate a new WhereTerm.
97857 **
97858 ** WARNING:  This routine might reallocate the space used to store
97859 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
97860 ** calling this routine.  Such pointers may be reinitialized by referencing
97861 ** the pWC->a[] array.
97862 */
97863 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
97864   WhereTerm *pTerm;
97865   int idx;
97866   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
97867   if( pWC->nTerm>=pWC->nSlot ){
97868     WhereTerm *pOld = pWC->a;
97869     sqlite3 *db = pWC->pParse->db;
97870     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
97871     if( pWC->a==0 ){
97872       if( wtFlags & TERM_DYNAMIC ){
97873         sqlite3ExprDelete(db, p);
97874       }
97875       pWC->a = pOld;
97876       return 0;
97877     }
97878     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
97879     if( pOld!=pWC->aStatic ){
97880       sqlite3DbFree(db, pOld);
97881     }
97882     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
97883   }
97884   pTerm = &pWC->a[idx = pWC->nTerm++];
97885   pTerm->pExpr = p;
97886   pTerm->wtFlags = wtFlags;
97887   pTerm->pWC = pWC;
97888   pTerm->iParent = -1;
97889   return idx;
97890 }
97891
97892 /*
97893 ** This routine identifies subexpressions in the WHERE clause where
97894 ** each subexpression is separated by the AND operator or some other
97895 ** operator specified in the op parameter.  The WhereClause structure
97896 ** is filled with pointers to subexpressions.  For example:
97897 **
97898 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
97899 **           \________/     \_______________/     \________________/
97900 **            slot[0]            slot[1]               slot[2]
97901 **
97902 ** The original WHERE clause in pExpr is unaltered.  All this routine
97903 ** does is make slot[] entries point to substructure within pExpr.
97904 **
97905 ** In the previous sentence and in the diagram, "slot[]" refers to
97906 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
97907 ** all terms of the WHERE clause.
97908 */
97909 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
97910   pWC->op = (u8)op;
97911   if( pExpr==0 ) return;
97912   if( pExpr->op!=op ){
97913     whereClauseInsert(pWC, pExpr, 0);
97914   }else{
97915     whereSplit(pWC, pExpr->pLeft, op);
97916     whereSplit(pWC, pExpr->pRight, op);
97917   }
97918 }
97919
97920 /*
97921 ** Initialize an expression mask set (a WhereMaskSet object)
97922 */
97923 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
97924
97925 /*
97926 ** Return the bitmask for the given cursor number.  Return 0 if
97927 ** iCursor is not in the set.
97928 */
97929 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
97930   int i;
97931   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
97932   for(i=0; i<pMaskSet->n; i++){
97933     if( pMaskSet->ix[i]==iCursor ){
97934       return ((Bitmask)1)<<i;
97935     }
97936   }
97937   return 0;
97938 }
97939
97940 /*
97941 ** Create a new mask for cursor iCursor.
97942 **
97943 ** There is one cursor per table in the FROM clause.  The number of
97944 ** tables in the FROM clause is limited by a test early in the
97945 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
97946 ** array will never overflow.
97947 */
97948 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
97949   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
97950   pMaskSet->ix[pMaskSet->n++] = iCursor;
97951 }
97952
97953 /*
97954 ** This routine walks (recursively) an expression tree and generates
97955 ** a bitmask indicating which tables are used in that expression
97956 ** tree.
97957 **
97958 ** In order for this routine to work, the calling function must have
97959 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
97960 ** the header comment on that routine for additional information.
97961 ** The sqlite3ResolveExprNames() routines looks for column names and
97962 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
97963 ** the VDBE cursor number of the table.  This routine just has to
97964 ** translate the cursor numbers into bitmask values and OR all
97965 ** the bitmasks together.
97966 */
97967 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
97968 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
97969 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
97970   Bitmask mask = 0;
97971   if( p==0 ) return 0;
97972   if( p->op==TK_COLUMN ){
97973     mask = getMask(pMaskSet, p->iTable);
97974     return mask;
97975   }
97976   mask = exprTableUsage(pMaskSet, p->pRight);
97977   mask |= exprTableUsage(pMaskSet, p->pLeft);
97978   if( ExprHasProperty(p, EP_xIsSelect) ){
97979     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
97980   }else{
97981     mask |= exprListTableUsage(pMaskSet, p->x.pList);
97982   }
97983   return mask;
97984 }
97985 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
97986   int i;
97987   Bitmask mask = 0;
97988   if( pList ){
97989     for(i=0; i<pList->nExpr; i++){
97990       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
97991     }
97992   }
97993   return mask;
97994 }
97995 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
97996   Bitmask mask = 0;
97997   while( pS ){
97998     mask |= exprListTableUsage(pMaskSet, pS->pEList);
97999     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
98000     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
98001     mask |= exprTableUsage(pMaskSet, pS->pWhere);
98002     mask |= exprTableUsage(pMaskSet, pS->pHaving);
98003     pS = pS->pPrior;
98004   }
98005   return mask;
98006 }
98007
98008 /*
98009 ** Return TRUE if the given operator is one of the operators that is
98010 ** allowed for an indexable WHERE clause term.  The allowed operators are
98011 ** "=", "<", ">", "<=", ">=", and "IN".
98012 **
98013 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98014 ** of one of the following forms: column = expression column > expression
98015 ** column >= expression column < expression column <= expression
98016 ** expression = column expression > column expression >= column
98017 ** expression < column expression <= column column IN
98018 ** (expression-list) column IN (subquery) column IS NULL
98019 */
98020 static int allowedOp(int op){
98021   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98022   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98023   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98024   assert( TK_GE==TK_EQ+4 );
98025   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98026 }
98027
98028 /*
98029 ** Swap two objects of type TYPE.
98030 */
98031 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98032
98033 /*
98034 ** Commute a comparison operator.  Expressions of the form "X op Y"
98035 ** are converted into "Y op X".
98036 **
98037 ** If a collation sequence is associated with either the left or right
98038 ** side of the comparison, it remains associated with the same side after
98039 ** the commutation. So "Y collate NOCASE op X" becomes 
98040 ** "X collate NOCASE op Y". This is because any collation sequence on
98041 ** the left hand side of a comparison overrides any collation sequence 
98042 ** attached to the right. For the same reason the EP_ExpCollate flag
98043 ** is not commuted.
98044 */
98045 static void exprCommute(Parse *pParse, Expr *pExpr){
98046   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98047   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98048   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98049   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98050   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98051   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98052   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98053   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98054   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98055   if( pExpr->op>=TK_GT ){
98056     assert( TK_LT==TK_GT+2 );
98057     assert( TK_GE==TK_LE+2 );
98058     assert( TK_GT>TK_EQ );
98059     assert( TK_GT<TK_LE );
98060     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98061     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98062   }
98063 }
98064
98065 /*
98066 ** Translate from TK_xx operator to WO_xx bitmask.
98067 */
98068 static u16 operatorMask(int op){
98069   u16 c;
98070   assert( allowedOp(op) );
98071   if( op==TK_IN ){
98072     c = WO_IN;
98073   }else if( op==TK_ISNULL ){
98074     c = WO_ISNULL;
98075   }else{
98076     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98077     c = (u16)(WO_EQ<<(op-TK_EQ));
98078   }
98079   assert( op!=TK_ISNULL || c==WO_ISNULL );
98080   assert( op!=TK_IN || c==WO_IN );
98081   assert( op!=TK_EQ || c==WO_EQ );
98082   assert( op!=TK_LT || c==WO_LT );
98083   assert( op!=TK_LE || c==WO_LE );
98084   assert( op!=TK_GT || c==WO_GT );
98085   assert( op!=TK_GE || c==WO_GE );
98086   return c;
98087 }
98088
98089 /*
98090 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98091 ** where X is a reference to the iColumn of table iCur and <op> is one of
98092 ** the WO_xx operator codes specified by the op parameter.
98093 ** Return a pointer to the term.  Return 0 if not found.
98094 */
98095 static WhereTerm *findTerm(
98096   WhereClause *pWC,     /* The WHERE clause to be searched */
98097   int iCur,             /* Cursor number of LHS */
98098   int iColumn,          /* Column number of LHS */
98099   Bitmask notReady,     /* RHS must not overlap with this mask */
98100   u32 op,               /* Mask of WO_xx values describing operator */
98101   Index *pIdx           /* Must be compatible with this index, if not NULL */
98102 ){
98103   WhereTerm *pTerm;
98104   int k;
98105   assert( iCur>=0 );
98106   op &= WO_ALL;
98107   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98108     if( pTerm->leftCursor==iCur
98109        && (pTerm->prereqRight & notReady)==0
98110        && pTerm->u.leftColumn==iColumn
98111        && (pTerm->eOperator & op)!=0
98112     ){
98113       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98114         Expr *pX = pTerm->pExpr;
98115         CollSeq *pColl;
98116         char idxaff;
98117         int j;
98118         Parse *pParse = pWC->pParse;
98119
98120         idxaff = pIdx->pTable->aCol[iColumn].affinity;
98121         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98122
98123         /* Figure out the collation sequence required from an index for
98124         ** it to be useful for optimising expression pX. Store this
98125         ** value in variable pColl.
98126         */
98127         assert(pX->pLeft);
98128         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98129         assert(pColl || pParse->nErr);
98130
98131         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98132           if( NEVER(j>=pIdx->nColumn) ) return 0;
98133         }
98134         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98135       }
98136       return pTerm;
98137     }
98138   }
98139   return 0;
98140 }
98141
98142 /* Forward reference */
98143 static void exprAnalyze(SrcList*, WhereClause*, int);
98144
98145 /*
98146 ** Call exprAnalyze on all terms in a WHERE clause.  
98147 **
98148 **
98149 */
98150 static void exprAnalyzeAll(
98151   SrcList *pTabList,       /* the FROM clause */
98152   WhereClause *pWC         /* the WHERE clause to be analyzed */
98153 ){
98154   int i;
98155   for(i=pWC->nTerm-1; i>=0; i--){
98156     exprAnalyze(pTabList, pWC, i);
98157   }
98158 }
98159
98160 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98161 /*
98162 ** Check to see if the given expression is a LIKE or GLOB operator that
98163 ** can be optimized using inequality constraints.  Return TRUE if it is
98164 ** so and false if not.
98165 **
98166 ** In order for the operator to be optimizible, the RHS must be a string
98167 ** literal that does not begin with a wildcard.  
98168 */
98169 static int isLikeOrGlob(
98170   Parse *pParse,    /* Parsing and code generating context */
98171   Expr *pExpr,      /* Test this expression */
98172   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
98173   int *pisComplete, /* True if the only wildcard is % in the last character */
98174   int *pnoCase      /* True if uppercase is equivalent to lowercase */
98175 ){
98176   const char *z = 0;         /* String on RHS of LIKE operator */
98177   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
98178   ExprList *pList;           /* List of operands to the LIKE operator */
98179   int c;                     /* One character in z[] */
98180   int cnt;                   /* Number of non-wildcard prefix characters */
98181   char wc[3];                /* Wildcard characters */
98182   sqlite3 *db = pParse->db;  /* Database connection */
98183   sqlite3_value *pVal = 0;
98184   int op;                    /* Opcode of pRight */
98185
98186   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98187     return 0;
98188   }
98189 #ifdef SQLITE_EBCDIC
98190   if( *pnoCase ) return 0;
98191 #endif
98192   pList = pExpr->x.pList;
98193   pLeft = pList->a[1].pExpr;
98194   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98195     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98196     ** be the name of an indexed column with TEXT affinity. */
98197     return 0;
98198   }
98199   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98200
98201   pRight = pList->a[0].pExpr;
98202   op = pRight->op;
98203   if( op==TK_REGISTER ){
98204     op = pRight->op2;
98205   }
98206   if( op==TK_VARIABLE ){
98207     Vdbe *pReprepare = pParse->pReprepare;
98208     int iCol = pRight->iColumn;
98209     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
98210     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
98211       z = (char *)sqlite3_value_text(pVal);
98212     }
98213     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
98214     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
98215   }else if( op==TK_STRING ){
98216     z = pRight->u.zToken;
98217   }
98218   if( z ){
98219     cnt = 0;
98220     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
98221       cnt++;
98222     }
98223     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
98224       Expr *pPrefix;
98225       *pisComplete = c==wc[0] && z[cnt+1]==0;
98226       pPrefix = sqlite3Expr(db, TK_STRING, z);
98227       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
98228       *ppPrefix = pPrefix;
98229       if( op==TK_VARIABLE ){
98230         Vdbe *v = pParse->pVdbe;
98231         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
98232         if( *pisComplete && pRight->u.zToken[1] ){
98233           /* If the rhs of the LIKE expression is a variable, and the current
98234           ** value of the variable means there is no need to invoke the LIKE
98235           ** function, then no OP_Variable will be added to the program.
98236           ** This causes problems for the sqlite3_bind_parameter_name()
98237           ** API. To workaround them, add a dummy OP_Variable here.
98238           */ 
98239           int r1 = sqlite3GetTempReg(pParse);
98240           sqlite3ExprCodeTarget(pParse, pRight, r1);
98241           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
98242           sqlite3ReleaseTempReg(pParse, r1);
98243         }
98244       }
98245     }else{
98246       z = 0;
98247     }
98248   }
98249
98250   sqlite3ValueFree(pVal);
98251   return (z!=0);
98252 }
98253 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98254
98255
98256 #ifndef SQLITE_OMIT_VIRTUALTABLE
98257 /*
98258 ** Check to see if the given expression is of the form
98259 **
98260 **         column MATCH expr
98261 **
98262 ** If it is then return TRUE.  If not, return FALSE.
98263 */
98264 static int isMatchOfColumn(
98265   Expr *pExpr      /* Test this expression */
98266 ){
98267   ExprList *pList;
98268
98269   if( pExpr->op!=TK_FUNCTION ){
98270     return 0;
98271   }
98272   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
98273     return 0;
98274   }
98275   pList = pExpr->x.pList;
98276   if( pList->nExpr!=2 ){
98277     return 0;
98278   }
98279   if( pList->a[1].pExpr->op != TK_COLUMN ){
98280     return 0;
98281   }
98282   return 1;
98283 }
98284 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98285
98286 /*
98287 ** If the pBase expression originated in the ON or USING clause of
98288 ** a join, then transfer the appropriate markings over to derived.
98289 */
98290 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
98291   pDerived->flags |= pBase->flags & EP_FromJoin;
98292   pDerived->iRightJoinTable = pBase->iRightJoinTable;
98293 }
98294
98295 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98296 /*
98297 ** Analyze a term that consists of two or more OR-connected
98298 ** subterms.  So in:
98299 **
98300 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
98301 **                          ^^^^^^^^^^^^^^^^^^^^
98302 **
98303 ** This routine analyzes terms such as the middle term in the above example.
98304 ** A WhereOrTerm object is computed and attached to the term under
98305 ** analysis, regardless of the outcome of the analysis.  Hence:
98306 **
98307 **     WhereTerm.wtFlags   |=  TERM_ORINFO
98308 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
98309 **
98310 ** The term being analyzed must have two or more of OR-connected subterms.
98311 ** A single subterm might be a set of AND-connected sub-subterms.
98312 ** Examples of terms under analysis:
98313 **
98314 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
98315 **     (B)     x=expr1 OR expr2=x OR x=expr3
98316 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
98317 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
98318 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
98319 **
98320 ** CASE 1:
98321 **
98322 ** If all subterms are of the form T.C=expr for some single column of C
98323 ** a single table T (as shown in example B above) then create a new virtual
98324 ** term that is an equivalent IN expression.  In other words, if the term
98325 ** being analyzed is:
98326 **
98327 **      x = expr1  OR  expr2 = x  OR  x = expr3
98328 **
98329 ** then create a new virtual term like this:
98330 **
98331 **      x IN (expr1,expr2,expr3)
98332 **
98333 ** CASE 2:
98334 **
98335 ** If all subterms are indexable by a single table T, then set
98336 **
98337 **     WhereTerm.eOperator              =  WO_OR
98338 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
98339 **
98340 ** A subterm is "indexable" if it is of the form
98341 ** "T.C <op> <expr>" where C is any column of table T and 
98342 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
98343 ** A subterm is also indexable if it is an AND of two or more
98344 ** subsubterms at least one of which is indexable.  Indexable AND 
98345 ** subterms have their eOperator set to WO_AND and they have
98346 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
98347 **
98348 ** From another point of view, "indexable" means that the subterm could
98349 ** potentially be used with an index if an appropriate index exists.
98350 ** This analysis does not consider whether or not the index exists; that
98351 ** is something the bestIndex() routine will determine.  This analysis
98352 ** only looks at whether subterms appropriate for indexing exist.
98353 **
98354 ** All examples A through E above all satisfy case 2.  But if a term
98355 ** also statisfies case 1 (such as B) we know that the optimizer will
98356 ** always prefer case 1, so in that case we pretend that case 2 is not
98357 ** satisfied.
98358 **
98359 ** It might be the case that multiple tables are indexable.  For example,
98360 ** (E) above is indexable on tables P, Q, and R.
98361 **
98362 ** Terms that satisfy case 2 are candidates for lookup by using
98363 ** separate indices to find rowids for each subterm and composing
98364 ** the union of all rowids using a RowSet object.  This is similar
98365 ** to "bitmap indices" in other database engines.
98366 **
98367 ** OTHERWISE:
98368 **
98369 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
98370 ** zero.  This term is not useful for search.
98371 */
98372 static void exprAnalyzeOrTerm(
98373   SrcList *pSrc,            /* the FROM clause */
98374   WhereClause *pWC,         /* the complete WHERE clause */
98375   int idxTerm               /* Index of the OR-term to be analyzed */
98376 ){
98377   Parse *pParse = pWC->pParse;            /* Parser context */
98378   sqlite3 *db = pParse->db;               /* Database connection */
98379   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
98380   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
98381   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
98382   int i;                                  /* Loop counters */
98383   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
98384   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
98385   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
98386   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
98387   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
98388
98389   /*
98390   ** Break the OR clause into its separate subterms.  The subterms are
98391   ** stored in a WhereClause structure containing within the WhereOrInfo
98392   ** object that is attached to the original OR clause term.
98393   */
98394   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
98395   assert( pExpr->op==TK_OR );
98396   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
98397   if( pOrInfo==0 ) return;
98398   pTerm->wtFlags |= TERM_ORINFO;
98399   pOrWc = &pOrInfo->wc;
98400   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
98401   whereSplit(pOrWc, pExpr, TK_OR);
98402   exprAnalyzeAll(pSrc, pOrWc);
98403   if( db->mallocFailed ) return;
98404   assert( pOrWc->nTerm>=2 );
98405
98406   /*
98407   ** Compute the set of tables that might satisfy cases 1 or 2.
98408   */
98409   indexable = ~(Bitmask)0;
98410   chngToIN = ~(pWC->vmask);
98411   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
98412     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
98413       WhereAndInfo *pAndInfo;
98414       assert( pOrTerm->eOperator==0 );
98415       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
98416       chngToIN = 0;
98417       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
98418       if( pAndInfo ){
98419         WhereClause *pAndWC;
98420         WhereTerm *pAndTerm;
98421         int j;
98422         Bitmask b = 0;
98423         pOrTerm->u.pAndInfo = pAndInfo;
98424         pOrTerm->wtFlags |= TERM_ANDINFO;
98425         pOrTerm->eOperator = WO_AND;
98426         pAndWC = &pAndInfo->wc;
98427         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
98428         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
98429         exprAnalyzeAll(pSrc, pAndWC);
98430         testcase( db->mallocFailed );
98431         if( !db->mallocFailed ){
98432           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
98433             assert( pAndTerm->pExpr );
98434             if( allowedOp(pAndTerm->pExpr->op) ){
98435               b |= getMask(pMaskSet, pAndTerm->leftCursor);
98436             }
98437           }
98438         }
98439         indexable &= b;
98440       }
98441     }else if( pOrTerm->wtFlags & TERM_COPIED ){
98442       /* Skip this term for now.  We revisit it when we process the
98443       ** corresponding TERM_VIRTUAL term */
98444     }else{
98445       Bitmask b;
98446       b = getMask(pMaskSet, pOrTerm->leftCursor);
98447       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
98448         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
98449         b |= getMask(pMaskSet, pOther->leftCursor);
98450       }
98451       indexable &= b;
98452       if( pOrTerm->eOperator!=WO_EQ ){
98453         chngToIN = 0;
98454       }else{
98455         chngToIN &= b;
98456       }
98457     }
98458   }
98459
98460   /*
98461   ** Record the set of tables that satisfy case 2.  The set might be
98462   ** empty.
98463   */
98464   pOrInfo->indexable = indexable;
98465   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
98466
98467   /*
98468   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
98469   ** we have to do some additional checking to see if case 1 really
98470   ** is satisfied.
98471   **
98472   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
98473   ** that there is no possibility of transforming the OR clause into an
98474   ** IN operator because one or more terms in the OR clause contain
98475   ** something other than == on a column in the single table.  The 1-bit
98476   ** case means that every term of the OR clause is of the form
98477   ** "table.column=expr" for some single table.  The one bit that is set
98478   ** will correspond to the common table.  We still need to check to make
98479   ** sure the same column is used on all terms.  The 2-bit case is when
98480   ** the all terms are of the form "table1.column=table2.column".  It
98481   ** might be possible to form an IN operator with either table1.column
98482   ** or table2.column as the LHS if either is common to every term of
98483   ** the OR clause.
98484   **
98485   ** Note that terms of the form "table.column1=table.column2" (the
98486   ** same table on both sizes of the ==) cannot be optimized.
98487   */
98488   if( chngToIN ){
98489     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
98490     int iColumn = -1;         /* Column index on lhs of IN operator */
98491     int iCursor = -1;         /* Table cursor common to all terms */
98492     int j = 0;                /* Loop counter */
98493
98494     /* Search for a table and column that appears on one side or the
98495     ** other of the == operator in every subterm.  That table and column
98496     ** will be recorded in iCursor and iColumn.  There might not be any
98497     ** such table and column.  Set okToChngToIN if an appropriate table
98498     ** and column is found but leave okToChngToIN false if not found.
98499     */
98500     for(j=0; j<2 && !okToChngToIN; j++){
98501       pOrTerm = pOrWc->a;
98502       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
98503         assert( pOrTerm->eOperator==WO_EQ );
98504         pOrTerm->wtFlags &= ~TERM_OR_OK;
98505         if( pOrTerm->leftCursor==iCursor ){
98506           /* This is the 2-bit case and we are on the second iteration and
98507           ** current term is from the first iteration.  So skip this term. */
98508           assert( j==1 );
98509           continue;
98510         }
98511         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
98512           /* This term must be of the form t1.a==t2.b where t2 is in the
98513           ** chngToIN set but t1 is not.  This term will be either preceeded
98514           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
98515           ** and use its inversion. */
98516           testcase( pOrTerm->wtFlags & TERM_COPIED );
98517           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
98518           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
98519           continue;
98520         }
98521         iColumn = pOrTerm->u.leftColumn;
98522         iCursor = pOrTerm->leftCursor;
98523         break;
98524       }
98525       if( i<0 ){
98526         /* No candidate table+column was found.  This can only occur
98527         ** on the second iteration */
98528         assert( j==1 );
98529         assert( (chngToIN&(chngToIN-1))==0 );
98530         assert( chngToIN==getMask(pMaskSet, iCursor) );
98531         break;
98532       }
98533       testcase( j==1 );
98534
98535       /* We have found a candidate table and column.  Check to see if that
98536       ** table and column is common to every term in the OR clause */
98537       okToChngToIN = 1;
98538       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
98539         assert( pOrTerm->eOperator==WO_EQ );
98540         if( pOrTerm->leftCursor!=iCursor ){
98541           pOrTerm->wtFlags &= ~TERM_OR_OK;
98542         }else if( pOrTerm->u.leftColumn!=iColumn ){
98543           okToChngToIN = 0;
98544         }else{
98545           int affLeft, affRight;
98546           /* If the right-hand side is also a column, then the affinities
98547           ** of both right and left sides must be such that no type
98548           ** conversions are required on the right.  (Ticket #2249)
98549           */
98550           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
98551           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
98552           if( affRight!=0 && affRight!=affLeft ){
98553             okToChngToIN = 0;
98554           }else{
98555             pOrTerm->wtFlags |= TERM_OR_OK;
98556           }
98557         }
98558       }
98559     }
98560
98561     /* At this point, okToChngToIN is true if original pTerm satisfies
98562     ** case 1.  In that case, construct a new virtual term that is 
98563     ** pTerm converted into an IN operator.
98564     **
98565     ** EV: R-00211-15100
98566     */
98567     if( okToChngToIN ){
98568       Expr *pDup;            /* A transient duplicate expression */
98569       ExprList *pList = 0;   /* The RHS of the IN operator */
98570       Expr *pLeft = 0;       /* The LHS of the IN operator */
98571       Expr *pNew;            /* The complete IN operator */
98572
98573       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
98574         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
98575         assert( pOrTerm->eOperator==WO_EQ );
98576         assert( pOrTerm->leftCursor==iCursor );
98577         assert( pOrTerm->u.leftColumn==iColumn );
98578         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
98579         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
98580         pLeft = pOrTerm->pExpr->pLeft;
98581       }
98582       assert( pLeft!=0 );
98583       pDup = sqlite3ExprDup(db, pLeft, 0);
98584       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
98585       if( pNew ){
98586         int idxNew;
98587         transferJoinMarkings(pNew, pExpr);
98588         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
98589         pNew->x.pList = pList;
98590         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
98591         testcase( idxNew==0 );
98592         exprAnalyze(pSrc, pWC, idxNew);
98593         pTerm = &pWC->a[idxTerm];
98594         pWC->a[idxNew].iParent = idxTerm;
98595         pTerm->nChild = 1;
98596       }else{
98597         sqlite3ExprListDelete(db, pList);
98598       }
98599       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
98600     }
98601   }
98602 }
98603 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
98604
98605
98606 /*
98607 ** The input to this routine is an WhereTerm structure with only the
98608 ** "pExpr" field filled in.  The job of this routine is to analyze the
98609 ** subexpression and populate all the other fields of the WhereTerm
98610 ** structure.
98611 **
98612 ** If the expression is of the form "<expr> <op> X" it gets commuted
98613 ** to the standard form of "X <op> <expr>".
98614 **
98615 ** If the expression is of the form "X <op> Y" where both X and Y are
98616 ** columns, then the original expression is unchanged and a new virtual
98617 ** term of the form "Y <op> X" is added to the WHERE clause and
98618 ** analyzed separately.  The original term is marked with TERM_COPIED
98619 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
98620 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
98621 ** is a commuted copy of a prior term.)  The original term has nChild=1
98622 ** and the copy has idxParent set to the index of the original term.
98623 */
98624 static void exprAnalyze(
98625   SrcList *pSrc,            /* the FROM clause */
98626   WhereClause *pWC,         /* the WHERE clause */
98627   int idxTerm               /* Index of the term to be analyzed */
98628 ){
98629   WhereTerm *pTerm;                /* The term to be analyzed */
98630   WhereMaskSet *pMaskSet;          /* Set of table index masks */
98631   Expr *pExpr;                     /* The expression to be analyzed */
98632   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
98633   Bitmask prereqAll;               /* Prerequesites of pExpr */
98634   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
98635   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
98636   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
98637   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
98638   int op;                          /* Top-level operator.  pExpr->op */
98639   Parse *pParse = pWC->pParse;     /* Parsing context */
98640   sqlite3 *db = pParse->db;        /* Database connection */
98641
98642   if( db->mallocFailed ){
98643     return;
98644   }
98645   pTerm = &pWC->a[idxTerm];
98646   pMaskSet = pWC->pMaskSet;
98647   pExpr = pTerm->pExpr;
98648   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
98649   op = pExpr->op;
98650   if( op==TK_IN ){
98651     assert( pExpr->pRight==0 );
98652     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98653       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
98654     }else{
98655       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
98656     }
98657   }else if( op==TK_ISNULL ){
98658     pTerm->prereqRight = 0;
98659   }else{
98660     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
98661   }
98662   prereqAll = exprTableUsage(pMaskSet, pExpr);
98663   if( ExprHasProperty(pExpr, EP_FromJoin) ){
98664     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
98665     prereqAll |= x;
98666     extraRight = x-1;  /* ON clause terms may not be used with an index
98667                        ** on left table of a LEFT JOIN.  Ticket #3015 */
98668   }
98669   pTerm->prereqAll = prereqAll;
98670   pTerm->leftCursor = -1;
98671   pTerm->iParent = -1;
98672   pTerm->eOperator = 0;
98673   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
98674     Expr *pLeft = pExpr->pLeft;
98675     Expr *pRight = pExpr->pRight;
98676     if( pLeft->op==TK_COLUMN ){
98677       pTerm->leftCursor = pLeft->iTable;
98678       pTerm->u.leftColumn = pLeft->iColumn;
98679       pTerm->eOperator = operatorMask(op);
98680     }
98681     if( pRight && pRight->op==TK_COLUMN ){
98682       WhereTerm *pNew;
98683       Expr *pDup;
98684       if( pTerm->leftCursor>=0 ){
98685         int idxNew;
98686         pDup = sqlite3ExprDup(db, pExpr, 0);
98687         if( db->mallocFailed ){
98688           sqlite3ExprDelete(db, pDup);
98689           return;
98690         }
98691         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
98692         if( idxNew==0 ) return;
98693         pNew = &pWC->a[idxNew];
98694         pNew->iParent = idxTerm;
98695         pTerm = &pWC->a[idxTerm];
98696         pTerm->nChild = 1;
98697         pTerm->wtFlags |= TERM_COPIED;
98698       }else{
98699         pDup = pExpr;
98700         pNew = pTerm;
98701       }
98702       exprCommute(pParse, pDup);
98703       pLeft = pDup->pLeft;
98704       pNew->leftCursor = pLeft->iTable;
98705       pNew->u.leftColumn = pLeft->iColumn;
98706       testcase( (prereqLeft | extraRight) != prereqLeft );
98707       pNew->prereqRight = prereqLeft | extraRight;
98708       pNew->prereqAll = prereqAll;
98709       pNew->eOperator = operatorMask(pDup->op);
98710     }
98711   }
98712
98713 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
98714   /* If a term is the BETWEEN operator, create two new virtual terms
98715   ** that define the range that the BETWEEN implements.  For example:
98716   **
98717   **      a BETWEEN b AND c
98718   **
98719   ** is converted into:
98720   **
98721   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
98722   **
98723   ** The two new terms are added onto the end of the WhereClause object.
98724   ** The new terms are "dynamic" and are children of the original BETWEEN
98725   ** term.  That means that if the BETWEEN term is coded, the children are
98726   ** skipped.  Or, if the children are satisfied by an index, the original
98727   ** BETWEEN term is skipped.
98728   */
98729   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
98730     ExprList *pList = pExpr->x.pList;
98731     int i;
98732     static const u8 ops[] = {TK_GE, TK_LE};
98733     assert( pList!=0 );
98734     assert( pList->nExpr==2 );
98735     for(i=0; i<2; i++){
98736       Expr *pNewExpr;
98737       int idxNew;
98738       pNewExpr = sqlite3PExpr(pParse, ops[i], 
98739                              sqlite3ExprDup(db, pExpr->pLeft, 0),
98740                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
98741       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98742       testcase( idxNew==0 );
98743       exprAnalyze(pSrc, pWC, idxNew);
98744       pTerm = &pWC->a[idxTerm];
98745       pWC->a[idxNew].iParent = idxTerm;
98746     }
98747     pTerm->nChild = 2;
98748   }
98749 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
98750
98751 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98752   /* Analyze a term that is composed of two or more subterms connected by
98753   ** an OR operator.
98754   */
98755   else if( pExpr->op==TK_OR ){
98756     assert( pWC->op==TK_AND );
98757     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
98758     pTerm = &pWC->a[idxTerm];
98759   }
98760 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
98761
98762 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98763   /* Add constraints to reduce the search space on a LIKE or GLOB
98764   ** operator.
98765   **
98766   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
98767   **
98768   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
98769   **
98770   ** The last character of the prefix "abc" is incremented to form the
98771   ** termination condition "abd".
98772   */
98773   if( pWC->op==TK_AND 
98774    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
98775   ){
98776     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
98777     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
98778     Expr *pNewExpr1;
98779     Expr *pNewExpr2;
98780     int idxNew1;
98781     int idxNew2;
98782     CollSeq *pColl;    /* Collating sequence to use */
98783
98784     pLeft = pExpr->x.pList->a[1].pExpr;
98785     pStr2 = sqlite3ExprDup(db, pStr1, 0);
98786     if( !db->mallocFailed ){
98787       u8 c, *pC;       /* Last character before the first wildcard */
98788       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
98789       c = *pC;
98790       if( noCase ){
98791         /* The point is to increment the last character before the first
98792         ** wildcard.  But if we increment '@', that will push it into the
98793         ** alphabetic range where case conversions will mess up the 
98794         ** inequality.  To avoid this, make sure to also run the full
98795         ** LIKE on all candidate expressions by clearing the isComplete flag
98796         */
98797         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
98798
98799
98800         c = sqlite3UpperToLower[c];
98801       }
98802       *pC = c + 1;
98803     }
98804     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
98805     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
98806                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98807                      pStr1, 0);
98808     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
98809     testcase( idxNew1==0 );
98810     exprAnalyze(pSrc, pWC, idxNew1);
98811     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
98812                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
98813                      pStr2, 0);
98814     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
98815     testcase( idxNew2==0 );
98816     exprAnalyze(pSrc, pWC, idxNew2);
98817     pTerm = &pWC->a[idxTerm];
98818     if( isComplete ){
98819       pWC->a[idxNew1].iParent = idxTerm;
98820       pWC->a[idxNew2].iParent = idxTerm;
98821       pTerm->nChild = 2;
98822     }
98823   }
98824 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98825
98826 #ifndef SQLITE_OMIT_VIRTUALTABLE
98827   /* Add a WO_MATCH auxiliary term to the constraint set if the
98828   ** current expression is of the form:  column MATCH expr.
98829   ** This information is used by the xBestIndex methods of
98830   ** virtual tables.  The native query optimizer does not attempt
98831   ** to do anything with MATCH functions.
98832   */
98833   if( isMatchOfColumn(pExpr) ){
98834     int idxNew;
98835     Expr *pRight, *pLeft;
98836     WhereTerm *pNewTerm;
98837     Bitmask prereqColumn, prereqExpr;
98838
98839     pRight = pExpr->x.pList->a[0].pExpr;
98840     pLeft = pExpr->x.pList->a[1].pExpr;
98841     prereqExpr = exprTableUsage(pMaskSet, pRight);
98842     prereqColumn = exprTableUsage(pMaskSet, pLeft);
98843     if( (prereqExpr & prereqColumn)==0 ){
98844       Expr *pNewExpr;
98845       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
98846                               0, sqlite3ExprDup(db, pRight, 0), 0);
98847       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
98848       testcase( idxNew==0 );
98849       pNewTerm = &pWC->a[idxNew];
98850       pNewTerm->prereqRight = prereqExpr;
98851       pNewTerm->leftCursor = pLeft->iTable;
98852       pNewTerm->u.leftColumn = pLeft->iColumn;
98853       pNewTerm->eOperator = WO_MATCH;
98854       pNewTerm->iParent = idxTerm;
98855       pTerm = &pWC->a[idxTerm];
98856       pTerm->nChild = 1;
98857       pTerm->wtFlags |= TERM_COPIED;
98858       pNewTerm->prereqAll = pTerm->prereqAll;
98859     }
98860   }
98861 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98862
98863 #ifdef SQLITE_ENABLE_STAT2
98864   /* When sqlite_stat2 histogram data is available an operator of the
98865   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
98866   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
98867   ** virtual term of that form.
98868   **
98869   ** Note that the virtual term must be tagged with TERM_VNULL.  This
98870   ** TERM_VNULL tag will suppress the not-null check at the beginning
98871   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
98872   ** the start of the loop will prevent any results from being returned.
98873   */
98874   if( pExpr->op==TK_NOTNULL
98875    && pExpr->pLeft->op==TK_COLUMN
98876    && pExpr->pLeft->iColumn>=0
98877   ){
98878     Expr *pNewExpr;
98879     Expr *pLeft = pExpr->pLeft;
98880     int idxNew;
98881     WhereTerm *pNewTerm;
98882
98883     pNewExpr = sqlite3PExpr(pParse, TK_GT,
98884                             sqlite3ExprDup(db, pLeft, 0),
98885                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
98886
98887     idxNew = whereClauseInsert(pWC, pNewExpr,
98888                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
98889     if( idxNew ){
98890       pNewTerm = &pWC->a[idxNew];
98891       pNewTerm->prereqRight = 0;
98892       pNewTerm->leftCursor = pLeft->iTable;
98893       pNewTerm->u.leftColumn = pLeft->iColumn;
98894       pNewTerm->eOperator = WO_GT;
98895       pNewTerm->iParent = idxTerm;
98896       pTerm = &pWC->a[idxTerm];
98897       pTerm->nChild = 1;
98898       pTerm->wtFlags |= TERM_COPIED;
98899       pNewTerm->prereqAll = pTerm->prereqAll;
98900     }
98901   }
98902 #endif /* SQLITE_ENABLE_STAT2 */
98903
98904   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
98905   ** an index for tables to the left of the join.
98906   */
98907   pTerm->prereqRight |= extraRight;
98908 }
98909
98910 /*
98911 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
98912 ** a reference to any table other than the iBase table.
98913 */
98914 static int referencesOtherTables(
98915   ExprList *pList,          /* Search expressions in ths list */
98916   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
98917   int iFirst,               /* Be searching with the iFirst-th expression */
98918   int iBase                 /* Ignore references to this table */
98919 ){
98920   Bitmask allowed = ~getMask(pMaskSet, iBase);
98921   while( iFirst<pList->nExpr ){
98922     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
98923       return 1;
98924     }
98925   }
98926   return 0;
98927 }
98928
98929
98930 /*
98931 ** This routine decides if pIdx can be used to satisfy the ORDER BY
98932 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
98933 ** ORDER BY clause, this routine returns 0.
98934 **
98935 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
98936 ** left-most table in the FROM clause of that same SELECT statement and
98937 ** the table has a cursor number of "base".  pIdx is an index on pTab.
98938 **
98939 ** nEqCol is the number of columns of pIdx that are used as equality
98940 ** constraints.  Any of these columns may be missing from the ORDER BY
98941 ** clause and the match can still be a success.
98942 **
98943 ** All terms of the ORDER BY that match against the index must be either
98944 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
98945 ** index do not need to satisfy this constraint.)  The *pbRev value is
98946 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
98947 ** the ORDER BY clause is all ASC.
98948 */
98949 static int isSortingIndex(
98950   Parse *pParse,          /* Parsing context */
98951   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
98952   Index *pIdx,            /* The index we are testing */
98953   int base,               /* Cursor number for the table to be sorted */
98954   ExprList *pOrderBy,     /* The ORDER BY clause */
98955   int nEqCol,             /* Number of index columns with == constraints */
98956   int wsFlags,            /* Index usages flags */
98957   int *pbRev              /* Set to 1 if ORDER BY is DESC */
98958 ){
98959   int i, j;                       /* Loop counters */
98960   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
98961   int nTerm;                      /* Number of ORDER BY terms */
98962   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
98963   sqlite3 *db = pParse->db;
98964
98965   assert( pOrderBy!=0 );
98966   nTerm = pOrderBy->nExpr;
98967   assert( nTerm>0 );
98968
98969   /* Argument pIdx must either point to a 'real' named index structure, 
98970   ** or an index structure allocated on the stack by bestBtreeIndex() to
98971   ** represent the rowid index that is part of every table.  */
98972   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
98973
98974   /* Match terms of the ORDER BY clause against columns of
98975   ** the index.
98976   **
98977   ** Note that indices have pIdx->nColumn regular columns plus
98978   ** one additional column containing the rowid.  The rowid column
98979   ** of the index is also allowed to match against the ORDER BY
98980   ** clause.
98981   */
98982   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
98983     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
98984     CollSeq *pColl;    /* The collating sequence of pExpr */
98985     int termSortOrder; /* Sort order for this term */
98986     int iColumn;       /* The i-th column of the index.  -1 for rowid */
98987     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
98988     const char *zColl; /* Name of the collating sequence for i-th index term */
98989
98990     pExpr = pTerm->pExpr;
98991     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
98992       /* Can not use an index sort on anything that is not a column in the
98993       ** left-most table of the FROM clause */
98994       break;
98995     }
98996     pColl = sqlite3ExprCollSeq(pParse, pExpr);
98997     if( !pColl ){
98998       pColl = db->pDfltColl;
98999     }
99000     if( pIdx->zName && i<pIdx->nColumn ){
99001       iColumn = pIdx->aiColumn[i];
99002       if( iColumn==pIdx->pTable->iPKey ){
99003         iColumn = -1;
99004       }
99005       iSortOrder = pIdx->aSortOrder[i];
99006       zColl = pIdx->azColl[i];
99007     }else{
99008       iColumn = -1;
99009       iSortOrder = 0;
99010       zColl = pColl->zName;
99011     }
99012     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99013       /* Term j of the ORDER BY clause does not match column i of the index */
99014       if( i<nEqCol ){
99015         /* If an index column that is constrained by == fails to match an
99016         ** ORDER BY term, that is OK.  Just ignore that column of the index
99017         */
99018         continue;
99019       }else if( i==pIdx->nColumn ){
99020         /* Index column i is the rowid.  All other terms match. */
99021         break;
99022       }else{
99023         /* If an index column fails to match and is not constrained by ==
99024         ** then the index cannot satisfy the ORDER BY constraint.
99025         */
99026         return 0;
99027       }
99028     }
99029     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99030     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99031     assert( iSortOrder==0 || iSortOrder==1 );
99032     termSortOrder = iSortOrder ^ pTerm->sortOrder;
99033     if( i>nEqCol ){
99034       if( termSortOrder!=sortOrder ){
99035         /* Indices can only be used if all ORDER BY terms past the
99036         ** equality constraints are all either DESC or ASC. */
99037         return 0;
99038       }
99039     }else{
99040       sortOrder = termSortOrder;
99041     }
99042     j++;
99043     pTerm++;
99044     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99045       /* If the indexed column is the primary key and everything matches
99046       ** so far and none of the ORDER BY terms to the right reference other
99047       ** tables in the join, then we are assured that the index can be used 
99048       ** to sort because the primary key is unique and so none of the other
99049       ** columns will make any difference
99050       */
99051       j = nTerm;
99052     }
99053   }
99054
99055   *pbRev = sortOrder!=0;
99056   if( j>=nTerm ){
99057     /* All terms of the ORDER BY clause are covered by this index so
99058     ** this index can be used for sorting. */
99059     return 1;
99060   }
99061   if( pIdx->onError!=OE_None && i==pIdx->nColumn
99062       && (wsFlags & WHERE_COLUMN_NULL)==0
99063       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99064     /* All terms of this index match some prefix of the ORDER BY clause
99065     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99066     ** clause reference other tables in a join.  If this is all true then
99067     ** the order by clause is superfluous.  Not that if the matching
99068     ** condition is IS NULL then the result is not necessarily unique
99069     ** even on a UNIQUE index, so disallow those cases. */
99070     return 1;
99071   }
99072   return 0;
99073 }
99074
99075 /*
99076 ** Prepare a crude estimate of the logarithm of the input value.
99077 ** The results need not be exact.  This is only used for estimating
99078 ** the total cost of performing operations with O(logN) or O(NlogN)
99079 ** complexity.  Because N is just a guess, it is no great tragedy if
99080 ** logN is a little off.
99081 */
99082 static double estLog(double N){
99083   double logN = 1;
99084   double x = 10;
99085   while( N>x ){
99086     logN += 1;
99087     x *= 10;
99088   }
99089   return logN;
99090 }
99091
99092 /*
99093 ** Two routines for printing the content of an sqlite3_index_info
99094 ** structure.  Used for testing and debugging only.  If neither
99095 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99096 ** are no-ops.
99097 */
99098 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99099 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99100   int i;
99101   if( !sqlite3WhereTrace ) return;
99102   for(i=0; i<p->nConstraint; i++){
99103     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99104        i,
99105        p->aConstraint[i].iColumn,
99106        p->aConstraint[i].iTermOffset,
99107        p->aConstraint[i].op,
99108        p->aConstraint[i].usable);
99109   }
99110   for(i=0; i<p->nOrderBy; i++){
99111     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
99112        i,
99113        p->aOrderBy[i].iColumn,
99114        p->aOrderBy[i].desc);
99115   }
99116 }
99117 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99118   int i;
99119   if( !sqlite3WhereTrace ) return;
99120   for(i=0; i<p->nConstraint; i++){
99121     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
99122        i,
99123        p->aConstraintUsage[i].argvIndex,
99124        p->aConstraintUsage[i].omit);
99125   }
99126   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
99127   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
99128   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
99129   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
99130 }
99131 #else
99132 #define TRACE_IDX_INPUTS(A)
99133 #define TRACE_IDX_OUTPUTS(A)
99134 #endif
99135
99136 /* 
99137 ** Required because bestIndex() is called by bestOrClauseIndex() 
99138 */
99139 static void bestIndex(
99140     Parse*, WhereClause*, struct SrcList_item*,
99141     Bitmask, Bitmask, ExprList*, WhereCost*);
99142
99143 /*
99144 ** This routine attempts to find an scanning strategy that can be used 
99145 ** to optimize an 'OR' expression that is part of a WHERE clause. 
99146 **
99147 ** The table associated with FROM clause term pSrc may be either a
99148 ** regular B-Tree table or a virtual table.
99149 */
99150 static void bestOrClauseIndex(
99151   Parse *pParse,              /* The parsing context */
99152   WhereClause *pWC,           /* The WHERE clause */
99153   struct SrcList_item *pSrc,  /* The FROM clause term to search */
99154   Bitmask notReady,           /* Mask of cursors not available for indexing */
99155   Bitmask notValid,           /* Cursors not available for any purpose */
99156   ExprList *pOrderBy,         /* The ORDER BY clause */
99157   WhereCost *pCost            /* Lowest cost query plan */
99158 ){
99159 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99160   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
99161   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
99162   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
99163   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
99164
99165   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99166   ** are used */
99167   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99168     return;
99169   }
99170
99171   /* Search the WHERE clause terms for a usable WO_OR term. */
99172   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99173     if( pTerm->eOperator==WO_OR 
99174      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99175      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
99176     ){
99177       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99178       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99179       WhereTerm *pOrTerm;
99180       int flags = WHERE_MULTI_OR;
99181       double rTotal = 0;
99182       double nRow = 0;
99183       Bitmask used = 0;
99184
99185       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99186         WhereCost sTermCost;
99187         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
99188           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99189         ));
99190         if( pOrTerm->eOperator==WO_AND ){
99191           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99192           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99193         }else if( pOrTerm->leftCursor==iCur ){
99194           WhereClause tempWC;
99195           tempWC.pParse = pWC->pParse;
99196           tempWC.pMaskSet = pWC->pMaskSet;
99197           tempWC.op = TK_AND;
99198           tempWC.a = pOrTerm;
99199           tempWC.nTerm = 1;
99200           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
99201         }else{
99202           continue;
99203         }
99204         rTotal += sTermCost.rCost;
99205         nRow += sTermCost.plan.nRow;
99206         used |= sTermCost.used;
99207         if( rTotal>=pCost->rCost ) break;
99208       }
99209
99210       /* If there is an ORDER BY clause, increase the scan cost to account 
99211       ** for the cost of the sort. */
99212       if( pOrderBy!=0 ){
99213         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
99214                     rTotal, rTotal+nRow*estLog(nRow)));
99215         rTotal += nRow*estLog(nRow);
99216       }
99217
99218       /* If the cost of scanning using this OR term for optimization is
99219       ** less than the current cost stored in pCost, replace the contents
99220       ** of pCost. */
99221       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
99222       if( rTotal<pCost->rCost ){
99223         pCost->rCost = rTotal;
99224         pCost->used = used;
99225         pCost->plan.nRow = nRow;
99226         pCost->plan.wsFlags = flags;
99227         pCost->plan.u.pTerm = pTerm;
99228       }
99229     }
99230   }
99231 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99232 }
99233
99234 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99235 /*
99236 ** Return TRUE if the WHERE clause term pTerm is of a form where it
99237 ** could be used with an index to access pSrc, assuming an appropriate
99238 ** index existed.
99239 */
99240 static int termCanDriveIndex(
99241   WhereTerm *pTerm,              /* WHERE clause term to check */
99242   struct SrcList_item *pSrc,     /* Table we are trying to access */
99243   Bitmask notReady               /* Tables in outer loops of the join */
99244 ){
99245   char aff;
99246   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
99247   if( pTerm->eOperator!=WO_EQ ) return 0;
99248   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
99249   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
99250   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
99251   return 1;
99252 }
99253 #endif
99254
99255 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99256 /*
99257 ** If the query plan for pSrc specified in pCost is a full table scan
99258 ** and indexing is allows (if there is no NOT INDEXED clause) and it
99259 ** possible to construct a transient index that would perform better
99260 ** than a full table scan even when the cost of constructing the index
99261 ** is taken into account, then alter the query plan to use the
99262 ** transient index.
99263 */
99264 static void bestAutomaticIndex(
99265   Parse *pParse,              /* The parsing context */
99266   WhereClause *pWC,           /* The WHERE clause */
99267   struct SrcList_item *pSrc,  /* The FROM clause term to search */
99268   Bitmask notReady,           /* Mask of cursors that are not available */
99269   WhereCost *pCost            /* Lowest cost query plan */
99270 ){
99271   double nTableRow;           /* Rows in the input table */
99272   double logN;                /* log(nTableRow) */
99273   double costTempIdx;         /* per-query cost of the transient index */
99274   WhereTerm *pTerm;           /* A single term of the WHERE clause */
99275   WhereTerm *pWCEnd;          /* End of pWC->a[] */
99276   Table *pTable;              /* Table tht might be indexed */
99277
99278   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
99279     /* Automatic indices are disabled at run-time */
99280     return;
99281   }
99282   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
99283     /* We already have some kind of index in use for this query. */
99284     return;
99285   }
99286   if( pSrc->notIndexed ){
99287     /* The NOT INDEXED clause appears in the SQL. */
99288     return;
99289   }
99290
99291   assert( pParse->nQueryLoop >= (double)1 );
99292   pTable = pSrc->pTab;
99293   nTableRow = pTable->nRowEst;
99294   logN = estLog(nTableRow);
99295   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
99296   if( costTempIdx>=pCost->rCost ){
99297     /* The cost of creating the transient table would be greater than
99298     ** doing the full table scan */
99299     return;
99300   }
99301
99302   /* Search for any equality comparison term */
99303   pWCEnd = &pWC->a[pWC->nTerm];
99304   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99305     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99306       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
99307                     pCost->rCost, costTempIdx));
99308       pCost->rCost = costTempIdx;
99309       pCost->plan.nRow = logN + 1;
99310       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
99311       pCost->used = pTerm->prereqRight;
99312       break;
99313     }
99314   }
99315 }
99316 #else
99317 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
99318 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99319
99320
99321 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99322 /*
99323 ** Generate code to construct the Index object for an automatic index
99324 ** and to set up the WhereLevel object pLevel so that the code generator
99325 ** makes use of the automatic index.
99326 */
99327 static void constructAutomaticIndex(
99328   Parse *pParse,              /* The parsing context */
99329   WhereClause *pWC,           /* The WHERE clause */
99330   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
99331   Bitmask notReady,           /* Mask of cursors that are not available */
99332   WhereLevel *pLevel          /* Write new index here */
99333 ){
99334   int nColumn;                /* Number of columns in the constructed index */
99335   WhereTerm *pTerm;           /* A single term of the WHERE clause */
99336   WhereTerm *pWCEnd;          /* End of pWC->a[] */
99337   int nByte;                  /* Byte of memory needed for pIdx */
99338   Index *pIdx;                /* Object describing the transient index */
99339   Vdbe *v;                    /* Prepared statement under construction */
99340   int regIsInit;              /* Register set by initialization */
99341   int addrInit;               /* Address of the initialization bypass jump */
99342   Table *pTable;              /* The table being indexed */
99343   KeyInfo *pKeyinfo;          /* Key information for the index */   
99344   int addrTop;                /* Top of the index fill loop */
99345   int regRecord;              /* Register holding an index record */
99346   int n;                      /* Column counter */
99347   int i;                      /* Loop counter */
99348   int mxBitCol;               /* Maximum column in pSrc->colUsed */
99349   CollSeq *pColl;             /* Collating sequence to on a column */
99350   Bitmask idxCols;            /* Bitmap of columns used for indexing */
99351   Bitmask extraCols;          /* Bitmap of additional columns */
99352
99353   /* Generate code to skip over the creation and initialization of the
99354   ** transient index on 2nd and subsequent iterations of the loop. */
99355   v = pParse->pVdbe;
99356   assert( v!=0 );
99357   regIsInit = ++pParse->nMem;
99358   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
99359   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
99360
99361   /* Count the number of columns that will be added to the index
99362   ** and used to match WHERE clause constraints */
99363   nColumn = 0;
99364   pTable = pSrc->pTab;
99365   pWCEnd = &pWC->a[pWC->nTerm];
99366   idxCols = 0;
99367   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99368     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99369       int iCol = pTerm->u.leftColumn;
99370       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99371       testcase( iCol==BMS );
99372       testcase( iCol==BMS-1 );
99373       if( (idxCols & cMask)==0 ){
99374         nColumn++;
99375         idxCols |= cMask;
99376       }
99377     }
99378   }
99379   assert( nColumn>0 );
99380   pLevel->plan.nEq = nColumn;
99381
99382   /* Count the number of additional columns needed to create a
99383   ** covering index.  A "covering index" is an index that contains all
99384   ** columns that are needed by the query.  With a covering index, the
99385   ** original table never needs to be accessed.  Automatic indices must
99386   ** be a covering index because the index will not be updated if the
99387   ** original table changes and the index and table cannot both be used
99388   ** if they go out of sync.
99389   */
99390   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
99391   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
99392   testcase( pTable->nCol==BMS-1 );
99393   testcase( pTable->nCol==BMS-2 );
99394   for(i=0; i<mxBitCol; i++){
99395     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
99396   }
99397   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99398     nColumn += pTable->nCol - BMS + 1;
99399   }
99400   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
99401
99402   /* Construct the Index object to describe this index */
99403   nByte = sizeof(Index);
99404   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
99405   nByte += nColumn*sizeof(char*);   /* Index.azColl */
99406   nByte += nColumn;                 /* Index.aSortOrder */
99407   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
99408   if( pIdx==0 ) return;
99409   pLevel->plan.u.pIdx = pIdx;
99410   pIdx->azColl = (char**)&pIdx[1];
99411   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
99412   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
99413   pIdx->zName = "auto-index";
99414   pIdx->nColumn = nColumn;
99415   pIdx->pTable = pTable;
99416   n = 0;
99417   idxCols = 0;
99418   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99419     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99420       int iCol = pTerm->u.leftColumn;
99421       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99422       if( (idxCols & cMask)==0 ){
99423         Expr *pX = pTerm->pExpr;
99424         idxCols |= cMask;
99425         pIdx->aiColumn[n] = pTerm->u.leftColumn;
99426         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
99427         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
99428         n++;
99429       }
99430     }
99431   }
99432   assert( (u32)n==pLevel->plan.nEq );
99433
99434   /* Add additional columns needed to make the automatic index into
99435   ** a covering index */
99436   for(i=0; i<mxBitCol; i++){
99437     if( extraCols & (((Bitmask)1)<<i) ){
99438       pIdx->aiColumn[n] = i;
99439       pIdx->azColl[n] = "BINARY";
99440       n++;
99441     }
99442   }
99443   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99444     for(i=BMS-1; i<pTable->nCol; i++){
99445       pIdx->aiColumn[n] = i;
99446       pIdx->azColl[n] = "BINARY";
99447       n++;
99448     }
99449   }
99450   assert( n==nColumn );
99451
99452   /* Create the automatic index */
99453   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
99454   assert( pLevel->iIdxCur>=0 );
99455   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
99456                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
99457   VdbeComment((v, "for %s", pTable->zName));
99458
99459   /* Fill the automatic index with content */
99460   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
99461   regRecord = sqlite3GetTempReg(pParse);
99462   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
99463   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
99464   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
99465   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
99466   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
99467   sqlite3VdbeJumpHere(v, addrTop);
99468   sqlite3ReleaseTempReg(pParse, regRecord);
99469   
99470   /* Jump here when skipping the initialization */
99471   sqlite3VdbeJumpHere(v, addrInit);
99472 }
99473 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99474
99475 #ifndef SQLITE_OMIT_VIRTUALTABLE
99476 /*
99477 ** Allocate and populate an sqlite3_index_info structure. It is the 
99478 ** responsibility of the caller to eventually release the structure
99479 ** by passing the pointer returned by this function to sqlite3_free().
99480 */
99481 static sqlite3_index_info *allocateIndexInfo(
99482   Parse *pParse, 
99483   WhereClause *pWC,
99484   struct SrcList_item *pSrc,
99485   ExprList *pOrderBy
99486 ){
99487   int i, j;
99488   int nTerm;
99489   struct sqlite3_index_constraint *pIdxCons;
99490   struct sqlite3_index_orderby *pIdxOrderBy;
99491   struct sqlite3_index_constraint_usage *pUsage;
99492   WhereTerm *pTerm;
99493   int nOrderBy;
99494   sqlite3_index_info *pIdxInfo;
99495
99496   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
99497
99498   /* Count the number of possible WHERE clause constraints referring
99499   ** to this virtual table */
99500   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99501     if( pTerm->leftCursor != pSrc->iCursor ) continue;
99502     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99503     testcase( pTerm->eOperator==WO_IN );
99504     testcase( pTerm->eOperator==WO_ISNULL );
99505     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99506     nTerm++;
99507   }
99508
99509   /* If the ORDER BY clause contains only columns in the current 
99510   ** virtual table then allocate space for the aOrderBy part of
99511   ** the sqlite3_index_info structure.
99512   */
99513   nOrderBy = 0;
99514   if( pOrderBy ){
99515     for(i=0; i<pOrderBy->nExpr; i++){
99516       Expr *pExpr = pOrderBy->a[i].pExpr;
99517       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
99518     }
99519     if( i==pOrderBy->nExpr ){
99520       nOrderBy = pOrderBy->nExpr;
99521     }
99522   }
99523
99524   /* Allocate the sqlite3_index_info structure
99525   */
99526   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
99527                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
99528                            + sizeof(*pIdxOrderBy)*nOrderBy );
99529   if( pIdxInfo==0 ){
99530     sqlite3ErrorMsg(pParse, "out of memory");
99531     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
99532     return 0;
99533   }
99534
99535   /* Initialize the structure.  The sqlite3_index_info structure contains
99536   ** many fields that are declared "const" to prevent xBestIndex from
99537   ** changing them.  We have to do some funky casting in order to
99538   ** initialize those fields.
99539   */
99540   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
99541   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
99542   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
99543   *(int*)&pIdxInfo->nConstraint = nTerm;
99544   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
99545   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
99546   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
99547   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
99548                                                                    pUsage;
99549
99550   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99551     if( pTerm->leftCursor != pSrc->iCursor ) continue;
99552     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99553     testcase( pTerm->eOperator==WO_IN );
99554     testcase( pTerm->eOperator==WO_ISNULL );
99555     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99556     pIdxCons[j].iColumn = pTerm->u.leftColumn;
99557     pIdxCons[j].iTermOffset = i;
99558     pIdxCons[j].op = (u8)pTerm->eOperator;
99559     /* The direct assignment in the previous line is possible only because
99560     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
99561     ** following asserts verify this fact. */
99562     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
99563     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
99564     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
99565     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
99566     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
99567     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
99568     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
99569     j++;
99570   }
99571   for(i=0; i<nOrderBy; i++){
99572     Expr *pExpr = pOrderBy->a[i].pExpr;
99573     pIdxOrderBy[i].iColumn = pExpr->iColumn;
99574     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
99575   }
99576
99577   return pIdxInfo;
99578 }
99579
99580 /*
99581 ** The table object reference passed as the second argument to this function
99582 ** must represent a virtual table. This function invokes the xBestIndex()
99583 ** method of the virtual table with the sqlite3_index_info pointer passed
99584 ** as the argument.
99585 **
99586 ** If an error occurs, pParse is populated with an error message and a
99587 ** non-zero value is returned. Otherwise, 0 is returned and the output
99588 ** part of the sqlite3_index_info structure is left populated.
99589 **
99590 ** Whether or not an error is returned, it is the responsibility of the
99591 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
99592 ** that this is required.
99593 */
99594 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
99595   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
99596   int i;
99597   int rc;
99598
99599   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
99600   TRACE_IDX_INPUTS(p);
99601   rc = pVtab->pModule->xBestIndex(pVtab, p);
99602   TRACE_IDX_OUTPUTS(p);
99603
99604   if( rc!=SQLITE_OK ){
99605     if( rc==SQLITE_NOMEM ){
99606       pParse->db->mallocFailed = 1;
99607     }else if( !pVtab->zErrMsg ){
99608       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
99609     }else{
99610       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
99611     }
99612   }
99613   sqlite3_free(pVtab->zErrMsg);
99614   pVtab->zErrMsg = 0;
99615
99616   for(i=0; i<p->nConstraint; i++){
99617     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
99618       sqlite3ErrorMsg(pParse, 
99619           "table %s: xBestIndex returned an invalid plan", pTab->zName);
99620     }
99621   }
99622
99623   return pParse->nErr;
99624 }
99625
99626
99627 /*
99628 ** Compute the best index for a virtual table.
99629 **
99630 ** The best index is computed by the xBestIndex method of the virtual
99631 ** table module.  This routine is really just a wrapper that sets up
99632 ** the sqlite3_index_info structure that is used to communicate with
99633 ** xBestIndex.
99634 **
99635 ** In a join, this routine might be called multiple times for the
99636 ** same virtual table.  The sqlite3_index_info structure is created
99637 ** and initialized on the first invocation and reused on all subsequent
99638 ** invocations.  The sqlite3_index_info structure is also used when
99639 ** code is generated to access the virtual table.  The whereInfoDelete() 
99640 ** routine takes care of freeing the sqlite3_index_info structure after
99641 ** everybody has finished with it.
99642 */
99643 static void bestVirtualIndex(
99644   Parse *pParse,                  /* The parsing context */
99645   WhereClause *pWC,               /* The WHERE clause */
99646   struct SrcList_item *pSrc,      /* The FROM clause term to search */
99647   Bitmask notReady,               /* Mask of cursors not available for index */
99648   Bitmask notValid,               /* Cursors not valid for any purpose */
99649   ExprList *pOrderBy,             /* The order by clause */
99650   WhereCost *pCost,               /* Lowest cost query plan */
99651   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
99652 ){
99653   Table *pTab = pSrc->pTab;
99654   sqlite3_index_info *pIdxInfo;
99655   struct sqlite3_index_constraint *pIdxCons;
99656   struct sqlite3_index_constraint_usage *pUsage;
99657   WhereTerm *pTerm;
99658   int i, j;
99659   int nOrderBy;
99660   double rCost;
99661
99662   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
99663   ** malloc in allocateIndexInfo() fails and this function returns leaving
99664   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
99665   */
99666   memset(pCost, 0, sizeof(*pCost));
99667   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
99668
99669   /* If the sqlite3_index_info structure has not been previously
99670   ** allocated and initialized, then allocate and initialize it now.
99671   */
99672   pIdxInfo = *ppIdxInfo;
99673   if( pIdxInfo==0 ){
99674     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
99675   }
99676   if( pIdxInfo==0 ){
99677     return;
99678   }
99679
99680   /* At this point, the sqlite3_index_info structure that pIdxInfo points
99681   ** to will have been initialized, either during the current invocation or
99682   ** during some prior invocation.  Now we just have to customize the
99683   ** details of pIdxInfo for the current invocation and pass it to
99684   ** xBestIndex.
99685   */
99686
99687   /* The module name must be defined. Also, by this point there must
99688   ** be a pointer to an sqlite3_vtab structure. Otherwise
99689   ** sqlite3ViewGetColumnNames() would have picked up the error. 
99690   */
99691   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
99692   assert( sqlite3GetVTable(pParse->db, pTab) );
99693
99694   /* Set the aConstraint[].usable fields and initialize all 
99695   ** output variables to zero.
99696   **
99697   ** aConstraint[].usable is true for constraints where the right-hand
99698   ** side contains only references to tables to the left of the current
99699   ** table.  In other words, if the constraint is of the form:
99700   **
99701   **           column = expr
99702   **
99703   ** and we are evaluating a join, then the constraint on column is 
99704   ** only valid if all tables referenced in expr occur to the left
99705   ** of the table containing column.
99706   **
99707   ** The aConstraints[] array contains entries for all constraints
99708   ** on the current table.  That way we only have to compute it once
99709   ** even though we might try to pick the best index multiple times.
99710   ** For each attempt at picking an index, the order of tables in the
99711   ** join might be different so we have to recompute the usable flag
99712   ** each time.
99713   */
99714   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99715   pUsage = pIdxInfo->aConstraintUsage;
99716   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
99717     j = pIdxCons->iTermOffset;
99718     pTerm = &pWC->a[j];
99719     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
99720   }
99721   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
99722   if( pIdxInfo->needToFreeIdxStr ){
99723     sqlite3_free(pIdxInfo->idxStr);
99724   }
99725   pIdxInfo->idxStr = 0;
99726   pIdxInfo->idxNum = 0;
99727   pIdxInfo->needToFreeIdxStr = 0;
99728   pIdxInfo->orderByConsumed = 0;
99729   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
99730   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
99731   nOrderBy = pIdxInfo->nOrderBy;
99732   if( !pOrderBy ){
99733     pIdxInfo->nOrderBy = 0;
99734   }
99735
99736   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
99737     return;
99738   }
99739
99740   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
99741   for(i=0; i<pIdxInfo->nConstraint; i++){
99742     if( pUsage[i].argvIndex>0 ){
99743       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
99744     }
99745   }
99746
99747   /* If there is an ORDER BY clause, and the selected virtual table index
99748   ** does not satisfy it, increase the cost of the scan accordingly. This
99749   ** matches the processing for non-virtual tables in bestBtreeIndex().
99750   */
99751   rCost = pIdxInfo->estimatedCost;
99752   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
99753     rCost += estLog(rCost)*rCost;
99754   }
99755
99756   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
99757   ** inital value of lowestCost in this loop. If it is, then the
99758   ** (cost<lowestCost) test below will never be true.
99759   ** 
99760   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
99761   ** is defined.
99762   */
99763   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
99764     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
99765   }else{
99766     pCost->rCost = rCost;
99767   }
99768   pCost->plan.u.pVtabIdx = pIdxInfo;
99769   if( pIdxInfo->orderByConsumed ){
99770     pCost->plan.wsFlags |= WHERE_ORDERBY;
99771   }
99772   pCost->plan.nEq = 0;
99773   pIdxInfo->nOrderBy = nOrderBy;
99774
99775   /* Try to find a more efficient access pattern by using multiple indexes
99776   ** to optimize an OR expression within the WHERE clause. 
99777   */
99778   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
99779 }
99780 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99781
99782 /*
99783 ** Argument pIdx is a pointer to an index structure that has an array of
99784 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
99785 ** stored in Index.aSample. These samples divide the domain of values stored
99786 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
99787 ** Region 0 contains all values less than the first sample value. Region
99788 ** 1 contains values between the first and second samples.  Region 2 contains
99789 ** values between samples 2 and 3.  And so on.  Region SQLITE_INDEX_SAMPLES
99790 ** contains values larger than the last sample.
99791 **
99792 ** If the index contains many duplicates of a single value, then it is
99793 ** possible that two or more adjacent samples can hold the same value.
99794 ** When that is the case, the smallest possible region code is returned
99795 ** when roundUp is false and the largest possible region code is returned
99796 ** when roundUp is true.
99797 **
99798 ** If successful, this function determines which of the regions value 
99799 ** pVal lies in, sets *piRegion to the region index (a value between 0
99800 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
99801 ** Or, if an OOM occurs while converting text values between encodings,
99802 ** SQLITE_NOMEM is returned and *piRegion is undefined.
99803 */
99804 #ifdef SQLITE_ENABLE_STAT2
99805 static int whereRangeRegion(
99806   Parse *pParse,              /* Database connection */
99807   Index *pIdx,                /* Index to consider domain of */
99808   sqlite3_value *pVal,        /* Value to consider */
99809   int roundUp,                /* Return largest valid region if true */
99810   int *piRegion               /* OUT: Region of domain in which value lies */
99811 ){
99812   assert( roundUp==0 || roundUp==1 );
99813   if( ALWAYS(pVal) ){
99814     IndexSample *aSample = pIdx->aSample;
99815     int i = 0;
99816     int eType = sqlite3_value_type(pVal);
99817
99818     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
99819       double r = sqlite3_value_double(pVal);
99820       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99821         if( aSample[i].eType==SQLITE_NULL ) continue;
99822         if( aSample[i].eType>=SQLITE_TEXT ) break;
99823         if( roundUp ){
99824           if( aSample[i].u.r>r ) break;
99825         }else{
99826           if( aSample[i].u.r>=r ) break;
99827         }
99828       }
99829     }else if( eType==SQLITE_NULL ){
99830       i = 0;
99831       if( roundUp ){
99832         while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
99833       }
99834     }else{ 
99835       sqlite3 *db = pParse->db;
99836       CollSeq *pColl;
99837       const u8 *z;
99838       int n;
99839
99840       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
99841       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
99842
99843       if( eType==SQLITE_BLOB ){
99844         z = (const u8 *)sqlite3_value_blob(pVal);
99845         pColl = db->pDfltColl;
99846         assert( pColl->enc==SQLITE_UTF8 );
99847       }else{
99848         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
99849         if( pColl==0 ){
99850           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
99851                           *pIdx->azColl);
99852           return SQLITE_ERROR;
99853         }
99854         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
99855         if( !z ){
99856           return SQLITE_NOMEM;
99857         }
99858         assert( z && pColl && pColl->xCmp );
99859       }
99860       n = sqlite3ValueBytes(pVal, pColl->enc);
99861
99862       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
99863         int c;
99864         int eSampletype = aSample[i].eType;
99865         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
99866         if( (eSampletype!=eType) ) break;
99867 #ifndef SQLITE_OMIT_UTF16
99868         if( pColl->enc!=SQLITE_UTF8 ){
99869           int nSample;
99870           char *zSample = sqlite3Utf8to16(
99871               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
99872           );
99873           if( !zSample ){
99874             assert( db->mallocFailed );
99875             return SQLITE_NOMEM;
99876           }
99877           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
99878           sqlite3DbFree(db, zSample);
99879         }else
99880 #endif
99881         {
99882           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
99883         }
99884         if( c-roundUp>=0 ) break;
99885       }
99886     }
99887
99888     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
99889     *piRegion = i;
99890   }
99891   return SQLITE_OK;
99892 }
99893 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
99894
99895 /*
99896 ** If expression pExpr represents a literal value, set *pp to point to
99897 ** an sqlite3_value structure containing the same value, with affinity
99898 ** aff applied to it, before returning. It is the responsibility of the 
99899 ** caller to eventually release this structure by passing it to 
99900 ** sqlite3ValueFree().
99901 **
99902 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
99903 ** is an SQL variable that currently has a non-NULL value bound to it,
99904 ** create an sqlite3_value structure containing this value, again with
99905 ** affinity aff applied to it, instead.
99906 **
99907 ** If neither of the above apply, set *pp to NULL.
99908 **
99909 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
99910 */
99911 #ifdef SQLITE_ENABLE_STAT2
99912 static int valueFromExpr(
99913   Parse *pParse, 
99914   Expr *pExpr, 
99915   u8 aff, 
99916   sqlite3_value **pp
99917 ){
99918   if( pExpr->op==TK_VARIABLE
99919    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
99920   ){
99921     int iVar = pExpr->iColumn;
99922     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
99923     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
99924     return SQLITE_OK;
99925   }
99926   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
99927 }
99928 #endif
99929
99930 /*
99931 ** This function is used to estimate the number of rows that will be visited
99932 ** by scanning an index for a range of values. The range may have an upper
99933 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
99934 ** and lower bounds are represented by pLower and pUpper respectively. For
99935 ** example, assuming that index p is on t1(a):
99936 **
99937 **   ... FROM t1 WHERE a > ? AND a < ? ...
99938 **                    |_____|   |_____|
99939 **                       |         |
99940 **                     pLower    pUpper
99941 **
99942 ** If either of the upper or lower bound is not present, then NULL is passed in
99943 ** place of the corresponding WhereTerm.
99944 **
99945 ** The nEq parameter is passed the index of the index column subject to the
99946 ** range constraint. Or, equivalently, the number of equality constraints
99947 ** optimized by the proposed index scan. For example, assuming index p is
99948 ** on t1(a, b), and the SQL query is:
99949 **
99950 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
99951 **
99952 ** then nEq should be passed the value 1 (as the range restricted column,
99953 ** b, is the second left-most column of the index). Or, if the query is:
99954 **
99955 **   ... FROM t1 WHERE a > ? AND a < ? ...
99956 **
99957 ** then nEq should be passed 0.
99958 **
99959 ** The returned value is an integer between 1 and 100, inclusive. A return
99960 ** value of 1 indicates that the proposed range scan is expected to visit
99961 ** approximately 1/100th (1%) of the rows selected by the nEq equality
99962 ** constraints (if any). A return value of 100 indicates that it is expected
99963 ** that the range scan will visit every row (100%) selected by the equality
99964 ** constraints.
99965 **
99966 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
99967 ** reduces the search space by 3/4ths.  Hence a single constraint (x>?)
99968 ** results in a return of 25 and a range constraint (x>? AND x<?) results
99969 ** in a return of 6.
99970 */
99971 static int whereRangeScanEst(
99972   Parse *pParse,       /* Parsing & code generating context */
99973   Index *p,            /* The index containing the range-compared column; "x" */
99974   int nEq,             /* index into p->aCol[] of the range-compared column */
99975   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
99976   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
99977   int *piEst           /* OUT: Return value */
99978 ){
99979   int rc = SQLITE_OK;
99980
99981 #ifdef SQLITE_ENABLE_STAT2
99982
99983   if( nEq==0 && p->aSample ){
99984     sqlite3_value *pLowerVal = 0;
99985     sqlite3_value *pUpperVal = 0;
99986     int iEst;
99987     int iLower = 0;
99988     int iUpper = SQLITE_INDEX_SAMPLES;
99989     int roundUpUpper = 0;
99990     int roundUpLower = 0;
99991     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
99992
99993     if( pLower ){
99994       Expr *pExpr = pLower->pExpr->pRight;
99995       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
99996       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
99997       roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
99998     }
99999     if( rc==SQLITE_OK && pUpper ){
100000       Expr *pExpr = pUpper->pExpr->pRight;
100001       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
100002       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
100003       roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
100004     }
100005
100006     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
100007       sqlite3ValueFree(pLowerVal);
100008       sqlite3ValueFree(pUpperVal);
100009       goto range_est_fallback;
100010     }else if( pLowerVal==0 ){
100011       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100012       if( pLower ) iLower = iUpper/2;
100013     }else if( pUpperVal==0 ){
100014       rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100015       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100016     }else{
100017       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100018       if( rc==SQLITE_OK ){
100019         rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100020       }
100021     }
100022     WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100023
100024     iEst = iUpper - iLower;
100025     testcase( iEst==SQLITE_INDEX_SAMPLES );
100026     assert( iEst<=SQLITE_INDEX_SAMPLES );
100027     if( iEst<1 ){
100028       *piEst = 50/SQLITE_INDEX_SAMPLES;
100029     }else{
100030       *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100031     }
100032     sqlite3ValueFree(pLowerVal);
100033     sqlite3ValueFree(pUpperVal);
100034     return rc;
100035   }
100036 range_est_fallback:
100037 #else
100038   UNUSED_PARAMETER(pParse);
100039   UNUSED_PARAMETER(p);
100040   UNUSED_PARAMETER(nEq);
100041 #endif
100042   assert( pLower || pUpper );
100043   *piEst = 100;
100044   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100045   if( pUpper ) *piEst /= 4;
100046   return rc;
100047 }
100048
100049 #ifdef SQLITE_ENABLE_STAT2
100050 /*
100051 ** Estimate the number of rows that will be returned based on
100052 ** an equality constraint x=VALUE and where that VALUE occurs in
100053 ** the histogram data.  This only works when x is the left-most
100054 ** column of an index and sqlite_stat2 histogram data is available
100055 ** for that index.  When pExpr==NULL that means the constraint is
100056 ** "x IS NULL" instead of "x=VALUE".
100057 **
100058 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100059 ** If unable to make an estimate, leave *pnRow unchanged and return
100060 ** non-zero.
100061 **
100062 ** This routine can fail if it is unable to load a collating sequence
100063 ** required for string comparison, or if unable to allocate memory
100064 ** for a UTF conversion required for comparison.  The error is stored
100065 ** in the pParse structure.
100066 */
100067 static int whereEqualScanEst(
100068   Parse *pParse,       /* Parsing & code generating context */
100069   Index *p,            /* The index whose left-most column is pTerm */
100070   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
100071   double *pnRow        /* Write the revised row estimate here */
100072 ){
100073   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
100074   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100075   u8 aff;                   /* Column affinity */
100076   int rc;                   /* Subfunction return code */
100077   double nRowEst;           /* New estimate of the number of rows */
100078
100079   assert( p->aSample!=0 );
100080   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100081   if( pExpr ){
100082     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100083     if( rc ) goto whereEqualScanEst_cancel;
100084   }else{
100085     pRhs = sqlite3ValueNew(pParse->db);
100086   }
100087   if( pRhs==0 ) return SQLITE_NOTFOUND;
100088   rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100089   if( rc ) goto whereEqualScanEst_cancel;
100090   rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100091   if( rc ) goto whereEqualScanEst_cancel;
100092   WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100093   if( iLower>=iUpper ){
100094     nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100095     if( nRowEst<*pnRow ) *pnRow = nRowEst;
100096   }else{
100097     nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100098     *pnRow = nRowEst;
100099   }
100100
100101 whereEqualScanEst_cancel:
100102   sqlite3ValueFree(pRhs);
100103   return rc;
100104 }
100105 #endif /* defined(SQLITE_ENABLE_STAT2) */
100106
100107 #ifdef SQLITE_ENABLE_STAT2
100108 /*
100109 ** Estimate the number of rows that will be returned based on
100110 ** an IN constraint where the right-hand side of the IN operator
100111 ** is a list of values.  Example:
100112 **
100113 **        WHERE x IN (1,2,3,4)
100114 **
100115 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100116 ** If unable to make an estimate, leave *pnRow unchanged and return
100117 ** non-zero.
100118 **
100119 ** This routine can fail if it is unable to load a collating sequence
100120 ** required for string comparison, or if unable to allocate memory
100121 ** for a UTF conversion required for comparison.  The error is stored
100122 ** in the pParse structure.
100123 */
100124 static int whereInScanEst(
100125   Parse *pParse,       /* Parsing & code generating context */
100126   Index *p,            /* The index whose left-most column is pTerm */
100127   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100128   double *pnRow        /* Write the revised row estimate here */
100129 ){
100130   sqlite3_value *pVal = 0;  /* One value from list */
100131   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100132   u8 aff;                   /* Column affinity */
100133   int rc = SQLITE_OK;       /* Subfunction return code */
100134   double nRowEst;           /* New estimate of the number of rows */
100135   int nSpan = 0;            /* Number of histogram regions spanned */
100136   int nSingle = 0;          /* Histogram regions hit by a single value */
100137   int nNotFound = 0;        /* Count of values that are not constants */
100138   int i;                               /* Loop counter */
100139   u8 aSpan[SQLITE_INDEX_SAMPLES+1];    /* Histogram regions that are spanned */
100140   u8 aSingle[SQLITE_INDEX_SAMPLES+1];  /* Histogram regions hit once */
100141
100142   assert( p->aSample!=0 );
100143   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100144   memset(aSpan, 0, sizeof(aSpan));
100145   memset(aSingle, 0, sizeof(aSingle));
100146   for(i=0; i<pList->nExpr; i++){
100147     sqlite3ValueFree(pVal);
100148     rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100149     if( rc ) break;
100150     if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100151       nNotFound++;
100152       continue;
100153     }
100154     rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100155     if( rc ) break;
100156     rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100157     if( rc ) break;
100158     if( iLower>=iUpper ){
100159       aSingle[iLower] = 1;
100160     }else{
100161       assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100162       while( iLower<iUpper ) aSpan[iLower++] = 1;
100163     }
100164   }
100165   if( rc==SQLITE_OK ){
100166     for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100167       if( aSpan[i] ){
100168         nSpan++;
100169       }else if( aSingle[i] ){
100170         nSingle++;
100171       }
100172     }
100173     nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100174                + nNotFound*p->aiRowEst[1];
100175     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100176     *pnRow = nRowEst;
100177     WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100178                  nSpan, nSingle, nNotFound, nRowEst));
100179   }
100180   sqlite3ValueFree(pVal);
100181   return rc;
100182 }
100183 #endif /* defined(SQLITE_ENABLE_STAT2) */
100184
100185
100186 /*
100187 ** Find the best query plan for accessing a particular table.  Write the
100188 ** best query plan and its cost into the WhereCost object supplied as the
100189 ** last parameter.
100190 **
100191 ** The lowest cost plan wins.  The cost is an estimate of the amount of
100192 ** CPU and disk I/O needed to process the requested result.
100193 ** Factors that influence cost include:
100194 **
100195 **    *  The estimated number of rows that will be retrieved.  (The
100196 **       fewer the better.)
100197 **
100198 **    *  Whether or not sorting must occur.
100199 **
100200 **    *  Whether or not there must be separate lookups in the
100201 **       index and in the main table.
100202 **
100203 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
100204 ** the SQL statement, then this function only considers plans using the 
100205 ** named index. If no such plan is found, then the returned cost is
100206 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
100207 ** then the cost is calculated in the usual way.
100208 **
100209 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
100210 ** in the SELECT statement, then no indexes are considered. However, the 
100211 ** selected plan may still take advantage of the built-in rowid primary key
100212 ** index.
100213 */
100214 static void bestBtreeIndex(
100215   Parse *pParse,              /* The parsing context */
100216   WhereClause *pWC,           /* The WHERE clause */
100217   struct SrcList_item *pSrc,  /* The FROM clause term to search */
100218   Bitmask notReady,           /* Mask of cursors not available for indexing */
100219   Bitmask notValid,           /* Cursors not available for any purpose */
100220   ExprList *pOrderBy,         /* The ORDER BY clause */
100221   WhereCost *pCost            /* Lowest cost query plan */
100222 ){
100223   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
100224   Index *pProbe;              /* An index we are evaluating */
100225   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
100226   int eqTermMask;             /* Current mask of valid equality operators */
100227   int idxEqTermMask;          /* Index mask of valid equality operators */
100228   Index sPk;                  /* A fake index object for the primary key */
100229   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
100230   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
100231   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
100232
100233   /* Initialize the cost to a worst-case value */
100234   memset(pCost, 0, sizeof(*pCost));
100235   pCost->rCost = SQLITE_BIG_DBL;
100236
100237   /* If the pSrc table is the right table of a LEFT JOIN then we may not
100238   ** use an index to satisfy IS NULL constraints on that table.  This is
100239   ** because columns might end up being NULL if the table does not match -
100240   ** a circumstance which the index cannot help us discover.  Ticket #2177.
100241   */
100242   if( pSrc->jointype & JT_LEFT ){
100243     idxEqTermMask = WO_EQ|WO_IN;
100244   }else{
100245     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
100246   }
100247
100248   if( pSrc->pIndex ){
100249     /* An INDEXED BY clause specifies a particular index to use */
100250     pIdx = pProbe = pSrc->pIndex;
100251     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100252     eqTermMask = idxEqTermMask;
100253   }else{
100254     /* There is no INDEXED BY clause.  Create a fake Index object in local
100255     ** variable sPk to represent the rowid primary key index.  Make this
100256     ** fake index the first in a chain of Index objects with all of the real
100257     ** indices to follow */
100258     Index *pFirst;                  /* First of real indices on the table */
100259     memset(&sPk, 0, sizeof(Index));
100260     sPk.nColumn = 1;
100261     sPk.aiColumn = &aiColumnPk;
100262     sPk.aiRowEst = aiRowEstPk;
100263     sPk.onError = OE_Replace;
100264     sPk.pTable = pSrc->pTab;
100265     aiRowEstPk[0] = pSrc->pTab->nRowEst;
100266     aiRowEstPk[1] = 1;
100267     pFirst = pSrc->pTab->pIndex;
100268     if( pSrc->notIndexed==0 ){
100269       /* The real indices of the table are only considered if the
100270       ** NOT INDEXED qualifier is omitted from the FROM clause */
100271       sPk.pNext = pFirst;
100272     }
100273     pProbe = &sPk;
100274     wsFlagMask = ~(
100275         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
100276     );
100277     eqTermMask = WO_EQ|WO_IN;
100278     pIdx = 0;
100279   }
100280
100281   /* Loop over all indices looking for the best one to use
100282   */
100283   for(; pProbe; pIdx=pProbe=pProbe->pNext){
100284     const unsigned int * const aiRowEst = pProbe->aiRowEst;
100285     double cost;                /* Cost of using pProbe */
100286     double nRow;                /* Estimated number of rows in result set */
100287     double log10N;              /* base-10 logarithm of nRow (inexact) */
100288     int rev;                    /* True to scan in reverse order */
100289     int wsFlags = 0;
100290     Bitmask used = 0;
100291
100292     /* The following variables are populated based on the properties of
100293     ** index being evaluated. They are then used to determine the expected
100294     ** cost and number of rows returned.
100295     **
100296     **  nEq: 
100297     **    Number of equality terms that can be implemented using the index.
100298     **    In other words, the number of initial fields in the index that
100299     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
100300     **
100301     **  nInMul:  
100302     **    The "in-multiplier". This is an estimate of how many seek operations 
100303     **    SQLite must perform on the index in question. For example, if the 
100304     **    WHERE clause is:
100305     **
100306     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
100307     **
100308     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
100309     **    set to 9. Given the same schema and either of the following WHERE 
100310     **    clauses:
100311     **
100312     **      WHERE a =  1
100313     **      WHERE a >= 2
100314     **
100315     **    nInMul is set to 1.
100316     **
100317     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
100318     **    the sub-select is assumed to return 25 rows for the purposes of 
100319     **    determining nInMul.
100320     **
100321     **  bInEst:  
100322     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
100323     **    in determining the value of nInMul.  Note that the RHS of the
100324     **    IN operator must be a SELECT, not a value list, for this variable
100325     **    to be true.
100326     **
100327     **  estBound:
100328     **    An estimate on the amount of the table that must be searched.  A
100329     **    value of 100 means the entire table is searched.  Range constraints
100330     **    might reduce this to a value less than 100 to indicate that only
100331     **    a fraction of the table needs searching.  In the absence of
100332     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
100333     **    space to 1/4rd its original size.  So an x>? constraint reduces
100334     **    estBound to 25.  Two constraints (x>? AND x<?) reduce estBound to 6.
100335     **
100336     **  bSort:   
100337     **    Boolean. True if there is an ORDER BY clause that will require an 
100338     **    external sort (i.e. scanning the index being evaluated will not 
100339     **    correctly order records).
100340     **
100341     **  bLookup: 
100342     **    Boolean. True if a table lookup is required for each index entry
100343     **    visited.  In other words, true if this is not a covering index.
100344     **    This is always false for the rowid primary key index of a table.
100345     **    For other indexes, it is true unless all the columns of the table
100346     **    used by the SELECT statement are present in the index (such an
100347     **    index is sometimes described as a covering index).
100348     **    For example, given the index on (a, b), the second of the following 
100349     **    two queries requires table b-tree lookups in order to find the value
100350     **    of column c, but the first does not because columns a and b are
100351     **    both available in the index.
100352     **
100353     **             SELECT a, b    FROM tbl WHERE a = 1;
100354     **             SELECT a, b, c FROM tbl WHERE a = 1;
100355     */
100356     int nEq;                      /* Number of == or IN terms matching index */
100357     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
100358     int nInMul = 1;               /* Number of distinct equalities to lookup */
100359     int estBound = 100;           /* Estimated reduction in search space */
100360     int nBound = 0;               /* Number of range constraints seen */
100361     int bSort = 0;                /* True if external sort required */
100362     int bLookup = 0;              /* True if not a covering index */
100363     WhereTerm *pTerm;             /* A single term of the WHERE clause */
100364 #ifdef SQLITE_ENABLE_STAT2
100365     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
100366 #endif
100367
100368     /* Determine the values of nEq and nInMul */
100369     for(nEq=0; nEq<pProbe->nColumn; nEq++){
100370       int j = pProbe->aiColumn[nEq];
100371       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
100372       if( pTerm==0 ) break;
100373       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
100374       if( pTerm->eOperator & WO_IN ){
100375         Expr *pExpr = pTerm->pExpr;
100376         wsFlags |= WHERE_COLUMN_IN;
100377         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100378           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
100379           nInMul *= 25;
100380           bInEst = 1;
100381         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
100382           /* "x IN (value, value, ...)" */
100383           nInMul *= pExpr->x.pList->nExpr;
100384         }
100385       }else if( pTerm->eOperator & WO_ISNULL ){
100386         wsFlags |= WHERE_COLUMN_NULL;
100387       }
100388 #ifdef SQLITE_ENABLE_STAT2
100389       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
100390 #endif
100391       used |= pTerm->prereqRight;
100392     }
100393
100394     /* Determine the value of estBound. */
100395     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
100396       int j = pProbe->aiColumn[nEq];
100397       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
100398         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
100399         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
100400         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
100401         if( pTop ){
100402           nBound = 1;
100403           wsFlags |= WHERE_TOP_LIMIT;
100404           used |= pTop->prereqRight;
100405         }
100406         if( pBtm ){
100407           nBound++;
100408           wsFlags |= WHERE_BTM_LIMIT;
100409           used |= pBtm->prereqRight;
100410         }
100411         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
100412       }
100413     }else if( pProbe->onError!=OE_None ){
100414       testcase( wsFlags & WHERE_COLUMN_IN );
100415       testcase( wsFlags & WHERE_COLUMN_NULL );
100416       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
100417         wsFlags |= WHERE_UNIQUE;
100418       }
100419     }
100420
100421     /* If there is an ORDER BY clause and the index being considered will
100422     ** naturally scan rows in the required order, set the appropriate flags
100423     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
100424     ** will scan rows in a different order, set the bSort variable.  */
100425     if( pOrderBy ){
100426       if( (wsFlags & WHERE_COLUMN_IN)==0
100427         && pProbe->bUnordered==0
100428         && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
100429                           nEq, wsFlags, &rev)
100430       ){
100431         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
100432         wsFlags |= (rev ? WHERE_REVERSE : 0);
100433       }else{
100434         bSort = 1;
100435       }
100436     }
100437
100438     /* If currently calculating the cost of using an index (not the IPK
100439     ** index), determine if all required column data may be obtained without 
100440     ** using the main table (i.e. if the index is a covering
100441     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
100442     ** wsFlags. Otherwise, set the bLookup variable to true.  */
100443     if( pIdx && wsFlags ){
100444       Bitmask m = pSrc->colUsed;
100445       int j;
100446       for(j=0; j<pIdx->nColumn; j++){
100447         int x = pIdx->aiColumn[j];
100448         if( x<BMS-1 ){
100449           m &= ~(((Bitmask)1)<<x);
100450         }
100451       }
100452       if( m==0 ){
100453         wsFlags |= WHERE_IDX_ONLY;
100454       }else{
100455         bLookup = 1;
100456       }
100457     }
100458
100459     /*
100460     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
100461     ** constraint, do not let the estimate exceed half the rows in the table.
100462     */
100463     nRow = (double)(aiRowEst[nEq] * nInMul);
100464     if( bInEst && nRow*2>aiRowEst[0] ){
100465       nRow = aiRowEst[0]/2;
100466       nInMul = (int)(nRow / aiRowEst[nEq]);
100467     }
100468
100469 #ifdef SQLITE_ENABLE_STAT2
100470     /* If the constraint is of the form x=VALUE and histogram
100471     ** data is available for column x, then it might be possible
100472     ** to get a better estimate on the number of rows based on
100473     ** VALUE and how common that value is according to the histogram.
100474     */
100475     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
100476       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
100477         testcase( pFirstTerm->eOperator==WO_EQ );
100478         testcase( pFirstTerm->eOperator==WO_ISNULL );
100479         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
100480       }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
100481         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
100482       }
100483     }
100484 #endif /* SQLITE_ENABLE_STAT2 */
100485
100486     /* Adjust the number of output rows and downward to reflect rows
100487     ** that are excluded by range constraints.
100488     */
100489     nRow = (nRow * (double)estBound) / (double)100;
100490     if( nRow<1 ) nRow = 1;
100491
100492     /* Experiments run on real SQLite databases show that the time needed
100493     ** to do a binary search to locate a row in a table or index is roughly
100494     ** log10(N) times the time to move from one row to the next row within
100495     ** a table or index.  The actual times can vary, with the size of
100496     ** records being an important factor.  Both moves and searches are
100497     ** slower with larger records, presumably because fewer records fit
100498     ** on one page and hence more pages have to be fetched.
100499     **
100500     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
100501     ** not give us data on the relative sizes of table and index records.
100502     ** So this computation assumes table records are about twice as big
100503     ** as index records
100504     */
100505     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100506       /* The cost of a full table scan is a number of move operations equal
100507       ** to the number of rows in the table.
100508       **
100509       ** We add an additional 4x penalty to full table scans.  This causes
100510       ** the cost function to err on the side of choosing an index over
100511       ** choosing a full scan.  This 4x full-scan penalty is an arguable
100512       ** decision and one which we expect to revisit in the future.  But
100513       ** it seems to be working well enough at the moment.
100514       */
100515       cost = aiRowEst[0]*4;
100516     }else{
100517       log10N = estLog(aiRowEst[0]);
100518       cost = nRow;
100519       if( pIdx ){
100520         if( bLookup ){
100521           /* For an index lookup followed by a table lookup:
100522           **    nInMul index searches to find the start of each index range
100523           **  + nRow steps through the index
100524           **  + nRow table searches to lookup the table entry using the rowid
100525           */
100526           cost += (nInMul + nRow)*log10N;
100527         }else{
100528           /* For a covering index:
100529           **     nInMul index searches to find the initial entry 
100530           **   + nRow steps through the index
100531           */
100532           cost += nInMul*log10N;
100533         }
100534       }else{
100535         /* For a rowid primary key lookup:
100536         **    nInMult table searches to find the initial entry for each range
100537         **  + nRow steps through the table
100538         */
100539         cost += nInMul*log10N;
100540       }
100541     }
100542
100543     /* Add in the estimated cost of sorting the result.  Actual experimental
100544     ** measurements of sorting performance in SQLite show that sorting time
100545     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
100546     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
100547     ** difference and select C of 3.0.
100548     */
100549     if( bSort ){
100550       cost += nRow*estLog(nRow)*3;
100551     }
100552
100553     /**** Cost of using this index has now been computed ****/
100554
100555     /* If there are additional constraints on this table that cannot
100556     ** be used with the current index, but which might lower the number
100557     ** of output rows, adjust the nRow value accordingly.  This only 
100558     ** matters if the current index is the least costly, so do not bother
100559     ** with this step if we already know this index will not be chosen.
100560     ** Also, never reduce the output row count below 2 using this step.
100561     **
100562     ** It is critical that the notValid mask be used here instead of
100563     ** the notReady mask.  When computing an "optimal" index, the notReady
100564     ** mask will only have one bit set - the bit for the current table.
100565     ** The notValid mask, on the other hand, always has all bits set for
100566     ** tables that are not in outer loops.  If notReady is used here instead
100567     ** of notValid, then a optimal index that depends on inner joins loops
100568     ** might be selected even when there exists an optimal index that has
100569     ** no such dependency.
100570     */
100571     if( nRow>2 && cost<=pCost->rCost ){
100572       int k;                       /* Loop counter */
100573       int nSkipEq = nEq;           /* Number of == constraints to skip */
100574       int nSkipRange = nBound;     /* Number of < constraints to skip */
100575       Bitmask thisTab;             /* Bitmap for pSrc */
100576
100577       thisTab = getMask(pWC->pMaskSet, iCur);
100578       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
100579         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
100580         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
100581         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
100582           if( nSkipEq ){
100583             /* Ignore the first nEq equality matches since the index
100584             ** has already accounted for these */
100585             nSkipEq--;
100586           }else{
100587             /* Assume each additional equality match reduces the result
100588             ** set size by a factor of 10 */
100589             nRow /= 10;
100590           }
100591         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
100592           if( nSkipRange ){
100593             /* Ignore the first nSkipRange range constraints since the index
100594             ** has already accounted for these */
100595             nSkipRange--;
100596           }else{
100597             /* Assume each additional range constraint reduces the result
100598             ** set size by a factor of 3.  Indexed range constraints reduce
100599             ** the search space by a larger factor: 4.  We make indexed range
100600             ** more selective intentionally because of the subjective 
100601             ** observation that indexed range constraints really are more
100602             ** selective in practice, on average. */
100603             nRow /= 3;
100604           }
100605         }else if( pTerm->eOperator!=WO_NOOP ){
100606           /* Any other expression lowers the output row count by half */
100607           nRow /= 2;
100608         }
100609       }
100610       if( nRow<2 ) nRow = 2;
100611     }
100612
100613
100614     WHERETRACE((
100615       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
100616       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
100617       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
100618       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
100619       notReady, log10N, nRow, cost, used
100620     ));
100621
100622     /* If this index is the best we have seen so far, then record this
100623     ** index and its cost in the pCost structure.
100624     */
100625     if( (!pIdx || wsFlags)
100626      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
100627     ){
100628       pCost->rCost = cost;
100629       pCost->used = used;
100630       pCost->plan.nRow = nRow;
100631       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
100632       pCost->plan.nEq = nEq;
100633       pCost->plan.u.pIdx = pIdx;
100634     }
100635
100636     /* If there was an INDEXED BY clause, then only that one index is
100637     ** considered. */
100638     if( pSrc->pIndex ) break;
100639
100640     /* Reset masks for the next index in the loop */
100641     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100642     eqTermMask = idxEqTermMask;
100643   }
100644
100645   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
100646   ** is set, then reverse the order that the index will be scanned
100647   ** in. This is used for application testing, to help find cases
100648   ** where application behaviour depends on the (undefined) order that
100649   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
100650   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
100651     pCost->plan.wsFlags |= WHERE_REVERSE;
100652   }
100653
100654   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
100655   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
100656   assert( pSrc->pIndex==0 
100657        || pCost->plan.u.pIdx==0 
100658        || pCost->plan.u.pIdx==pSrc->pIndex 
100659   );
100660
100661   WHERETRACE(("best index is: %s\n", 
100662     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
100663          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
100664   ));
100665   
100666   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100667   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
100668   pCost->plan.wsFlags |= eqTermMask;
100669 }
100670
100671 /*
100672 ** Find the query plan for accessing table pSrc->pTab. Write the
100673 ** best query plan and its cost into the WhereCost object supplied 
100674 ** as the last parameter. This function may calculate the cost of
100675 ** both real and virtual table scans.
100676 */
100677 static void bestIndex(
100678   Parse *pParse,              /* The parsing context */
100679   WhereClause *pWC,           /* The WHERE clause */
100680   struct SrcList_item *pSrc,  /* The FROM clause term to search */
100681   Bitmask notReady,           /* Mask of cursors not available for indexing */
100682   Bitmask notValid,           /* Cursors not available for any purpose */
100683   ExprList *pOrderBy,         /* The ORDER BY clause */
100684   WhereCost *pCost            /* Lowest cost query plan */
100685 ){
100686 #ifndef SQLITE_OMIT_VIRTUALTABLE
100687   if( IsVirtual(pSrc->pTab) ){
100688     sqlite3_index_info *p = 0;
100689     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
100690     if( p->needToFreeIdxStr ){
100691       sqlite3_free(p->idxStr);
100692     }
100693     sqlite3DbFree(pParse->db, p);
100694   }else
100695 #endif
100696   {
100697     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100698   }
100699 }
100700
100701 /*
100702 ** Disable a term in the WHERE clause.  Except, do not disable the term
100703 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
100704 ** or USING clause of that join.
100705 **
100706 ** Consider the term t2.z='ok' in the following queries:
100707 **
100708 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
100709 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
100710 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
100711 **
100712 ** The t2.z='ok' is disabled in the in (2) because it originates
100713 ** in the ON clause.  The term is disabled in (3) because it is not part
100714 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
100715 **
100716 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
100717 ** completely satisfied by indices.
100718 **
100719 ** Disabling a term causes that term to not be tested in the inner loop
100720 ** of the join.  Disabling is an optimization.  When terms are satisfied
100721 ** by indices, we disable them to prevent redundant tests in the inner
100722 ** loop.  We would get the correct results if nothing were ever disabled,
100723 ** but joins might run a little slower.  The trick is to disable as much
100724 ** as we can without disabling too much.  If we disabled in (1), we'd get
100725 ** the wrong answer.  See ticket #813.
100726 */
100727 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
100728   if( pTerm
100729       && (pTerm->wtFlags & TERM_CODED)==0
100730       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
100731   ){
100732     pTerm->wtFlags |= TERM_CODED;
100733     if( pTerm->iParent>=0 ){
100734       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
100735       if( (--pOther->nChild)==0 ){
100736         disableTerm(pLevel, pOther);
100737       }
100738     }
100739   }
100740 }
100741
100742 /*
100743 ** Code an OP_Affinity opcode to apply the column affinity string zAff
100744 ** to the n registers starting at base. 
100745 **
100746 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
100747 ** beginning and end of zAff are ignored.  If all entries in zAff are
100748 ** SQLITE_AFF_NONE, then no code gets generated.
100749 **
100750 ** This routine makes its own copy of zAff so that the caller is free
100751 ** to modify zAff after this routine returns.
100752 */
100753 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
100754   Vdbe *v = pParse->pVdbe;
100755   if( zAff==0 ){
100756     assert( pParse->db->mallocFailed );
100757     return;
100758   }
100759   assert( v!=0 );
100760
100761   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
100762   ** and end of the affinity string.
100763   */
100764   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
100765     n--;
100766     base++;
100767     zAff++;
100768   }
100769   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
100770     n--;
100771   }
100772
100773   /* Code the OP_Affinity opcode if there is anything left to do. */
100774   if( n>0 ){
100775     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
100776     sqlite3VdbeChangeP4(v, -1, zAff, n);
100777     sqlite3ExprCacheAffinityChange(pParse, base, n);
100778   }
100779 }
100780
100781
100782 /*
100783 ** Generate code for a single equality term of the WHERE clause.  An equality
100784 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
100785 ** coded.
100786 **
100787 ** The current value for the constraint is left in register iReg.
100788 **
100789 ** For a constraint of the form X=expr, the expression is evaluated and its
100790 ** result is left on the stack.  For constraints of the form X IN (...)
100791 ** this routine sets up a loop that will iterate over all values of X.
100792 */
100793 static int codeEqualityTerm(
100794   Parse *pParse,      /* The parsing context */
100795   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
100796   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
100797   int iTarget         /* Attempt to leave results in this register */
100798 ){
100799   Expr *pX = pTerm->pExpr;
100800   Vdbe *v = pParse->pVdbe;
100801   int iReg;                  /* Register holding results */
100802
100803   assert( iTarget>0 );
100804   if( pX->op==TK_EQ ){
100805     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
100806   }else if( pX->op==TK_ISNULL ){
100807     iReg = iTarget;
100808     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
100809 #ifndef SQLITE_OMIT_SUBQUERY
100810   }else{
100811     int eType;
100812     int iTab;
100813     struct InLoop *pIn;
100814
100815     assert( pX->op==TK_IN );
100816     iReg = iTarget;
100817     eType = sqlite3FindInIndex(pParse, pX, 0);
100818     iTab = pX->iTable;
100819     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
100820     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
100821     if( pLevel->u.in.nIn==0 ){
100822       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
100823     }
100824     pLevel->u.in.nIn++;
100825     pLevel->u.in.aInLoop =
100826        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
100827                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
100828     pIn = pLevel->u.in.aInLoop;
100829     if( pIn ){
100830       pIn += pLevel->u.in.nIn - 1;
100831       pIn->iCur = iTab;
100832       if( eType==IN_INDEX_ROWID ){
100833         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
100834       }else{
100835         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
100836       }
100837       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
100838     }else{
100839       pLevel->u.in.nIn = 0;
100840     }
100841 #endif
100842   }
100843   disableTerm(pLevel, pTerm);
100844   return iReg;
100845 }
100846
100847 /*
100848 ** Generate code that will evaluate all == and IN constraints for an
100849 ** index.
100850 **
100851 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
100852 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
100853 ** The index has as many as three equality constraints, but in this
100854 ** example, the third "c" value is an inequality.  So only two 
100855 ** constraints are coded.  This routine will generate code to evaluate
100856 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
100857 ** in consecutive registers and the index of the first register is returned.
100858 **
100859 ** In the example above nEq==2.  But this subroutine works for any value
100860 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
100861 ** The only thing it does is allocate the pLevel->iMem memory cell and
100862 ** compute the affinity string.
100863 **
100864 ** This routine always allocates at least one memory cell and returns
100865 ** the index of that memory cell. The code that
100866 ** calls this routine will use that memory cell to store the termination
100867 ** key value of the loop.  If one or more IN operators appear, then
100868 ** this routine allocates an additional nEq memory cells for internal
100869 ** use.
100870 **
100871 ** Before returning, *pzAff is set to point to a buffer containing a
100872 ** copy of the column affinity string of the index allocated using
100873 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
100874 ** with equality constraints that use NONE affinity are set to
100875 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
100876 **
100877 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
100878 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
100879 **
100880 ** In the example above, the index on t1(a) has TEXT affinity. But since
100881 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
100882 ** no conversion should be attempted before using a t2.b value as part of
100883 ** a key to search the index. Hence the first byte in the returned affinity
100884 ** string in this example would be set to SQLITE_AFF_NONE.
100885 */
100886 static int codeAllEqualityTerms(
100887   Parse *pParse,        /* Parsing context */
100888   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
100889   WhereClause *pWC,     /* The WHERE clause */
100890   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
100891   int nExtraReg,        /* Number of extra registers to allocate */
100892   char **pzAff          /* OUT: Set to point to affinity string */
100893 ){
100894   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
100895   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
100896   Index *pIdx;                  /* The index being used for this loop */
100897   int iCur = pLevel->iTabCur;   /* The cursor of the table */
100898   WhereTerm *pTerm;             /* A single constraint term */
100899   int j;                        /* Loop counter */
100900   int regBase;                  /* Base register */
100901   int nReg;                     /* Number of registers to allocate */
100902   char *zAff;                   /* Affinity string to return */
100903
100904   /* This module is only called on query plans that use an index. */
100905   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
100906   pIdx = pLevel->plan.u.pIdx;
100907
100908   /* Figure out how many memory cells we will need then allocate them.
100909   */
100910   regBase = pParse->nMem + 1;
100911   nReg = pLevel->plan.nEq + nExtraReg;
100912   pParse->nMem += nReg;
100913
100914   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
100915   if( !zAff ){
100916     pParse->db->mallocFailed = 1;
100917   }
100918
100919   /* Evaluate the equality constraints
100920   */
100921   assert( pIdx->nColumn>=nEq );
100922   for(j=0; j<nEq; j++){
100923     int r1;
100924     int k = pIdx->aiColumn[j];
100925     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
100926     if( NEVER(pTerm==0) ) break;
100927     /* The following true for indices with redundant columns. 
100928     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
100929     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
100930     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
100931     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
100932     if( r1!=regBase+j ){
100933       if( nReg==1 ){
100934         sqlite3ReleaseTempReg(pParse, regBase);
100935         regBase = r1;
100936       }else{
100937         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
100938       }
100939     }
100940     testcase( pTerm->eOperator & WO_ISNULL );
100941     testcase( pTerm->eOperator & WO_IN );
100942     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
100943       Expr *pRight = pTerm->pExpr->pRight;
100944       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
100945       if( zAff ){
100946         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
100947           zAff[j] = SQLITE_AFF_NONE;
100948         }
100949         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
100950           zAff[j] = SQLITE_AFF_NONE;
100951         }
100952       }
100953     }
100954   }
100955   *pzAff = zAff;
100956   return regBase;
100957 }
100958
100959 #ifndef SQLITE_OMIT_EXPLAIN
100960 /*
100961 ** This routine is a helper for explainIndexRange() below
100962 **
100963 ** pStr holds the text of an expression that we are building up one term
100964 ** at a time.  This routine adds a new term to the end of the expression.
100965 ** Terms are separated by AND so add the "AND" text for second and subsequent
100966 ** terms only.
100967 */
100968 static void explainAppendTerm(
100969   StrAccum *pStr,             /* The text expression being built */
100970   int iTerm,                  /* Index of this term.  First is zero */
100971   const char *zColumn,        /* Name of the column */
100972   const char *zOp             /* Name of the operator */
100973 ){
100974   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
100975   sqlite3StrAccumAppend(pStr, zColumn, -1);
100976   sqlite3StrAccumAppend(pStr, zOp, 1);
100977   sqlite3StrAccumAppend(pStr, "?", 1);
100978 }
100979
100980 /*
100981 ** Argument pLevel describes a strategy for scanning table pTab. This 
100982 ** function returns a pointer to a string buffer containing a description
100983 ** of the subset of table rows scanned by the strategy in the form of an
100984 ** SQL expression. Or, if all rows are scanned, NULL is returned.
100985 **
100986 ** For example, if the query:
100987 **
100988 **   SELECT * FROM t1 WHERE a=1 AND b>2;
100989 **
100990 ** is run and there is an index on (a, b), then this function returns a
100991 ** string similar to:
100992 **
100993 **   "a=? AND b>?"
100994 **
100995 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
100996 ** It is the responsibility of the caller to free the buffer when it is
100997 ** no longer required.
100998 */
100999 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
101000   WherePlan *pPlan = &pLevel->plan;
101001   Index *pIndex = pPlan->u.pIdx;
101002   int nEq = pPlan->nEq;
101003   int i, j;
101004   Column *aCol = pTab->aCol;
101005   int *aiColumn = pIndex->aiColumn;
101006   StrAccum txt;
101007
101008   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
101009     return 0;
101010   }
101011   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101012   txt.db = db;
101013   sqlite3StrAccumAppend(&txt, " (", 2);
101014   for(i=0; i<nEq; i++){
101015     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101016   }
101017
101018   j = i;
101019   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101020     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101021   }
101022   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101023     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101024   }
101025   sqlite3StrAccumAppend(&txt, ")", 1);
101026   return sqlite3StrAccumFinish(&txt);
101027 }
101028
101029 /*
101030 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101031 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101032 ** record is added to the output to describe the table scan strategy in 
101033 ** pLevel.
101034 */
101035 static void explainOneScan(
101036   Parse *pParse,                  /* Parse context */
101037   SrcList *pTabList,              /* Table list this loop refers to */
101038   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
101039   int iLevel,                     /* Value for "level" column of output */
101040   int iFrom,                      /* Value for "from" column of output */
101041   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
101042 ){
101043   if( pParse->explain==2 ){
101044     u32 flags = pLevel->plan.wsFlags;
101045     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101046     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
101047     sqlite3 *db = pParse->db;     /* Database handle */
101048     char *zMsg;                   /* Text to add to EQP output */
101049     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
101050     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
101051     int isSearch;                 /* True for a SEARCH. False for SCAN. */
101052
101053     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101054
101055     isSearch = (pLevel->plan.nEq>0)
101056              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101057              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101058
101059     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101060     if( pItem->pSelect ){
101061       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101062     }else{
101063       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101064     }
101065
101066     if( pItem->zAlias ){
101067       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101068     }
101069     if( (flags & WHERE_INDEXED)!=0 ){
101070       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101071       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
101072           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101073           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101074           ((flags & WHERE_TEMP_INDEX)?"":" "),
101075           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101076           zWhere
101077       );
101078       sqlite3DbFree(db, zWhere);
101079     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101080       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101081
101082       if( flags&WHERE_ROWID_EQ ){
101083         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101084       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101085         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101086       }else if( flags&WHERE_BTM_LIMIT ){
101087         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101088       }else if( flags&WHERE_TOP_LIMIT ){
101089         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101090       }
101091     }
101092 #ifndef SQLITE_OMIT_VIRTUALTABLE
101093     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101094       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101095       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101096                   pVtabIdx->idxNum, pVtabIdx->idxStr);
101097     }
101098 #endif
101099     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101100       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101101       nRow = 1;
101102     }else{
101103       nRow = (sqlite3_int64)pLevel->plan.nRow;
101104     }
101105     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101106     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101107   }
101108 }
101109 #else
101110 # define explainOneScan(u,v,w,x,y,z)
101111 #endif /* SQLITE_OMIT_EXPLAIN */
101112
101113
101114 /*
101115 ** Generate code for the start of the iLevel-th loop in the WHERE clause
101116 ** implementation described by pWInfo.
101117 */
101118 static Bitmask codeOneLoopStart(
101119   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
101120   int iLevel,          /* Which level of pWInfo->a[] should be coded */
101121   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
101122   Bitmask notReady     /* Which tables are currently available */
101123 ){
101124   int j, k;            /* Loop counters */
101125   int iCur;            /* The VDBE cursor for the table */
101126   int addrNxt;         /* Where to jump to continue with the next IN case */
101127   int omitTable;       /* True if we use the index only */
101128   int bRev;            /* True if we need to scan in reverse order */
101129   WhereLevel *pLevel;  /* The where level to be coded */
101130   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
101131   WhereTerm *pTerm;               /* A WHERE clause term */
101132   Parse *pParse;                  /* Parsing context */
101133   Vdbe *v;                        /* The prepared stmt under constructions */
101134   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
101135   int addrBrk;                    /* Jump here to break out of the loop */
101136   int addrCont;                   /* Jump here to continue with next cycle */
101137   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
101138   int iReleaseReg = 0;      /* Temp register to free before returning */
101139
101140   pParse = pWInfo->pParse;
101141   v = pParse->pVdbe;
101142   pWC = pWInfo->pWC;
101143   pLevel = &pWInfo->a[iLevel];
101144   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101145   iCur = pTabItem->iCursor;
101146   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101147   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
101148            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101149
101150   /* Create labels for the "break" and "continue" instructions
101151   ** for the current loop.  Jump to addrBrk to break out of a loop.
101152   ** Jump to cont to go immediately to the next iteration of the
101153   ** loop.
101154   **
101155   ** When there is an IN operator, we also have a "addrNxt" label that
101156   ** means to continue with the next IN value combination.  When
101157   ** there are no IN operators in the constraints, the "addrNxt" label
101158   ** is the same as "addrBrk".
101159   */
101160   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101161   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101162
101163   /* If this is the right table of a LEFT OUTER JOIN, allocate and
101164   ** initialize a memory cell that records if this table matches any
101165   ** row of the left table of the join.
101166   */
101167   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101168     pLevel->iLeftJoin = ++pParse->nMem;
101169     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101170     VdbeComment((v, "init LEFT JOIN no-match flag"));
101171   }
101172
101173 #ifndef SQLITE_OMIT_VIRTUALTABLE
101174   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101175     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
101176     **          to access the data.
101177     */
101178     int iReg;   /* P3 Value for OP_VFilter */
101179     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101180     int nConstraint = pVtabIdx->nConstraint;
101181     struct sqlite3_index_constraint_usage *aUsage =
101182                                                 pVtabIdx->aConstraintUsage;
101183     const struct sqlite3_index_constraint *aConstraint =
101184                                                 pVtabIdx->aConstraint;
101185
101186     sqlite3ExprCachePush(pParse);
101187     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101188     for(j=1; j<=nConstraint; j++){
101189       for(k=0; k<nConstraint; k++){
101190         if( aUsage[k].argvIndex==j ){
101191           int iTerm = aConstraint[k].iTermOffset;
101192           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101193           break;
101194         }
101195       }
101196       if( k==nConstraint ) break;
101197     }
101198     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101199     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101200     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
101201                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
101202     pVtabIdx->needToFreeIdxStr = 0;
101203     for(j=0; j<nConstraint; j++){
101204       if( aUsage[j].omit ){
101205         int iTerm = aConstraint[j].iTermOffset;
101206         disableTerm(pLevel, &pWC->a[iTerm]);
101207       }
101208     }
101209     pLevel->op = OP_VNext;
101210     pLevel->p1 = iCur;
101211     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101212     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
101213     sqlite3ExprCachePop(pParse, 1);
101214   }else
101215 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101216
101217   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
101218     /* Case 1:  We can directly reference a single row using an
101219     **          equality comparison against the ROWID field.  Or
101220     **          we reference multiple rows using a "rowid IN (...)"
101221     **          construct.
101222     */
101223     iReleaseReg = sqlite3GetTempReg(pParse);
101224     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
101225     assert( pTerm!=0 );
101226     assert( pTerm->pExpr!=0 );
101227     assert( pTerm->leftCursor==iCur );
101228     assert( omitTable==0 );
101229     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101230     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
101231     addrNxt = pLevel->addrNxt;
101232     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
101233     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
101234     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101235     VdbeComment((v, "pk"));
101236     pLevel->op = OP_Noop;
101237   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
101238     /* Case 2:  We have an inequality comparison against the ROWID field.
101239     */
101240     int testOp = OP_Noop;
101241     int start;
101242     int memEndValue = 0;
101243     WhereTerm *pStart, *pEnd;
101244
101245     assert( omitTable==0 );
101246     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
101247     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
101248     if( bRev ){
101249       pTerm = pStart;
101250       pStart = pEnd;
101251       pEnd = pTerm;
101252     }
101253     if( pStart ){
101254       Expr *pX;             /* The expression that defines the start bound */
101255       int r1, rTemp;        /* Registers for holding the start boundary */
101256
101257       /* The following constant maps TK_xx codes into corresponding 
101258       ** seek opcodes.  It depends on a particular ordering of TK_xx
101259       */
101260       const u8 aMoveOp[] = {
101261            /* TK_GT */  OP_SeekGt,
101262            /* TK_LE */  OP_SeekLe,
101263            /* TK_LT */  OP_SeekLt,
101264            /* TK_GE */  OP_SeekGe
101265       };
101266       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
101267       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
101268       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
101269
101270       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101271       pX = pStart->pExpr;
101272       assert( pX!=0 );
101273       assert( pStart->leftCursor==iCur );
101274       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
101275       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
101276       VdbeComment((v, "pk"));
101277       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
101278       sqlite3ReleaseTempReg(pParse, rTemp);
101279       disableTerm(pLevel, pStart);
101280     }else{
101281       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
101282     }
101283     if( pEnd ){
101284       Expr *pX;
101285       pX = pEnd->pExpr;
101286       assert( pX!=0 );
101287       assert( pEnd->leftCursor==iCur );
101288       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101289       memEndValue = ++pParse->nMem;
101290       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
101291       if( pX->op==TK_LT || pX->op==TK_GT ){
101292         testOp = bRev ? OP_Le : OP_Ge;
101293       }else{
101294         testOp = bRev ? OP_Lt : OP_Gt;
101295       }
101296       disableTerm(pLevel, pEnd);
101297     }
101298     start = sqlite3VdbeCurrentAddr(v);
101299     pLevel->op = bRev ? OP_Prev : OP_Next;
101300     pLevel->p1 = iCur;
101301     pLevel->p2 = start;
101302     if( pStart==0 && pEnd==0 ){
101303       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101304     }else{
101305       assert( pLevel->p5==0 );
101306     }
101307     if( testOp!=OP_Noop ){
101308       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101309       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
101310       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101311       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
101312       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
101313     }
101314   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
101315     /* Case 3: A scan using an index.
101316     **
101317     **         The WHERE clause may contain zero or more equality 
101318     **         terms ("==" or "IN" operators) that refer to the N
101319     **         left-most columns of the index. It may also contain
101320     **         inequality constraints (>, <, >= or <=) on the indexed
101321     **         column that immediately follows the N equalities. Only 
101322     **         the right-most column can be an inequality - the rest must
101323     **         use the "==" and "IN" operators. For example, if the 
101324     **         index is on (x,y,z), then the following clauses are all 
101325     **         optimized:
101326     **
101327     **            x=5
101328     **            x=5 AND y=10
101329     **            x=5 AND y<10
101330     **            x=5 AND y>5 AND y<10
101331     **            x=5 AND y=5 AND z<=10
101332     **
101333     **         The z<10 term of the following cannot be used, only
101334     **         the x=5 term:
101335     **
101336     **            x=5 AND z<10
101337     **
101338     **         N may be zero if there are inequality constraints.
101339     **         If there are no inequality constraints, then N is at
101340     **         least one.
101341     **
101342     **         This case is also used when there are no WHERE clause
101343     **         constraints but an index is selected anyway, in order
101344     **         to force the output order to conform to an ORDER BY.
101345     */  
101346     static const u8 aStartOp[] = {
101347       0,
101348       0,
101349       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
101350       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
101351       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
101352       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
101353       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
101354       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
101355     };
101356     static const u8 aEndOp[] = {
101357       OP_Noop,             /* 0: (!end_constraints) */
101358       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
101359       OP_IdxLT             /* 2: (end_constraints && bRev) */
101360     };
101361     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
101362     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
101363     int regBase;                 /* Base register holding constraint values */
101364     int r1;                      /* Temp register */
101365     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
101366     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
101367     int startEq;                 /* True if range start uses ==, >= or <= */
101368     int endEq;                   /* True if range end uses ==, >= or <= */
101369     int start_constraints;       /* Start of range is constrained */
101370     int nConstraint;             /* Number of constraint terms */
101371     Index *pIdx;                 /* The index we will be using */
101372     int iIdxCur;                 /* The VDBE cursor for the index */
101373     int nExtraReg = 0;           /* Number of extra registers needed */
101374     int op;                      /* Instruction opcode */
101375     char *zStartAff;             /* Affinity for start of range constraint */
101376     char *zEndAff;               /* Affinity for end of range constraint */
101377
101378     pIdx = pLevel->plan.u.pIdx;
101379     iIdxCur = pLevel->iIdxCur;
101380     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
101381
101382     /* If this loop satisfies a sort order (pOrderBy) request that 
101383     ** was passed to this function to implement a "SELECT min(x) ..." 
101384     ** query, then the caller will only allow the loop to run for
101385     ** a single iteration. This means that the first row returned
101386     ** should not have a NULL value stored in 'x'. If column 'x' is
101387     ** the first one after the nEq equality constraints in the index,
101388     ** this requires some special handling.
101389     */
101390     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
101391      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
101392      && (pIdx->nColumn>nEq)
101393     ){
101394       /* assert( pOrderBy->nExpr==1 ); */
101395       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
101396       isMinQuery = 1;
101397       nExtraReg = 1;
101398     }
101399
101400     /* Find any inequality constraint terms for the start and end 
101401     ** of the range. 
101402     */
101403     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
101404       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
101405       nExtraReg = 1;
101406     }
101407     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
101408       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
101409       nExtraReg = 1;
101410     }
101411
101412     /* Generate code to evaluate all constraint terms using == or IN
101413     ** and store the values of those terms in an array of registers
101414     ** starting at regBase.
101415     */
101416     regBase = codeAllEqualityTerms(
101417         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
101418     );
101419     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
101420     addrNxt = pLevel->addrNxt;
101421
101422     /* If we are doing a reverse order scan on an ascending index, or
101423     ** a forward order scan on a descending index, interchange the 
101424     ** start and end terms (pRangeStart and pRangeEnd).
101425     */
101426     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
101427       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
101428     }
101429
101430     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
101431     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
101432     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
101433     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
101434     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
101435     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
101436     start_constraints = pRangeStart || nEq>0;
101437
101438     /* Seek the index cursor to the start of the range. */
101439     nConstraint = nEq;
101440     if( pRangeStart ){
101441       Expr *pRight = pRangeStart->pExpr->pRight;
101442       sqlite3ExprCode(pParse, pRight, regBase+nEq);
101443       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
101444         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101445       }
101446       if( zStartAff ){
101447         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
101448           /* Since the comparison is to be performed with no conversions
101449           ** applied to the operands, set the affinity to apply to pRight to 
101450           ** SQLITE_AFF_NONE.  */
101451           zStartAff[nEq] = SQLITE_AFF_NONE;
101452         }
101453         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
101454           zStartAff[nEq] = SQLITE_AFF_NONE;
101455         }
101456       }  
101457       nConstraint++;
101458       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101459     }else if( isMinQuery ){
101460       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
101461       nConstraint++;
101462       startEq = 0;
101463       start_constraints = 1;
101464     }
101465     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
101466     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
101467     assert( op!=0 );
101468     testcase( op==OP_Rewind );
101469     testcase( op==OP_Last );
101470     testcase( op==OP_SeekGt );
101471     testcase( op==OP_SeekGe );
101472     testcase( op==OP_SeekLe );
101473     testcase( op==OP_SeekLt );
101474     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101475
101476     /* Load the value for the inequality constraint at the end of the
101477     ** range (if any).
101478     */
101479     nConstraint = nEq;
101480     if( pRangeEnd ){
101481       Expr *pRight = pRangeEnd->pExpr->pRight;
101482       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
101483       sqlite3ExprCode(pParse, pRight, regBase+nEq);
101484       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
101485         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101486       }
101487       if( zEndAff ){
101488         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
101489           /* Since the comparison is to be performed with no conversions
101490           ** applied to the operands, set the affinity to apply to pRight to 
101491           ** SQLITE_AFF_NONE.  */
101492           zEndAff[nEq] = SQLITE_AFF_NONE;
101493         }
101494         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
101495           zEndAff[nEq] = SQLITE_AFF_NONE;
101496         }
101497       }  
101498       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
101499       nConstraint++;
101500       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101501     }
101502     sqlite3DbFree(pParse->db, zStartAff);
101503     sqlite3DbFree(pParse->db, zEndAff);
101504
101505     /* Top of the loop body */
101506     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101507
101508     /* Check if the index cursor is past the end of the range. */
101509     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
101510     testcase( op==OP_Noop );
101511     testcase( op==OP_IdxGE );
101512     testcase( op==OP_IdxLT );
101513     if( op!=OP_Noop ){
101514       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101515       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
101516     }
101517
101518     /* If there are inequality constraints, check that the value
101519     ** of the table column that the inequality contrains is not NULL.
101520     ** If it is, jump to the next iteration of the loop.
101521     */
101522     r1 = sqlite3GetTempReg(pParse);
101523     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
101524     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
101525     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
101526       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
101527       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
101528     }
101529     sqlite3ReleaseTempReg(pParse, r1);
101530
101531     /* Seek the table cursor, if required */
101532     disableTerm(pLevel, pRangeStart);
101533     disableTerm(pLevel, pRangeEnd);
101534     if( !omitTable ){
101535       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101536       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
101537       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101538       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
101539     }
101540
101541     /* Record the instruction used to terminate the loop. Disable 
101542     ** WHERE clause terms made redundant by the index range scan.
101543     */
101544     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
101545       pLevel->op = OP_Noop;
101546     }else if( bRev ){
101547       pLevel->op = OP_Prev;
101548     }else{
101549       pLevel->op = OP_Next;
101550     }
101551     pLevel->p1 = iIdxCur;
101552   }else
101553
101554 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
101555   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
101556     /* Case 4:  Two or more separately indexed terms connected by OR
101557     **
101558     ** Example:
101559     **
101560     **   CREATE TABLE t1(a,b,c,d);
101561     **   CREATE INDEX i1 ON t1(a);
101562     **   CREATE INDEX i2 ON t1(b);
101563     **   CREATE INDEX i3 ON t1(c);
101564     **
101565     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
101566     **
101567     ** In the example, there are three indexed terms connected by OR.
101568     ** The top of the loop looks like this:
101569     **
101570     **          Null       1                # Zero the rowset in reg 1
101571     **
101572     ** Then, for each indexed term, the following. The arguments to
101573     ** RowSetTest are such that the rowid of the current row is inserted
101574     ** into the RowSet. If it is already present, control skips the
101575     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
101576     **
101577     **        sqlite3WhereBegin(<term>)
101578     **          RowSetTest                  # Insert rowid into rowset
101579     **          Gosub      2 A
101580     **        sqlite3WhereEnd()
101581     **
101582     ** Following the above, code to terminate the loop. Label A, the target
101583     ** of the Gosub above, jumps to the instruction right after the Goto.
101584     **
101585     **          Null       1                # Zero the rowset in reg 1
101586     **          Goto       B                # The loop is finished.
101587     **
101588     **       A: <loop body>                 # Return data, whatever.
101589     **
101590     **          Return     2                # Jump back to the Gosub
101591     **
101592     **       B: <after the loop>
101593     **
101594     */
101595     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
101596     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
101597
101598     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
101599     int regRowset = 0;                        /* Register for RowSet object */
101600     int regRowid = 0;                         /* Register holding rowid */
101601     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
101602     int iRetInit;                             /* Address of regReturn init */
101603     int untestedTerms = 0;             /* Some terms not completely tested */
101604     int ii;
101605    
101606     pTerm = pLevel->plan.u.pTerm;
101607     assert( pTerm!=0 );
101608     assert( pTerm->eOperator==WO_OR );
101609     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
101610     pOrWc = &pTerm->u.pOrInfo->wc;
101611     pLevel->op = OP_Return;
101612     pLevel->p1 = regReturn;
101613
101614     /* Set up a new SrcList ni pOrTab containing the table being scanned
101615     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
101616     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
101617     */
101618     if( pWInfo->nLevel>1 ){
101619       int nNotReady;                 /* The number of notReady tables */
101620       struct SrcList_item *origSrc;     /* Original list of tables */
101621       nNotReady = pWInfo->nLevel - iLevel - 1;
101622       pOrTab = sqlite3StackAllocRaw(pParse->db,
101623                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
101624       if( pOrTab==0 ) return notReady;
101625       pOrTab->nAlloc = (i16)(nNotReady + 1);
101626       pOrTab->nSrc = pOrTab->nAlloc;
101627       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
101628       origSrc = pWInfo->pTabList->a;
101629       for(k=1; k<=nNotReady; k++){
101630         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
101631       }
101632     }else{
101633       pOrTab = pWInfo->pTabList;
101634     }
101635
101636     /* Initialize the rowset register to contain NULL. An SQL NULL is 
101637     ** equivalent to an empty rowset.
101638     **
101639     ** Also initialize regReturn to contain the address of the instruction 
101640     ** immediately following the OP_Return at the bottom of the loop. This
101641     ** is required in a few obscure LEFT JOIN cases where control jumps
101642     ** over the top of the loop into the body of it. In this case the 
101643     ** correct response for the end-of-loop code (the OP_Return) is to 
101644     ** fall through to the next instruction, just as an OP_Next does if
101645     ** called on an uninitialized cursor.
101646     */
101647     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101648       regRowset = ++pParse->nMem;
101649       regRowid = ++pParse->nMem;
101650       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
101651     }
101652     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
101653
101654     for(ii=0; ii<pOrWc->nTerm; ii++){
101655       WhereTerm *pOrTerm = &pOrWc->a[ii];
101656       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
101657         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
101658         /* Loop through table entries that match term pOrTerm. */
101659         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
101660                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
101661                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
101662         if( pSubWInfo ){
101663           explainOneScan(
101664               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
101665           );
101666           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101667             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
101668             int r;
101669             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
101670                                          regRowid);
101671             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
101672                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
101673           }
101674           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
101675
101676           /* The pSubWInfo->untestedTerms flag means that this OR term
101677           ** contained one or more AND term from a notReady table.  The
101678           ** terms from the notReady table could not be tested and will
101679           ** need to be tested later.
101680           */
101681           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
101682
101683           /* Finish the loop through table entries that match term pOrTerm. */
101684           sqlite3WhereEnd(pSubWInfo);
101685         }
101686       }
101687     }
101688     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
101689     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
101690     sqlite3VdbeResolveLabel(v, iLoopBody);
101691
101692     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
101693     if( !untestedTerms ) disableTerm(pLevel, pTerm);
101694   }else
101695 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101696
101697   {
101698     /* Case 5:  There is no usable index.  We must do a complete
101699     **          scan of the entire table.
101700     */
101701     static const u8 aStep[] = { OP_Next, OP_Prev };
101702     static const u8 aStart[] = { OP_Rewind, OP_Last };
101703     assert( bRev==0 || bRev==1 );
101704     assert( omitTable==0 );
101705     pLevel->op = aStep[bRev];
101706     pLevel->p1 = iCur;
101707     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
101708     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101709   }
101710   notReady &= ~getMask(pWC->pMaskSet, iCur);
101711
101712   /* Insert code to test every subexpression that can be completely
101713   ** computed using the current set of tables.
101714   **
101715   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
101716   ** the use of indices become tests that are evaluated against each row of
101717   ** the relevant input tables.
101718   */
101719   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
101720     Expr *pE;
101721     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
101722     testcase( pTerm->wtFlags & TERM_CODED );
101723     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101724     if( (pTerm->prereqAll & notReady)!=0 ){
101725       testcase( pWInfo->untestedTerms==0
101726                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
101727       pWInfo->untestedTerms = 1;
101728       continue;
101729     }
101730     pE = pTerm->pExpr;
101731     assert( pE!=0 );
101732     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
101733       continue;
101734     }
101735     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
101736     pTerm->wtFlags |= TERM_CODED;
101737   }
101738
101739   /* For a LEFT OUTER JOIN, generate code that will record the fact that
101740   ** at least one row of the right table has matched the left table.  
101741   */
101742   if( pLevel->iLeftJoin ){
101743     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
101744     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
101745     VdbeComment((v, "record LEFT JOIN hit"));
101746     sqlite3ExprCacheClear(pParse);
101747     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
101748       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
101749       testcase( pTerm->wtFlags & TERM_CODED );
101750       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
101751       if( (pTerm->prereqAll & notReady)!=0 ){
101752         assert( pWInfo->untestedTerms );
101753         continue;
101754       }
101755       assert( pTerm->pExpr );
101756       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
101757       pTerm->wtFlags |= TERM_CODED;
101758     }
101759   }
101760   sqlite3ReleaseTempReg(pParse, iReleaseReg);
101761
101762   return notReady;
101763 }
101764
101765 #if defined(SQLITE_TEST)
101766 /*
101767 ** The following variable holds a text description of query plan generated
101768 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
101769 ** overwrites the previous.  This information is used for testing and
101770 ** analysis only.
101771 */
101772 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
101773 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
101774
101775 #endif /* SQLITE_TEST */
101776
101777
101778 /*
101779 ** Free a WhereInfo structure
101780 */
101781 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
101782   if( ALWAYS(pWInfo) ){
101783     int i;
101784     for(i=0; i<pWInfo->nLevel; i++){
101785       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
101786       if( pInfo ){
101787         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
101788         if( pInfo->needToFreeIdxStr ){
101789           sqlite3_free(pInfo->idxStr);
101790         }
101791         sqlite3DbFree(db, pInfo);
101792       }
101793       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
101794         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
101795         if( pIdx ){
101796           sqlite3DbFree(db, pIdx->zColAff);
101797           sqlite3DbFree(db, pIdx);
101798         }
101799       }
101800     }
101801     whereClauseClear(pWInfo->pWC);
101802     sqlite3DbFree(db, pWInfo);
101803   }
101804 }
101805
101806
101807 /*
101808 ** Generate the beginning of the loop used for WHERE clause processing.
101809 ** The return value is a pointer to an opaque structure that contains
101810 ** information needed to terminate the loop.  Later, the calling routine
101811 ** should invoke sqlite3WhereEnd() with the return value of this function
101812 ** in order to complete the WHERE clause processing.
101813 **
101814 ** If an error occurs, this routine returns NULL.
101815 **
101816 ** The basic idea is to do a nested loop, one loop for each table in
101817 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
101818 ** same as a SELECT with only a single table in the FROM clause.)  For
101819 ** example, if the SQL is this:
101820 **
101821 **       SELECT * FROM t1, t2, t3 WHERE ...;
101822 **
101823 ** Then the code generated is conceptually like the following:
101824 **
101825 **      foreach row1 in t1 do       \    Code generated
101826 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
101827 **          foreach row3 in t3 do   /
101828 **            ...
101829 **          end                     \    Code generated
101830 **        end                        |-- by sqlite3WhereEnd()
101831 **      end                         /
101832 **
101833 ** Note that the loops might not be nested in the order in which they
101834 ** appear in the FROM clause if a different order is better able to make
101835 ** use of indices.  Note also that when the IN operator appears in
101836 ** the WHERE clause, it might result in additional nested loops for
101837 ** scanning through all values on the right-hand side of the IN.
101838 **
101839 ** There are Btree cursors associated with each table.  t1 uses cursor
101840 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
101841 ** And so forth.  This routine generates code to open those VDBE cursors
101842 ** and sqlite3WhereEnd() generates the code to close them.
101843 **
101844 ** The code that sqlite3WhereBegin() generates leaves the cursors named
101845 ** in pTabList pointing at their appropriate entries.  The [...] code
101846 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
101847 ** data from the various tables of the loop.
101848 **
101849 ** If the WHERE clause is empty, the foreach loops must each scan their
101850 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
101851 ** the tables have indices and there are terms in the WHERE clause that
101852 ** refer to those indices, a complete table scan can be avoided and the
101853 ** code will run much faster.  Most of the work of this routine is checking
101854 ** to see if there are indices that can be used to speed up the loop.
101855 **
101856 ** Terms of the WHERE clause are also used to limit which rows actually
101857 ** make it to the "..." in the middle of the loop.  After each "foreach",
101858 ** terms of the WHERE clause that use only terms in that loop and outer
101859 ** loops are evaluated and if false a jump is made around all subsequent
101860 ** inner loops (or around the "..." if the test occurs within the inner-
101861 ** most loop)
101862 **
101863 ** OUTER JOINS
101864 **
101865 ** An outer join of tables t1 and t2 is conceptally coded as follows:
101866 **
101867 **    foreach row1 in t1 do
101868 **      flag = 0
101869 **      foreach row2 in t2 do
101870 **        start:
101871 **          ...
101872 **          flag = 1
101873 **      end
101874 **      if flag==0 then
101875 **        move the row2 cursor to a null row
101876 **        goto start
101877 **      fi
101878 **    end
101879 **
101880 ** ORDER BY CLAUSE PROCESSING
101881 **
101882 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
101883 ** if there is one.  If there is no ORDER BY clause or if this routine
101884 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
101885 **
101886 ** If an index can be used so that the natural output order of the table
101887 ** scan is correct for the ORDER BY clause, then that index is used and
101888 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
101889 ** unnecessary sort of the result set if an index appropriate for the
101890 ** ORDER BY clause already exists.
101891 **
101892 ** If the where clause loops cannot be arranged to provide the correct
101893 ** output order, then the *ppOrderBy is unchanged.
101894 */
101895 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
101896   Parse *pParse,        /* The parser context */
101897   SrcList *pTabList,    /* A list of all tables to be scanned */
101898   Expr *pWhere,         /* The WHERE clause */
101899   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
101900   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
101901 ){
101902   int i;                     /* Loop counter */
101903   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
101904   int nTabList;              /* Number of elements in pTabList */
101905   WhereInfo *pWInfo;         /* Will become the return value of this function */
101906   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
101907   Bitmask notReady;          /* Cursors that are not yet positioned */
101908   WhereMaskSet *pMaskSet;    /* The expression mask set */
101909   WhereClause *pWC;               /* Decomposition of the WHERE clause */
101910   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
101911   WhereLevel *pLevel;             /* A single level in the pWInfo list */
101912   int iFrom;                      /* First unused FROM clause element */
101913   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
101914   sqlite3 *db;               /* Database connection */
101915
101916   /* The number of tables in the FROM clause is limited by the number of
101917   ** bits in a Bitmask 
101918   */
101919   testcase( pTabList->nSrc==BMS );
101920   if( pTabList->nSrc>BMS ){
101921     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
101922     return 0;
101923   }
101924
101925   /* This function normally generates a nested loop for all tables in 
101926   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
101927   ** only generate code for the first table in pTabList and assume that
101928   ** any cursors associated with subsequent tables are uninitialized.
101929   */
101930   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
101931
101932   /* Allocate and initialize the WhereInfo structure that will become the
101933   ** return value. A single allocation is used to store the WhereInfo
101934   ** struct, the contents of WhereInfo.a[], the WhereClause structure
101935   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
101936   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
101937   ** some architectures. Hence the ROUND8() below.
101938   */
101939   db = pParse->db;
101940   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
101941   pWInfo = sqlite3DbMallocZero(db, 
101942       nByteWInfo + 
101943       sizeof(WhereClause) +
101944       sizeof(WhereMaskSet)
101945   );
101946   if( db->mallocFailed ){
101947     sqlite3DbFree(db, pWInfo);
101948     pWInfo = 0;
101949     goto whereBeginError;
101950   }
101951   pWInfo->nLevel = nTabList;
101952   pWInfo->pParse = pParse;
101953   pWInfo->pTabList = pTabList;
101954   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
101955   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
101956   pWInfo->wctrlFlags = wctrlFlags;
101957   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
101958   pMaskSet = (WhereMaskSet*)&pWC[1];
101959
101960   /* Split the WHERE clause into separate subexpressions where each
101961   ** subexpression is separated by an AND operator.
101962   */
101963   initMaskSet(pMaskSet);
101964   whereClauseInit(pWC, pParse, pMaskSet);
101965   sqlite3ExprCodeConstants(pParse, pWhere);
101966   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
101967     
101968   /* Special case: a WHERE clause that is constant.  Evaluate the
101969   ** expression and either jump over all of the code or fall thru.
101970   */
101971   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
101972     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
101973     pWhere = 0;
101974   }
101975
101976   /* Assign a bit from the bitmask to every term in the FROM clause.
101977   **
101978   ** When assigning bitmask values to FROM clause cursors, it must be
101979   ** the case that if X is the bitmask for the N-th FROM clause term then
101980   ** the bitmask for all FROM clause terms to the left of the N-th term
101981   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
101982   ** its Expr.iRightJoinTable value to find the bitmask of the right table
101983   ** of the join.  Subtracting one from the right table bitmask gives a
101984   ** bitmask for all tables to the left of the join.  Knowing the bitmask
101985   ** for all tables to the left of a left join is important.  Ticket #3015.
101986   **
101987   ** Configure the WhereClause.vmask variable so that bits that correspond
101988   ** to virtual table cursors are set. This is used to selectively disable 
101989   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
101990   ** with virtual tables.
101991   **
101992   ** Note that bitmasks are created for all pTabList->nSrc tables in
101993   ** pTabList, not just the first nTabList tables.  nTabList is normally
101994   ** equal to pTabList->nSrc but might be shortened to 1 if the
101995   ** WHERE_ONETABLE_ONLY flag is set.
101996   */
101997   assert( pWC->vmask==0 && pMaskSet->n==0 );
101998   for(i=0; i<pTabList->nSrc; i++){
101999     createMask(pMaskSet, pTabList->a[i].iCursor);
102000 #ifndef SQLITE_OMIT_VIRTUALTABLE
102001     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
102002       pWC->vmask |= ((Bitmask)1 << i);
102003     }
102004 #endif
102005   }
102006 #ifndef NDEBUG
102007   {
102008     Bitmask toTheLeft = 0;
102009     for(i=0; i<pTabList->nSrc; i++){
102010       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102011       assert( (m-1)==toTheLeft );
102012       toTheLeft |= m;
102013     }
102014   }
102015 #endif
102016
102017   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
102018   ** add new virtual terms onto the end of the WHERE clause.  We do not
102019   ** want to analyze these virtual terms, so start analyzing at the end
102020   ** and work forward so that the added virtual terms are never processed.
102021   */
102022   exprAnalyzeAll(pTabList, pWC);
102023   if( db->mallocFailed ){
102024     goto whereBeginError;
102025   }
102026
102027   /* Chose the best index to use for each table in the FROM clause.
102028   **
102029   ** This loop fills in the following fields:
102030   **
102031   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
102032   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
102033   **   pWInfo->a[].nEq       The number of == and IN constraints
102034   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
102035   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
102036   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
102037   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
102038   **
102039   ** This loop also figures out the nesting order of tables in the FROM
102040   ** clause.
102041   */
102042   notReady = ~(Bitmask)0;
102043   andFlags = ~0;
102044   WHERETRACE(("*** Optimizer Start ***\n"));
102045   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102046     WhereCost bestPlan;         /* Most efficient plan seen so far */
102047     Index *pIdx;                /* Index for FROM table at pTabItem */
102048     int j;                      /* For looping over FROM tables */
102049     int bestJ = -1;             /* The value of j */
102050     Bitmask m;                  /* Bitmask value for j or bestJ */
102051     int isOptimal;              /* Iterator for optimal/non-optimal search */
102052     int nUnconstrained;         /* Number tables without INDEXED BY */
102053     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
102054
102055     memset(&bestPlan, 0, sizeof(bestPlan));
102056     bestPlan.rCost = SQLITE_BIG_DBL;
102057     WHERETRACE(("*** Begin search for loop %d ***\n", i));
102058
102059     /* Loop through the remaining entries in the FROM clause to find the
102060     ** next nested loop. The loop tests all FROM clause entries
102061     ** either once or twice. 
102062     **
102063     ** The first test is always performed if there are two or more entries
102064     ** remaining and never performed if there is only one FROM clause entry
102065     ** to choose from.  The first test looks for an "optimal" scan.  In
102066     ** this context an optimal scan is one that uses the same strategy
102067     ** for the given FROM clause entry as would be selected if the entry
102068     ** were used as the innermost nested loop.  In other words, a table
102069     ** is chosen such that the cost of running that table cannot be reduced
102070     ** by waiting for other tables to run first.  This "optimal" test works
102071     ** by first assuming that the FROM clause is on the inner loop and finding
102072     ** its query plan, then checking to see if that query plan uses any
102073     ** other FROM clause terms that are notReady.  If no notReady terms are
102074     ** used then the "optimal" query plan works.
102075     **
102076     ** Note that the WhereCost.nRow parameter for an optimal scan might
102077     ** not be as small as it would be if the table really were the innermost
102078     ** join.  The nRow value can be reduced by WHERE clause constraints
102079     ** that do not use indices.  But this nRow reduction only happens if the
102080     ** table really is the innermost join.  
102081     **
102082     ** The second loop iteration is only performed if no optimal scan
102083     ** strategies were found by the first iteration. This second iteration
102084     ** is used to search for the lowest cost scan overall.
102085     **
102086     ** Previous versions of SQLite performed only the second iteration -
102087     ** the next outermost loop was always that with the lowest overall
102088     ** cost. However, this meant that SQLite could select the wrong plan
102089     ** for scripts such as the following:
102090     **   
102091     **   CREATE TABLE t1(a, b); 
102092     **   CREATE TABLE t2(c, d);
102093     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102094     **
102095     ** The best strategy is to iterate through table t1 first. However it
102096     ** is not possible to determine this with a simple greedy algorithm.
102097     ** Since the cost of a linear scan through table t2 is the same 
102098     ** as the cost of a linear scan through table t1, a simple greedy 
102099     ** algorithm may choose to use t2 for the outer loop, which is a much
102100     ** costlier approach.
102101     */
102102     nUnconstrained = 0;
102103     notIndexed = 0;
102104     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102105       Bitmask mask;             /* Mask of tables not yet ready */
102106       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102107         int doNotReorder;    /* True if this table should not be reordered */
102108         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
102109         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
102110   
102111         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102112         if( j!=iFrom && doNotReorder ) break;
102113         m = getMask(pMaskSet, pTabItem->iCursor);
102114         if( (m & notReady)==0 ){
102115           if( j==iFrom ) iFrom++;
102116           continue;
102117         }
102118         mask = (isOptimal ? m : notReady);
102119         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102120         if( pTabItem->pIndex==0 ) nUnconstrained++;
102121   
102122         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102123                     j, isOptimal));
102124         assert( pTabItem->pTab );
102125 #ifndef SQLITE_OMIT_VIRTUALTABLE
102126         if( IsVirtual(pTabItem->pTab) ){
102127           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102128           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102129                            &sCost, pp);
102130         }else 
102131 #endif
102132         {
102133           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102134                          &sCost);
102135         }
102136         assert( isOptimal || (sCost.used&notReady)==0 );
102137
102138         /* If an INDEXED BY clause is present, then the plan must use that
102139         ** index if it uses any index at all */
102140         assert( pTabItem->pIndex==0 
102141                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102142                   || sCost.plan.u.pIdx==pTabItem->pIndex );
102143
102144         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102145           notIndexed |= m;
102146         }
102147
102148         /* Conditions under which this table becomes the best so far:
102149         **
102150         **   (1) The table must not depend on other tables that have not
102151         **       yet run.
102152         **
102153         **   (2) A full-table-scan plan cannot supercede indexed plan unless
102154         **       the full-table-scan is an "optimal" plan as defined above.
102155         **
102156         **   (3) All tables have an INDEXED BY clause or this table lacks an
102157         **       INDEXED BY clause or this table uses the specific
102158         **       index specified by its INDEXED BY clause.  This rule ensures
102159         **       that a best-so-far is always selected even if an impossible
102160         **       combination of INDEXED BY clauses are given.  The error
102161         **       will be detected and relayed back to the application later.
102162         **       The NEVER() comes about because rule (2) above prevents
102163         **       An indexable full-table-scan from reaching rule (3).
102164         **
102165         **   (4) The plan cost must be lower than prior plans or else the
102166         **       cost must be the same and the number of rows must be lower.
102167         */
102168         if( (sCost.used&notReady)==0                       /* (1) */
102169             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
102170                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102171                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102172             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
102173                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102174             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
102175                 || (sCost.rCost<=bestPlan.rCost 
102176                  && sCost.plan.nRow<bestPlan.plan.nRow))
102177         ){
102178           WHERETRACE(("=== table %d is best so far"
102179                       " with cost=%g and nRow=%g\n",
102180                       j, sCost.rCost, sCost.plan.nRow));
102181           bestPlan = sCost;
102182           bestJ = j;
102183         }
102184         if( doNotReorder ) break;
102185       }
102186     }
102187     assert( bestJ>=0 );
102188     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102189     WHERETRACE(("*** Optimizer selects table %d for loop %d"
102190                 " with cost=%g and nRow=%g\n",
102191                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102192     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102193       *ppOrderBy = 0;
102194     }
102195     andFlags &= bestPlan.plan.wsFlags;
102196     pLevel->plan = bestPlan.plan;
102197     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102198     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102199     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102200       pLevel->iIdxCur = pParse->nTab++;
102201     }else{
102202       pLevel->iIdxCur = -1;
102203     }
102204     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
102205     pLevel->iFrom = (u8)bestJ;
102206     if( bestPlan.plan.nRow>=(double)1 ){
102207       pParse->nQueryLoop *= bestPlan.plan.nRow;
102208     }
102209
102210     /* Check that if the table scanned by this loop iteration had an
102211     ** INDEXED BY clause attached to it, that the named index is being
102212     ** used for the scan. If not, then query compilation has failed.
102213     ** Return an error.
102214     */
102215     pIdx = pTabList->a[bestJ].pIndex;
102216     if( pIdx ){
102217       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
102218         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
102219         goto whereBeginError;
102220       }else{
102221         /* If an INDEXED BY clause is used, the bestIndex() function is
102222         ** guaranteed to find the index specified in the INDEXED BY clause
102223         ** if it find an index at all. */
102224         assert( bestPlan.plan.u.pIdx==pIdx );
102225       }
102226     }
102227   }
102228   WHERETRACE(("*** Optimizer Finished ***\n"));
102229   if( pParse->nErr || db->mallocFailed ){
102230     goto whereBeginError;
102231   }
102232
102233   /* If the total query only selects a single row, then the ORDER BY
102234   ** clause is irrelevant.
102235   */
102236   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
102237     *ppOrderBy = 0;
102238   }
102239
102240   /* If the caller is an UPDATE or DELETE statement that is requesting
102241   ** to use a one-pass algorithm, determine if this is appropriate.
102242   ** The one-pass algorithm only works if the WHERE clause constraints
102243   ** the statement to update a single row.
102244   */
102245   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
102246   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
102247     pWInfo->okOnePass = 1;
102248     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
102249   }
102250
102251   /* Open all tables in the pTabList and any indices selected for
102252   ** searching those tables.
102253   */
102254   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
102255   notReady = ~(Bitmask)0;
102256   pWInfo->nRowOut = (double)1;
102257   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102258     Table *pTab;     /* Table to open */
102259     int iDb;         /* Index of database containing table/index */
102260
102261     pTabItem = &pTabList->a[pLevel->iFrom];
102262     pTab = pTabItem->pTab;
102263     pLevel->iTabCur = pTabItem->iCursor;
102264     pWInfo->nRowOut *= pLevel->plan.nRow;
102265     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102266     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
102267       /* Do nothing */
102268     }else
102269 #ifndef SQLITE_OMIT_VIRTUALTABLE
102270     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
102271       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102272       int iCur = pTabItem->iCursor;
102273       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
102274     }else
102275 #endif
102276     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102277          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
102278       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
102279       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
102280       testcase( pTab->nCol==BMS-1 );
102281       testcase( pTab->nCol==BMS );
102282       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
102283         Bitmask b = pTabItem->colUsed;
102284         int n = 0;
102285         for(; b; b=b>>1, n++){}
102286         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
102287                             SQLITE_INT_TO_PTR(n), P4_INT32);
102288         assert( n<=pTab->nCol );
102289       }
102290     }else{
102291       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102292     }
102293 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102294     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
102295       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
102296     }else
102297 #endif
102298     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102299       Index *pIx = pLevel->plan.u.pIdx;
102300       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
102301       int iIdxCur = pLevel->iIdxCur;
102302       assert( pIx->pSchema==pTab->pSchema );
102303       assert( iIdxCur>=0 );
102304       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
102305                         (char*)pKey, P4_KEYINFO_HANDOFF);
102306       VdbeComment((v, "%s", pIx->zName));
102307     }
102308     sqlite3CodeVerifySchema(pParse, iDb);
102309     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
102310   }
102311   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
102312   if( db->mallocFailed ) goto whereBeginError;
102313
102314   /* Generate the code to do the search.  Each iteration of the for
102315   ** loop below generates code for a single nested loop of the VM
102316   ** program.
102317   */
102318   notReady = ~(Bitmask)0;
102319   for(i=0; i<nTabList; i++){
102320     pLevel = &pWInfo->a[i];
102321     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
102322     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
102323     pWInfo->iContinue = pLevel->addrCont;
102324   }
102325
102326 #ifdef SQLITE_TEST  /* For testing and debugging use only */
102327   /* Record in the query plan information about the current table
102328   ** and the index used to access it (if any).  If the table itself
102329   ** is not used, its name is just '{}'.  If no index is used
102330   ** the index is listed as "{}".  If the primary key is used the
102331   ** index name is '*'.
102332   */
102333   for(i=0; i<nTabList; i++){
102334     char *z;
102335     int n;
102336     pLevel = &pWInfo->a[i];
102337     pTabItem = &pTabList->a[pLevel->iFrom];
102338     z = pTabItem->zAlias;
102339     if( z==0 ) z = pTabItem->pTab->zName;
102340     n = sqlite3Strlen30(z);
102341     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
102342       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
102343         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
102344         nQPlan += 2;
102345       }else{
102346         memcpy(&sqlite3_query_plan[nQPlan], z, n);
102347         nQPlan += n;
102348       }
102349       sqlite3_query_plan[nQPlan++] = ' ';
102350     }
102351     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
102352     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
102353     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
102354       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
102355       nQPlan += 2;
102356     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102357       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
102358       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
102359         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
102360         nQPlan += n;
102361         sqlite3_query_plan[nQPlan++] = ' ';
102362       }
102363     }else{
102364       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
102365       nQPlan += 3;
102366     }
102367   }
102368   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
102369     sqlite3_query_plan[--nQPlan] = 0;
102370   }
102371   sqlite3_query_plan[nQPlan] = 0;
102372   nQPlan = 0;
102373 #endif /* SQLITE_TEST // Testing and debugging use only */
102374
102375   /* Record the continuation address in the WhereInfo structure.  Then
102376   ** clean up and return.
102377   */
102378   return pWInfo;
102379
102380   /* Jump here if malloc fails */
102381 whereBeginError:
102382   if( pWInfo ){
102383     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102384     whereInfoFree(db, pWInfo);
102385   }
102386   return 0;
102387 }
102388
102389 /*
102390 ** Generate the end of the WHERE loop.  See comments on 
102391 ** sqlite3WhereBegin() for additional information.
102392 */
102393 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
102394   Parse *pParse = pWInfo->pParse;
102395   Vdbe *v = pParse->pVdbe;
102396   int i;
102397   WhereLevel *pLevel;
102398   SrcList *pTabList = pWInfo->pTabList;
102399   sqlite3 *db = pParse->db;
102400
102401   /* Generate loop termination code.
102402   */
102403   sqlite3ExprCacheClear(pParse);
102404   for(i=pWInfo->nLevel-1; i>=0; i--){
102405     pLevel = &pWInfo->a[i];
102406     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
102407     if( pLevel->op!=OP_Noop ){
102408       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
102409       sqlite3VdbeChangeP5(v, pLevel->p5);
102410     }
102411     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
102412       struct InLoop *pIn;
102413       int j;
102414       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
102415       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
102416         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
102417         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
102418         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
102419       }
102420       sqlite3DbFree(db, pLevel->u.in.aInLoop);
102421     }
102422     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
102423     if( pLevel->iLeftJoin ){
102424       int addr;
102425       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
102426       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102427            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
102428       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
102429         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
102430       }
102431       if( pLevel->iIdxCur>=0 ){
102432         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
102433       }
102434       if( pLevel->op==OP_Return ){
102435         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
102436       }else{
102437         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
102438       }
102439       sqlite3VdbeJumpHere(v, addr);
102440     }
102441   }
102442
102443   /* The "break" point is here, just past the end of the outer loop.
102444   ** Set it.
102445   */
102446   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
102447
102448   /* Close all of the cursors that were opened by sqlite3WhereBegin.
102449   */
102450   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
102451   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
102452     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
102453     Table *pTab = pTabItem->pTab;
102454     assert( pTab!=0 );
102455     if( (pTab->tabFlags & TF_Ephemeral)==0
102456      && pTab->pSelect==0
102457      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
102458     ){
102459       int ws = pLevel->plan.wsFlags;
102460       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
102461         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
102462       }
102463       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
102464         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
102465       }
102466     }
102467
102468     /* If this scan uses an index, make code substitutions to read data
102469     ** from the index in preference to the table. Sometimes, this means
102470     ** the table need never be read from. This is a performance boost,
102471     ** as the vdbe level waits until the table is read before actually
102472     ** seeking the table cursor to the record corresponding to the current
102473     ** position in the index.
102474     ** 
102475     ** Calls to the code generator in between sqlite3WhereBegin and
102476     ** sqlite3WhereEnd will have created code that references the table
102477     ** directly.  This loop scans all that code looking for opcodes
102478     ** that reference the table and converts them into opcodes that
102479     ** reference the index.
102480     */
102481     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
102482       int k, j, last;
102483       VdbeOp *pOp;
102484       Index *pIdx = pLevel->plan.u.pIdx;
102485
102486       assert( pIdx!=0 );
102487       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
102488       last = sqlite3VdbeCurrentAddr(v);
102489       for(k=pWInfo->iTop; k<last; k++, pOp++){
102490         if( pOp->p1!=pLevel->iTabCur ) continue;
102491         if( pOp->opcode==OP_Column ){
102492           for(j=0; j<pIdx->nColumn; j++){
102493             if( pOp->p2==pIdx->aiColumn[j] ){
102494               pOp->p2 = j;
102495               pOp->p1 = pLevel->iIdxCur;
102496               break;
102497             }
102498           }
102499           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102500                || j<pIdx->nColumn );
102501         }else if( pOp->opcode==OP_Rowid ){
102502           pOp->p1 = pLevel->iIdxCur;
102503           pOp->opcode = OP_IdxRowid;
102504         }
102505       }
102506     }
102507   }
102508
102509   /* Final cleanup
102510   */
102511   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102512   whereInfoFree(db, pWInfo);
102513   return;
102514 }
102515
102516 /************** End of where.c ***********************************************/
102517 /************** Begin file parse.c *******************************************/
102518 /* Driver template for the LEMON parser generator.
102519 ** The author disclaims copyright to this source code.
102520 **
102521 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
102522 ** The only modifications are the addition of a couple of NEVER()
102523 ** macros to disable tests that are needed in the case of a general
102524 ** LALR(1) grammar but which are always false in the
102525 ** specific grammar used by SQLite.
102526 */
102527 /* First off, code is included that follows the "include" declaration
102528 ** in the input grammar file. */
102529
102530
102531 /*
102532 ** Disable all error recovery processing in the parser push-down
102533 ** automaton.
102534 */
102535 #define YYNOERRORRECOVERY 1
102536
102537 /*
102538 ** Make yytestcase() the same as testcase()
102539 */
102540 #define yytestcase(X) testcase(X)
102541
102542 /*
102543 ** An instance of this structure holds information about the
102544 ** LIMIT clause of a SELECT statement.
102545 */
102546 struct LimitVal {
102547   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
102548   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
102549 };
102550
102551 /*
102552 ** An instance of this structure is used to store the LIKE,
102553 ** GLOB, NOT LIKE, and NOT GLOB operators.
102554 */
102555 struct LikeOp {
102556   Token eOperator;  /* "like" or "glob" or "regexp" */
102557   int not;         /* True if the NOT keyword is present */
102558 };
102559
102560 /*
102561 ** An instance of the following structure describes the event of a
102562 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
102563 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
102564 **
102565 **      UPDATE ON (a,b,c)
102566 **
102567 ** Then the "b" IdList records the list "a,b,c".
102568 */
102569 struct TrigEvent { int a; IdList * b; };
102570
102571 /*
102572 ** An instance of this structure holds the ATTACH key and the key type.
102573 */
102574 struct AttachKey { int type;  Token key; };
102575
102576
102577   /* This is a utility routine used to set the ExprSpan.zStart and
102578   ** ExprSpan.zEnd values of pOut so that the span covers the complete
102579   ** range of text beginning with pStart and going to the end of pEnd.
102580   */
102581   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
102582     pOut->zStart = pStart->z;
102583     pOut->zEnd = &pEnd->z[pEnd->n];
102584   }
102585
102586   /* Construct a new Expr object from a single identifier.  Use the
102587   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
102588   ** that created the expression.
102589   */
102590   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
102591     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
102592     pOut->zStart = pValue->z;
102593     pOut->zEnd = &pValue->z[pValue->n];
102594   }
102595
102596   /* This routine constructs a binary expression node out of two ExprSpan
102597   ** objects and uses the result to populate a new ExprSpan object.
102598   */
102599   static void spanBinaryExpr(
102600     ExprSpan *pOut,     /* Write the result here */
102601     Parse *pParse,      /* The parsing context.  Errors accumulate here */
102602     int op,             /* The binary operation */
102603     ExprSpan *pLeft,    /* The left operand */
102604     ExprSpan *pRight    /* The right operand */
102605   ){
102606     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
102607     pOut->zStart = pLeft->zStart;
102608     pOut->zEnd = pRight->zEnd;
102609   }
102610
102611   /* Construct an expression node for a unary postfix operator
102612   */
102613   static void spanUnaryPostfix(
102614     ExprSpan *pOut,        /* Write the new expression node here */
102615     Parse *pParse,         /* Parsing context to record errors */
102616     int op,                /* The operator */
102617     ExprSpan *pOperand,    /* The operand */
102618     Token *pPostOp         /* The operand token for setting the span */
102619   ){
102620     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102621     pOut->zStart = pOperand->zStart;
102622     pOut->zEnd = &pPostOp->z[pPostOp->n];
102623   }                           
102624
102625   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
102626   ** unary TK_ISNULL or TK_NOTNULL expression. */
102627   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
102628     sqlite3 *db = pParse->db;
102629     if( db->mallocFailed==0 && pY->op==TK_NULL ){
102630       pA->op = (u8)op;
102631       sqlite3ExprDelete(db, pA->pRight);
102632       pA->pRight = 0;
102633     }
102634   }
102635
102636   /* Construct an expression node for a unary prefix operator
102637   */
102638   static void spanUnaryPrefix(
102639     ExprSpan *pOut,        /* Write the new expression node here */
102640     Parse *pParse,         /* Parsing context to record errors */
102641     int op,                /* The operator */
102642     ExprSpan *pOperand,    /* The operand */
102643     Token *pPreOp         /* The operand token for setting the span */
102644   ){
102645     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102646     pOut->zStart = pPreOp->z;
102647     pOut->zEnd = pOperand->zEnd;
102648   }
102649 /* Next is all token values, in a form suitable for use by makeheaders.
102650 ** This section will be null unless lemon is run with the -m switch.
102651 */
102652 /* 
102653 ** These constants (all generated automatically by the parser generator)
102654 ** specify the various kinds of tokens (terminals) that the parser
102655 ** understands. 
102656 **
102657 ** Each symbol here is a terminal symbol in the grammar.
102658 */
102659 /* Make sure the INTERFACE macro is defined.
102660 */
102661 #ifndef INTERFACE
102662 # define INTERFACE 1
102663 #endif
102664 /* The next thing included is series of defines which control
102665 ** various aspects of the generated parser.
102666 **    YYCODETYPE         is the data type used for storing terminal
102667 **                       and nonterminal numbers.  "unsigned char" is
102668 **                       used if there are fewer than 250 terminals
102669 **                       and nonterminals.  "int" is used otherwise.
102670 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
102671 **                       to no legal terminal or nonterminal number.  This
102672 **                       number is used to fill in empty slots of the hash 
102673 **                       table.
102674 **    YYFALLBACK         If defined, this indicates that one or more tokens
102675 **                       have fall-back values which should be used if the
102676 **                       original value of the token will not parse.
102677 **    YYACTIONTYPE       is the data type used for storing terminal
102678 **                       and nonterminal numbers.  "unsigned char" is
102679 **                       used if there are fewer than 250 rules and
102680 **                       states combined.  "int" is used otherwise.
102681 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
102682 **                       directly to the parser from the tokenizer.
102683 **    YYMINORTYPE        is the data type used for all minor tokens.
102684 **                       This is typically a union of many types, one of
102685 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
102686 **                       for base tokens is called "yy0".
102687 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
102688 **                       zero the stack is dynamically sized using realloc()
102689 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
102690 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
102691 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
102692 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
102693 **    YYNSTATE           the combined number of states.
102694 **    YYNRULE            the number of rules in the grammar
102695 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
102696 **                       defined, then do no error processing.
102697 */
102698 #define YYCODETYPE unsigned char
102699 #define YYNOCODE 253
102700 #define YYACTIONTYPE unsigned short int
102701 #define YYWILDCARD 67
102702 #define sqlite3ParserTOKENTYPE Token
102703 typedef union {
102704   int yyinit;
102705   sqlite3ParserTOKENTYPE yy0;
102706   int yy4;
102707   struct TrigEvent yy90;
102708   ExprSpan yy118;
102709   TriggerStep* yy203;
102710   u8 yy210;
102711   struct {int value; int mask;} yy215;
102712   SrcList* yy259;
102713   struct LimitVal yy292;
102714   Expr* yy314;
102715   ExprList* yy322;
102716   struct LikeOp yy342;
102717   IdList* yy384;
102718   Select* yy387;
102719 } YYMINORTYPE;
102720 #ifndef YYSTACKDEPTH
102721 #define YYSTACKDEPTH 100
102722 #endif
102723 #define sqlite3ParserARG_SDECL Parse *pParse;
102724 #define sqlite3ParserARG_PDECL ,Parse *pParse
102725 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
102726 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
102727 #define YYNSTATE 630
102728 #define YYNRULE 329
102729 #define YYFALLBACK 1
102730 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
102731 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
102732 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
102733
102734 /* The yyzerominor constant is used to initialize instances of
102735 ** YYMINORTYPE objects to zero. */
102736 static const YYMINORTYPE yyzerominor = { 0 };
102737
102738 /* Define the yytestcase() macro to be a no-op if is not already defined
102739 ** otherwise.
102740 **
102741 ** Applications can choose to define yytestcase() in the %include section
102742 ** to a macro that can assist in verifying code coverage.  For production
102743 ** code the yytestcase() macro should be turned off.  But it is useful
102744 ** for testing.
102745 */
102746 #ifndef yytestcase
102747 # define yytestcase(X)
102748 #endif
102749
102750
102751 /* Next are the tables used to determine what action to take based on the
102752 ** current state and lookahead token.  These tables are used to implement
102753 ** functions that take a state number and lookahead value and return an
102754 ** action integer.  
102755 **
102756 ** Suppose the action integer is N.  Then the action is determined as
102757 ** follows
102758 **
102759 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
102760 **                                      token onto the stack and goto state N.
102761 **
102762 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
102763 **
102764 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
102765 **
102766 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
102767 **
102768 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
102769 **                                      slots in the yy_action[] table.
102770 **
102771 ** The action table is constructed as a single large table named yy_action[].
102772 ** Given state S and lookahead X, the action is computed as
102773 **
102774 **      yy_action[ yy_shift_ofst[S] + X ]
102775 **
102776 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
102777 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
102778 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
102779 ** and that yy_default[S] should be used instead.  
102780 **
102781 ** The formula above is for computing the action when the lookahead is
102782 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
102783 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
102784 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
102785 ** YY_SHIFT_USE_DFLT.
102786 **
102787 ** The following are the tables generated in this section:
102788 **
102789 **  yy_action[]        A single table containing all actions.
102790 **  yy_lookahead[]     A table containing the lookahead for each entry in
102791 **                     yy_action.  Used to detect hash collisions.
102792 **  yy_shift_ofst[]    For each state, the offset into yy_action for
102793 **                     shifting terminals.
102794 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
102795 **                     shifting non-terminals after a reduce.
102796 **  yy_default[]       Default action for each state.
102797 */
102798 #define YY_ACTTAB_COUNT (1557)
102799 static const YYACTIONTYPE yy_action[] = {
102800  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
102801  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
102802  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
102803  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
102804  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
102805  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102806  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
102807  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
102808  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102809  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
102810  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
102811  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
102812  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
102813  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
102814  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
102815  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
102816  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
102817  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
102818  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
102819  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
102820  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102821  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102822  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
102823  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
102824  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
102825  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
102826  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
102827  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102828  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
102829  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
102830  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
102831  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
102832  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
102833  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
102834  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
102835  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
102836  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102837  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
102838  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
102839  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
102840  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
102841  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
102842  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102843  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
102844  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
102845  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
102846  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
102847  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
102848  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
102849  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
102850  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
102851  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
102852  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
102853  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
102854  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
102855  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
102856  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
102857  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102858  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102859  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
102860  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
102861  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
102862  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
102863  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
102864  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
102865  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
102866  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
102867  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
102868  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
102869  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
102870  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
102871  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
102872  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
102873  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102874  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
102875  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
102876  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
102877  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
102878  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
102879  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
102880  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
102881  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
102882  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
102883  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
102884  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
102885  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
102886  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
102887  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
102888  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
102889  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
102890  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
102891  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
102892  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
102893  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
102894  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
102895  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
102896  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
102897  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
102898  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
102899  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
102900  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
102901  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
102902  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
102903  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
102904  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
102905  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
102906  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
102907  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
102908  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
102909  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
102910  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
102911  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
102912  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
102913  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
102914  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
102915  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
102916  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
102917  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
102918  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
102919  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
102920  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
102921  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
102922  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
102923  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
102924  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
102925  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
102926  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
102927  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
102928  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
102929  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
102930  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
102931  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
102932  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
102933  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
102934  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
102935  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
102936  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
102937  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
102938  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
102939  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
102940  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
102941  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
102942  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
102943  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
102944  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
102945  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
102946  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
102947  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
102948  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
102949  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
102950  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
102951  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
102952  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
102953  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
102954  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
102955  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
102956 };
102957 static const YYCODETYPE yy_lookahead[] = {
102958  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
102959  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
102960  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
102961  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
102962  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
102963  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
102964  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
102965  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
102966  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
102967  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
102968  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
102969  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
102970  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
102971  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
102972  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
102973  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
102974  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
102975  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
102976  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
102977  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
102978  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
102979  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
102980  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
102981  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
102982  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
102983  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
102984  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
102985  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
102986  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
102987  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
102988  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
102989  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
102990  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
102991  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
102992  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
102993  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
102994  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
102995  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
102996  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
102997  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
102998  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
102999  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
103000  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103001  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
103002  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
103003  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
103004  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
103005  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
103006  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
103007  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
103008  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
103009  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
103010  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
103011  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
103012  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
103013  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
103014  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
103015  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103016  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103017  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
103018  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
103019  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
103020  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
103021  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
103022  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103023  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
103024  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
103025  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
103026  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
103027  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
103028  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
103029  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
103030  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
103031  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103032  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
103033  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
103034  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
103035  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
103036  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
103037  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103038  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
103039  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
103040  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
103041  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
103042  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
103043  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
103044  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
103045  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
103046  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
103047  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
103048  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
103049  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
103050  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
103051  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
103052  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103053  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103054  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
103055  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
103056  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
103057  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
103058  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
103059  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
103060  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
103061  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
103062  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
103063  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
103064  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
103065  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
103066  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
103067  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
103068  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103069  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
103070  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
103071  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
103072  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
103073  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
103074  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
103075  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
103076  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
103077  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
103078  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
103079  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
103080  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
103081  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
103082  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
103083  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
103084  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
103085  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
103086  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
103087  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
103088  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
103089  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
103090  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
103091  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
103092  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
103093  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
103094  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
103095  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
103096  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
103097  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
103098  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
103099  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
103100  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
103101  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
103102  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
103103  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
103104  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
103105  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
103106  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
103107  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
103108  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
103109  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
103110  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
103111  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
103112  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
103113  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
103114 };
103115 #define YY_SHIFT_USE_DFLT (-74)
103116 #define YY_SHIFT_COUNT (418)
103117 #define YY_SHIFT_MIN   (-73)
103118 #define YY_SHIFT_MAX   (1468)
103119 static const short yy_shift_ofst[] = {
103120  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
103121  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
103122  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103123  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103124  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103125  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103126  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
103127  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
103128  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
103129  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
103130  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
103131  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103132  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
103133  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
103134  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
103135  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103136  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103137  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103138  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
103139  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
103140  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
103141  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
103142  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
103143  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
103144  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103145  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103146  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103147  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103148  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103149  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103150  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
103151  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
103152  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
103153  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103154  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103155  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
103156  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
103157  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
103158  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
103159  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
103160  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
103161  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
103162 };
103163 #define YY_REDUCE_USE_DFLT (-142)
103164 #define YY_REDUCE_COUNT (312)
103165 #define YY_REDUCE_MIN   (-141)
103166 #define YY_REDUCE_MAX   (1369)
103167 static const short yy_reduce_ofst[] = {
103168  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
103169  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
103170  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103171  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
103172  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
103173  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
103174  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
103175  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103176  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103177  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103178  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
103179  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
103180  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
103181  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
103182  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
103183  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103184  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103185  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
103186  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
103187  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
103188  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103189  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103190  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103191  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103192  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103193  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103194  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103195  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103196  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103197  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103198  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
103199  /*   310 */  1031, 1023, 1030,
103200 };
103201 static const YYACTIONTYPE yy_default[] = {
103202  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
103203  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
103204  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103205  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103206  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103207  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103208  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
103209  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
103210  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
103211  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
103212  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
103213  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103214  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
103215  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
103216  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103217  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
103218  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103219  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103220  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
103221  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
103222  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
103223  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
103224  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
103225  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
103226  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
103227  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
103228  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
103229  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
103230  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
103231  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
103232  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
103233  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
103234  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103235  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
103236  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103237  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
103238  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
103239  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103240  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
103241  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
103242  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
103243  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
103244  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
103245  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
103246  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
103247  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
103248  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
103249  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
103250  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
103251  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
103252  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
103253  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
103254  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
103255  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
103256  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
103257  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
103258  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
103259  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
103260  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
103261  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
103262  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
103263  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
103264  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
103265 };
103266
103267 /* The next table maps tokens into fallback tokens.  If a construct
103268 ** like the following:
103269 ** 
103270 **      %fallback ID X Y Z.
103271 **
103272 ** appears in the grammar, then ID becomes a fallback token for X, Y,
103273 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
103274 ** but it does not parse, the type of the token is changed to ID and
103275 ** the parse is retried before an error is thrown.
103276 */
103277 #ifdef YYFALLBACK
103278 static const YYCODETYPE yyFallback[] = {
103279     0,  /*          $ => nothing */
103280     0,  /*       SEMI => nothing */
103281    26,  /*    EXPLAIN => ID */
103282    26,  /*      QUERY => ID */
103283    26,  /*       PLAN => ID */
103284    26,  /*      BEGIN => ID */
103285     0,  /* TRANSACTION => nothing */
103286    26,  /*   DEFERRED => ID */
103287    26,  /*  IMMEDIATE => ID */
103288    26,  /*  EXCLUSIVE => ID */
103289     0,  /*     COMMIT => nothing */
103290    26,  /*        END => ID */
103291    26,  /*   ROLLBACK => ID */
103292    26,  /*  SAVEPOINT => ID */
103293    26,  /*    RELEASE => ID */
103294     0,  /*         TO => nothing */
103295     0,  /*      TABLE => nothing */
103296     0,  /*     CREATE => nothing */
103297    26,  /*         IF => ID */
103298     0,  /*        NOT => nothing */
103299     0,  /*     EXISTS => nothing */
103300    26,  /*       TEMP => ID */
103301     0,  /*         LP => nothing */
103302     0,  /*         RP => nothing */
103303     0,  /*         AS => nothing */
103304     0,  /*      COMMA => nothing */
103305     0,  /*         ID => nothing */
103306     0,  /*    INDEXED => nothing */
103307    26,  /*      ABORT => ID */
103308    26,  /*     ACTION => ID */
103309    26,  /*      AFTER => ID */
103310    26,  /*    ANALYZE => ID */
103311    26,  /*        ASC => ID */
103312    26,  /*     ATTACH => ID */
103313    26,  /*     BEFORE => ID */
103314    26,  /*         BY => ID */
103315    26,  /*    CASCADE => ID */
103316    26,  /*       CAST => ID */
103317    26,  /*   COLUMNKW => ID */
103318    26,  /*   CONFLICT => ID */
103319    26,  /*   DATABASE => ID */
103320    26,  /*       DESC => ID */
103321    26,  /*     DETACH => ID */
103322    26,  /*       EACH => ID */
103323    26,  /*       FAIL => ID */
103324    26,  /*        FOR => ID */
103325    26,  /*     IGNORE => ID */
103326    26,  /*  INITIALLY => ID */
103327    26,  /*    INSTEAD => ID */
103328    26,  /*    LIKE_KW => ID */
103329    26,  /*      MATCH => ID */
103330    26,  /*         NO => ID */
103331    26,  /*        KEY => ID */
103332    26,  /*         OF => ID */
103333    26,  /*     OFFSET => ID */
103334    26,  /*     PRAGMA => ID */
103335    26,  /*      RAISE => ID */
103336    26,  /*    REPLACE => ID */
103337    26,  /*   RESTRICT => ID */
103338    26,  /*        ROW => ID */
103339    26,  /*    TRIGGER => ID */
103340    26,  /*     VACUUM => ID */
103341    26,  /*       VIEW => ID */
103342    26,  /*    VIRTUAL => ID */
103343    26,  /*    REINDEX => ID */
103344    26,  /*     RENAME => ID */
103345    26,  /*   CTIME_KW => ID */
103346 };
103347 #endif /* YYFALLBACK */
103348
103349 /* The following structure represents a single element of the
103350 ** parser's stack.  Information stored includes:
103351 **
103352 **   +  The state number for the parser at this level of the stack.
103353 **
103354 **   +  The value of the token stored at this level of the stack.
103355 **      (In other words, the "major" token.)
103356 **
103357 **   +  The semantic value stored at this level of the stack.  This is
103358 **      the information used by the action routines in the grammar.
103359 **      It is sometimes called the "minor" token.
103360 */
103361 struct yyStackEntry {
103362   YYACTIONTYPE stateno;  /* The state-number */
103363   YYCODETYPE major;      /* The major token value.  This is the code
103364                          ** number for the token at this stack level */
103365   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
103366                          ** is the value of the token  */
103367 };
103368 typedef struct yyStackEntry yyStackEntry;
103369
103370 /* The state of the parser is completely contained in an instance of
103371 ** the following structure */
103372 struct yyParser {
103373   int yyidx;                    /* Index of top element in stack */
103374 #ifdef YYTRACKMAXSTACKDEPTH
103375   int yyidxMax;                 /* Maximum value of yyidx */
103376 #endif
103377   int yyerrcnt;                 /* Shifts left before out of the error */
103378   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
103379 #if YYSTACKDEPTH<=0
103380   int yystksz;                  /* Current side of the stack */
103381   yyStackEntry *yystack;        /* The parser's stack */
103382 #else
103383   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
103384 #endif
103385 };
103386 typedef struct yyParser yyParser;
103387
103388 #ifndef NDEBUG
103389 static FILE *yyTraceFILE = 0;
103390 static char *yyTracePrompt = 0;
103391 #endif /* NDEBUG */
103392
103393 #ifndef NDEBUG
103394 /* 
103395 ** Turn parser tracing on by giving a stream to which to write the trace
103396 ** and a prompt to preface each trace message.  Tracing is turned off
103397 ** by making either argument NULL 
103398 **
103399 ** Inputs:
103400 ** <ul>
103401 ** <li> A FILE* to which trace output should be written.
103402 **      If NULL, then tracing is turned off.
103403 ** <li> A prefix string written at the beginning of every
103404 **      line of trace output.  If NULL, then tracing is
103405 **      turned off.
103406 ** </ul>
103407 **
103408 ** Outputs:
103409 ** None.
103410 */
103411 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
103412   yyTraceFILE = TraceFILE;
103413   yyTracePrompt = zTracePrompt;
103414   if( yyTraceFILE==0 ) yyTracePrompt = 0;
103415   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
103416 }
103417 #endif /* NDEBUG */
103418
103419 #ifndef NDEBUG
103420 /* For tracing shifts, the names of all terminals and nonterminals
103421 ** are required.  The following table supplies these names */
103422 static const char *const yyTokenName[] = { 
103423   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
103424   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
103425   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
103426   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
103427   "TABLE",         "CREATE",        "IF",            "NOT",         
103428   "EXISTS",        "TEMP",          "LP",            "RP",          
103429   "AS",            "COMMA",         "ID",            "INDEXED",     
103430   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
103431   "ASC",           "ATTACH",        "BEFORE",        "BY",          
103432   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
103433   "DATABASE",      "DESC",          "DETACH",        "EACH",        
103434   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
103435   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
103436   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
103437   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
103438   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
103439   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
103440   "OR",            "AND",           "IS",            "BETWEEN",     
103441   "IN",            "ISNULL",        "NOTNULL",       "NE",          
103442   "EQ",            "GT",            "LE",            "LT",          
103443   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
103444   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
103445   "STAR",          "SLASH",         "REM",           "CONCAT",      
103446   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
103447   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
103448   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
103449   "ON",            "INSERT",        "DELETE",        "UPDATE",      
103450   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
103451   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
103452   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
103453   "JOIN",          "USING",         "ORDER",         "GROUP",       
103454   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
103455   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
103456   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
103457   "THEN",          "ELSE",          "INDEX",         "ALTER",       
103458   "ADD",           "error",         "input",         "cmdlist",     
103459   "ecmd",          "explain",       "cmdx",          "cmd",         
103460   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
103461   "create_table",  "create_table_args",  "createkw",      "temp",        
103462   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
103463   "select",        "column",        "columnid",      "type",        
103464   "carglist",      "id",            "ids",           "typetoken",   
103465   "typename",      "signed",        "plus_num",      "minus_num",   
103466   "carg",          "ccons",         "term",          "expr",        
103467   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
103468   "refargs",       "defer_subclause",  "refarg",        "refact",      
103469   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
103470   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
103471   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
103472   "distinct",      "selcollist",    "from",          "where_opt",   
103473   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
103474   "sclp",          "as",            "seltablist",    "stl_prefix",  
103475   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
103476   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
103477   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
103478   "itemlist",      "exprlist",      "likeop",        "between_op",  
103479   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
103480   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
103481   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
103482   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
103483   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
103484   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
103485   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
103486 };
103487 #endif /* NDEBUG */
103488
103489 #ifndef NDEBUG
103490 /* For tracing reduce actions, the names of all rules are required.
103491 */
103492 static const char *const yyRuleName[] = {
103493  /*   0 */ "input ::= cmdlist",
103494  /*   1 */ "cmdlist ::= cmdlist ecmd",
103495  /*   2 */ "cmdlist ::= ecmd",
103496  /*   3 */ "ecmd ::= SEMI",
103497  /*   4 */ "ecmd ::= explain cmdx SEMI",
103498  /*   5 */ "explain ::=",
103499  /*   6 */ "explain ::= EXPLAIN",
103500  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
103501  /*   8 */ "cmdx ::= cmd",
103502  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
103503  /*  10 */ "trans_opt ::=",
103504  /*  11 */ "trans_opt ::= TRANSACTION",
103505  /*  12 */ "trans_opt ::= TRANSACTION nm",
103506  /*  13 */ "transtype ::=",
103507  /*  14 */ "transtype ::= DEFERRED",
103508  /*  15 */ "transtype ::= IMMEDIATE",
103509  /*  16 */ "transtype ::= EXCLUSIVE",
103510  /*  17 */ "cmd ::= COMMIT trans_opt",
103511  /*  18 */ "cmd ::= END trans_opt",
103512  /*  19 */ "cmd ::= ROLLBACK trans_opt",
103513  /*  20 */ "savepoint_opt ::= SAVEPOINT",
103514  /*  21 */ "savepoint_opt ::=",
103515  /*  22 */ "cmd ::= SAVEPOINT nm",
103516  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
103517  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
103518  /*  25 */ "cmd ::= create_table create_table_args",
103519  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
103520  /*  27 */ "createkw ::= CREATE",
103521  /*  28 */ "ifnotexists ::=",
103522  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
103523  /*  30 */ "temp ::= TEMP",
103524  /*  31 */ "temp ::=",
103525  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
103526  /*  33 */ "create_table_args ::= AS select",
103527  /*  34 */ "columnlist ::= columnlist COMMA column",
103528  /*  35 */ "columnlist ::= column",
103529  /*  36 */ "column ::= columnid type carglist",
103530  /*  37 */ "columnid ::= nm",
103531  /*  38 */ "id ::= ID",
103532  /*  39 */ "id ::= INDEXED",
103533  /*  40 */ "ids ::= ID|STRING",
103534  /*  41 */ "nm ::= id",
103535  /*  42 */ "nm ::= STRING",
103536  /*  43 */ "nm ::= JOIN_KW",
103537  /*  44 */ "type ::=",
103538  /*  45 */ "type ::= typetoken",
103539  /*  46 */ "typetoken ::= typename",
103540  /*  47 */ "typetoken ::= typename LP signed RP",
103541  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
103542  /*  49 */ "typename ::= ids",
103543  /*  50 */ "typename ::= typename ids",
103544  /*  51 */ "signed ::= plus_num",
103545  /*  52 */ "signed ::= minus_num",
103546  /*  53 */ "carglist ::= carglist carg",
103547  /*  54 */ "carglist ::=",
103548  /*  55 */ "carg ::= CONSTRAINT nm ccons",
103549  /*  56 */ "carg ::= ccons",
103550  /*  57 */ "ccons ::= DEFAULT term",
103551  /*  58 */ "ccons ::= DEFAULT LP expr RP",
103552  /*  59 */ "ccons ::= DEFAULT PLUS term",
103553  /*  60 */ "ccons ::= DEFAULT MINUS term",
103554  /*  61 */ "ccons ::= DEFAULT id",
103555  /*  62 */ "ccons ::= NULL onconf",
103556  /*  63 */ "ccons ::= NOT NULL onconf",
103557  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
103558  /*  65 */ "ccons ::= UNIQUE onconf",
103559  /*  66 */ "ccons ::= CHECK LP expr RP",
103560  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
103561  /*  68 */ "ccons ::= defer_subclause",
103562  /*  69 */ "ccons ::= COLLATE ids",
103563  /*  70 */ "autoinc ::=",
103564  /*  71 */ "autoinc ::= AUTOINCR",
103565  /*  72 */ "refargs ::=",
103566  /*  73 */ "refargs ::= refargs refarg",
103567  /*  74 */ "refarg ::= MATCH nm",
103568  /*  75 */ "refarg ::= ON INSERT refact",
103569  /*  76 */ "refarg ::= ON DELETE refact",
103570  /*  77 */ "refarg ::= ON UPDATE refact",
103571  /*  78 */ "refact ::= SET NULL",
103572  /*  79 */ "refact ::= SET DEFAULT",
103573  /*  80 */ "refact ::= CASCADE",
103574  /*  81 */ "refact ::= RESTRICT",
103575  /*  82 */ "refact ::= NO ACTION",
103576  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
103577  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
103578  /*  85 */ "init_deferred_pred_opt ::=",
103579  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
103580  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
103581  /*  88 */ "conslist_opt ::=",
103582  /*  89 */ "conslist_opt ::= COMMA conslist",
103583  /*  90 */ "conslist ::= conslist COMMA tcons",
103584  /*  91 */ "conslist ::= conslist tcons",
103585  /*  92 */ "conslist ::= tcons",
103586  /*  93 */ "tcons ::= CONSTRAINT nm",
103587  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
103588  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
103589  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
103590  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
103591  /*  98 */ "defer_subclause_opt ::=",
103592  /*  99 */ "defer_subclause_opt ::= defer_subclause",
103593  /* 100 */ "onconf ::=",
103594  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
103595  /* 102 */ "orconf ::=",
103596  /* 103 */ "orconf ::= OR resolvetype",
103597  /* 104 */ "resolvetype ::= raisetype",
103598  /* 105 */ "resolvetype ::= IGNORE",
103599  /* 106 */ "resolvetype ::= REPLACE",
103600  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
103601  /* 108 */ "ifexists ::= IF EXISTS",
103602  /* 109 */ "ifexists ::=",
103603  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
103604  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
103605  /* 112 */ "cmd ::= select",
103606  /* 113 */ "select ::= oneselect",
103607  /* 114 */ "select ::= select multiselect_op oneselect",
103608  /* 115 */ "multiselect_op ::= UNION",
103609  /* 116 */ "multiselect_op ::= UNION ALL",
103610  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
103611  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
103612  /* 119 */ "distinct ::= DISTINCT",
103613  /* 120 */ "distinct ::= ALL",
103614  /* 121 */ "distinct ::=",
103615  /* 122 */ "sclp ::= selcollist COMMA",
103616  /* 123 */ "sclp ::=",
103617  /* 124 */ "selcollist ::= sclp expr as",
103618  /* 125 */ "selcollist ::= sclp STAR",
103619  /* 126 */ "selcollist ::= sclp nm DOT STAR",
103620  /* 127 */ "as ::= AS nm",
103621  /* 128 */ "as ::= ids",
103622  /* 129 */ "as ::=",
103623  /* 130 */ "from ::=",
103624  /* 131 */ "from ::= FROM seltablist",
103625  /* 132 */ "stl_prefix ::= seltablist joinop",
103626  /* 133 */ "stl_prefix ::=",
103627  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
103628  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
103629  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
103630  /* 137 */ "dbnm ::=",
103631  /* 138 */ "dbnm ::= DOT nm",
103632  /* 139 */ "fullname ::= nm dbnm",
103633  /* 140 */ "joinop ::= COMMA|JOIN",
103634  /* 141 */ "joinop ::= JOIN_KW JOIN",
103635  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
103636  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
103637  /* 144 */ "on_opt ::= ON expr",
103638  /* 145 */ "on_opt ::=",
103639  /* 146 */ "indexed_opt ::=",
103640  /* 147 */ "indexed_opt ::= INDEXED BY nm",
103641  /* 148 */ "indexed_opt ::= NOT INDEXED",
103642  /* 149 */ "using_opt ::= USING LP inscollist RP",
103643  /* 150 */ "using_opt ::=",
103644  /* 151 */ "orderby_opt ::=",
103645  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
103646  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
103647  /* 154 */ "sortlist ::= sortitem sortorder",
103648  /* 155 */ "sortitem ::= expr",
103649  /* 156 */ "sortorder ::= ASC",
103650  /* 157 */ "sortorder ::= DESC",
103651  /* 158 */ "sortorder ::=",
103652  /* 159 */ "groupby_opt ::=",
103653  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
103654  /* 161 */ "having_opt ::=",
103655  /* 162 */ "having_opt ::= HAVING expr",
103656  /* 163 */ "limit_opt ::=",
103657  /* 164 */ "limit_opt ::= LIMIT expr",
103658  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
103659  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
103660  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
103661  /* 168 */ "where_opt ::=",
103662  /* 169 */ "where_opt ::= WHERE expr",
103663  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
103664  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
103665  /* 172 */ "setlist ::= nm EQ expr",
103666  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
103667  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
103668  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
103669  /* 176 */ "insert_cmd ::= INSERT orconf",
103670  /* 177 */ "insert_cmd ::= REPLACE",
103671  /* 178 */ "itemlist ::= itemlist COMMA expr",
103672  /* 179 */ "itemlist ::= expr",
103673  /* 180 */ "inscollist_opt ::=",
103674  /* 181 */ "inscollist_opt ::= LP inscollist RP",
103675  /* 182 */ "inscollist ::= inscollist COMMA nm",
103676  /* 183 */ "inscollist ::= nm",
103677  /* 184 */ "expr ::= term",
103678  /* 185 */ "expr ::= LP expr RP",
103679  /* 186 */ "term ::= NULL",
103680  /* 187 */ "expr ::= id",
103681  /* 188 */ "expr ::= JOIN_KW",
103682  /* 189 */ "expr ::= nm DOT nm",
103683  /* 190 */ "expr ::= nm DOT nm DOT nm",
103684  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
103685  /* 192 */ "term ::= STRING",
103686  /* 193 */ "expr ::= REGISTER",
103687  /* 194 */ "expr ::= VARIABLE",
103688  /* 195 */ "expr ::= expr COLLATE ids",
103689  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
103690  /* 197 */ "expr ::= ID LP distinct exprlist RP",
103691  /* 198 */ "expr ::= ID LP STAR RP",
103692  /* 199 */ "term ::= CTIME_KW",
103693  /* 200 */ "expr ::= expr AND expr",
103694  /* 201 */ "expr ::= expr OR expr",
103695  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
103696  /* 203 */ "expr ::= expr EQ|NE expr",
103697  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
103698  /* 205 */ "expr ::= expr PLUS|MINUS expr",
103699  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
103700  /* 207 */ "expr ::= expr CONCAT expr",
103701  /* 208 */ "likeop ::= LIKE_KW",
103702  /* 209 */ "likeop ::= NOT LIKE_KW",
103703  /* 210 */ "likeop ::= MATCH",
103704  /* 211 */ "likeop ::= NOT MATCH",
103705  /* 212 */ "expr ::= expr likeop expr",
103706  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
103707  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
103708  /* 215 */ "expr ::= expr NOT NULL",
103709  /* 216 */ "expr ::= expr IS expr",
103710  /* 217 */ "expr ::= expr IS NOT expr",
103711  /* 218 */ "expr ::= NOT expr",
103712  /* 219 */ "expr ::= BITNOT expr",
103713  /* 220 */ "expr ::= MINUS expr",
103714  /* 221 */ "expr ::= PLUS expr",
103715  /* 222 */ "between_op ::= BETWEEN",
103716  /* 223 */ "between_op ::= NOT BETWEEN",
103717  /* 224 */ "expr ::= expr between_op expr AND expr",
103718  /* 225 */ "in_op ::= IN",
103719  /* 226 */ "in_op ::= NOT IN",
103720  /* 227 */ "expr ::= expr in_op LP exprlist RP",
103721  /* 228 */ "expr ::= LP select RP",
103722  /* 229 */ "expr ::= expr in_op LP select RP",
103723  /* 230 */ "expr ::= expr in_op nm dbnm",
103724  /* 231 */ "expr ::= EXISTS LP select RP",
103725  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
103726  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
103727  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
103728  /* 235 */ "case_else ::= ELSE expr",
103729  /* 236 */ "case_else ::=",
103730  /* 237 */ "case_operand ::= expr",
103731  /* 238 */ "case_operand ::=",
103732  /* 239 */ "exprlist ::= nexprlist",
103733  /* 240 */ "exprlist ::=",
103734  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
103735  /* 242 */ "nexprlist ::= expr",
103736  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
103737  /* 244 */ "uniqueflag ::= UNIQUE",
103738  /* 245 */ "uniqueflag ::=",
103739  /* 246 */ "idxlist_opt ::=",
103740  /* 247 */ "idxlist_opt ::= LP idxlist RP",
103741  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
103742  /* 249 */ "idxlist ::= nm collate sortorder",
103743  /* 250 */ "collate ::=",
103744  /* 251 */ "collate ::= COLLATE ids",
103745  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
103746  /* 253 */ "cmd ::= VACUUM",
103747  /* 254 */ "cmd ::= VACUUM nm",
103748  /* 255 */ "cmd ::= PRAGMA nm dbnm",
103749  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
103750  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
103751  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
103752  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
103753  /* 260 */ "nmnum ::= plus_num",
103754  /* 261 */ "nmnum ::= nm",
103755  /* 262 */ "nmnum ::= ON",
103756  /* 263 */ "nmnum ::= DELETE",
103757  /* 264 */ "nmnum ::= DEFAULT",
103758  /* 265 */ "plus_num ::= plus_opt number",
103759  /* 266 */ "minus_num ::= MINUS number",
103760  /* 267 */ "number ::= INTEGER|FLOAT",
103761  /* 268 */ "plus_opt ::= PLUS",
103762  /* 269 */ "plus_opt ::=",
103763  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
103764  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
103765  /* 272 */ "trigger_time ::= BEFORE",
103766  /* 273 */ "trigger_time ::= AFTER",
103767  /* 274 */ "trigger_time ::= INSTEAD OF",
103768  /* 275 */ "trigger_time ::=",
103769  /* 276 */ "trigger_event ::= DELETE|INSERT",
103770  /* 277 */ "trigger_event ::= UPDATE",
103771  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
103772  /* 279 */ "foreach_clause ::=",
103773  /* 280 */ "foreach_clause ::= FOR EACH ROW",
103774  /* 281 */ "when_clause ::=",
103775  /* 282 */ "when_clause ::= WHEN expr",
103776  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
103777  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
103778  /* 285 */ "trnm ::= nm",
103779  /* 286 */ "trnm ::= nm DOT nm",
103780  /* 287 */ "tridxby ::=",
103781  /* 288 */ "tridxby ::= INDEXED BY nm",
103782  /* 289 */ "tridxby ::= NOT INDEXED",
103783  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
103784  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
103785  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
103786  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
103787  /* 294 */ "trigger_cmd ::= select",
103788  /* 295 */ "expr ::= RAISE LP IGNORE RP",
103789  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
103790  /* 297 */ "raisetype ::= ROLLBACK",
103791  /* 298 */ "raisetype ::= ABORT",
103792  /* 299 */ "raisetype ::= FAIL",
103793  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
103794  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
103795  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
103796  /* 303 */ "key_opt ::=",
103797  /* 304 */ "key_opt ::= KEY expr",
103798  /* 305 */ "database_kw_opt ::= DATABASE",
103799  /* 306 */ "database_kw_opt ::=",
103800  /* 307 */ "cmd ::= REINDEX",
103801  /* 308 */ "cmd ::= REINDEX nm dbnm",
103802  /* 309 */ "cmd ::= ANALYZE",
103803  /* 310 */ "cmd ::= ANALYZE nm dbnm",
103804  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
103805  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
103806  /* 313 */ "add_column_fullname ::= fullname",
103807  /* 314 */ "kwcolumn_opt ::=",
103808  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
103809  /* 316 */ "cmd ::= create_vtab",
103810  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
103811  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
103812  /* 319 */ "vtabarglist ::= vtabarg",
103813  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
103814  /* 321 */ "vtabarg ::=",
103815  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
103816  /* 323 */ "vtabargtoken ::= ANY",
103817  /* 324 */ "vtabargtoken ::= lp anylist RP",
103818  /* 325 */ "lp ::= LP",
103819  /* 326 */ "anylist ::=",
103820  /* 327 */ "anylist ::= anylist LP anylist RP",
103821  /* 328 */ "anylist ::= anylist ANY",
103822 };
103823 #endif /* NDEBUG */
103824
103825
103826 #if YYSTACKDEPTH<=0
103827 /*
103828 ** Try to increase the size of the parser stack.
103829 */
103830 static void yyGrowStack(yyParser *p){
103831   int newSize;
103832   yyStackEntry *pNew;
103833
103834   newSize = p->yystksz*2 + 100;
103835   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
103836   if( pNew ){
103837     p->yystack = pNew;
103838     p->yystksz = newSize;
103839 #ifndef NDEBUG
103840     if( yyTraceFILE ){
103841       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
103842               yyTracePrompt, p->yystksz);
103843     }
103844 #endif
103845   }
103846 }
103847 #endif
103848
103849 /* 
103850 ** This function allocates a new parser.
103851 ** The only argument is a pointer to a function which works like
103852 ** malloc.
103853 **
103854 ** Inputs:
103855 ** A pointer to the function used to allocate memory.
103856 **
103857 ** Outputs:
103858 ** A pointer to a parser.  This pointer is used in subsequent calls
103859 ** to sqlite3Parser and sqlite3ParserFree.
103860 */
103861 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
103862   yyParser *pParser;
103863   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
103864   if( pParser ){
103865     pParser->yyidx = -1;
103866 #ifdef YYTRACKMAXSTACKDEPTH
103867     pParser->yyidxMax = 0;
103868 #endif
103869 #if YYSTACKDEPTH<=0
103870     pParser->yystack = NULL;
103871     pParser->yystksz = 0;
103872     yyGrowStack(pParser);
103873 #endif
103874   }
103875   return pParser;
103876 }
103877
103878 /* The following function deletes the value associated with a
103879 ** symbol.  The symbol can be either a terminal or nonterminal.
103880 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
103881 ** the value.
103882 */
103883 static void yy_destructor(
103884   yyParser *yypParser,    /* The parser */
103885   YYCODETYPE yymajor,     /* Type code for object to destroy */
103886   YYMINORTYPE *yypminor   /* The object to be destroyed */
103887 ){
103888   sqlite3ParserARG_FETCH;
103889   switch( yymajor ){
103890     /* Here is inserted the actions which take place when a
103891     ** terminal or non-terminal is destroyed.  This can happen
103892     ** when the symbol is popped from the stack during a
103893     ** reduce or during error processing or when a parser is 
103894     ** being destroyed before it is finished parsing.
103895     **
103896     ** Note: during a reduce, the only symbols destroyed are those
103897     ** which appear on the RHS of the rule, but which are not used
103898     ** inside the C code.
103899     */
103900     case 160: /* select */
103901     case 194: /* oneselect */
103902 {
103903 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
103904 }
103905       break;
103906     case 174: /* term */
103907     case 175: /* expr */
103908 {
103909 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
103910 }
103911       break;
103912     case 179: /* idxlist_opt */
103913     case 187: /* idxlist */
103914     case 197: /* selcollist */
103915     case 200: /* groupby_opt */
103916     case 202: /* orderby_opt */
103917     case 204: /* sclp */
103918     case 214: /* sortlist */
103919     case 216: /* nexprlist */
103920     case 217: /* setlist */
103921     case 220: /* itemlist */
103922     case 221: /* exprlist */
103923     case 226: /* case_exprlist */
103924 {
103925 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
103926 }
103927       break;
103928     case 193: /* fullname */
103929     case 198: /* from */
103930     case 206: /* seltablist */
103931     case 207: /* stl_prefix */
103932 {
103933 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
103934 }
103935       break;
103936     case 199: /* where_opt */
103937     case 201: /* having_opt */
103938     case 210: /* on_opt */
103939     case 215: /* sortitem */
103940     case 225: /* case_operand */
103941     case 227: /* case_else */
103942     case 238: /* when_clause */
103943     case 243: /* key_opt */
103944 {
103945 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
103946 }
103947       break;
103948     case 211: /* using_opt */
103949     case 213: /* inscollist */
103950     case 219: /* inscollist_opt */
103951 {
103952 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
103953 }
103954       break;
103955     case 234: /* trigger_cmd_list */
103956     case 239: /* trigger_cmd */
103957 {
103958 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
103959 }
103960       break;
103961     case 236: /* trigger_event */
103962 {
103963 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
103964 }
103965       break;
103966     default:  break;   /* If no destructor action specified: do nothing */
103967   }
103968 }
103969
103970 /*
103971 ** Pop the parser's stack once.
103972 **
103973 ** If there is a destructor routine associated with the token which
103974 ** is popped from the stack, then call it.
103975 **
103976 ** Return the major token number for the symbol popped.
103977 */
103978 static int yy_pop_parser_stack(yyParser *pParser){
103979   YYCODETYPE yymajor;
103980   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
103981
103982   /* There is no mechanism by which the parser stack can be popped below
103983   ** empty in SQLite.  */
103984   if( NEVER(pParser->yyidx<0) ) return 0;
103985 #ifndef NDEBUG
103986   if( yyTraceFILE && pParser->yyidx>=0 ){
103987     fprintf(yyTraceFILE,"%sPopping %s\n",
103988       yyTracePrompt,
103989       yyTokenName[yytos->major]);
103990   }
103991 #endif
103992   yymajor = yytos->major;
103993   yy_destructor(pParser, yymajor, &yytos->minor);
103994   pParser->yyidx--;
103995   return yymajor;
103996 }
103997
103998 /* 
103999 ** Deallocate and destroy a parser.  Destructors are all called for
104000 ** all stack elements before shutting the parser down.
104001 **
104002 ** Inputs:
104003 ** <ul>
104004 ** <li>  A pointer to the parser.  This should be a pointer
104005 **       obtained from sqlite3ParserAlloc.
104006 ** <li>  A pointer to a function used to reclaim memory obtained
104007 **       from malloc.
104008 ** </ul>
104009 */
104010 SQLITE_PRIVATE void sqlite3ParserFree(
104011   void *p,                    /* The parser to be deleted */
104012   void (*freeProc)(void*)     /* Function used to reclaim memory */
104013 ){
104014   yyParser *pParser = (yyParser*)p;
104015   /* In SQLite, we never try to destroy a parser that was not successfully
104016   ** created in the first place. */
104017   if( NEVER(pParser==0) ) return;
104018   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104019 #if YYSTACKDEPTH<=0
104020   free(pParser->yystack);
104021 #endif
104022   (*freeProc)((void*)pParser);
104023 }
104024
104025 /*
104026 ** Return the peak depth of the stack for a parser.
104027 */
104028 #ifdef YYTRACKMAXSTACKDEPTH
104029 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104030   yyParser *pParser = (yyParser*)p;
104031   return pParser->yyidxMax;
104032 }
104033 #endif
104034
104035 /*
104036 ** Find the appropriate action for a parser given the terminal
104037 ** look-ahead token iLookAhead.
104038 **
104039 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104040 ** independent of the look-ahead.  If it is, return the action, otherwise
104041 ** return YY_NO_ACTION.
104042 */
104043 static int yy_find_shift_action(
104044   yyParser *pParser,        /* The parser */
104045   YYCODETYPE iLookAhead     /* The look-ahead token */
104046 ){
104047   int i;
104048   int stateno = pParser->yystack[pParser->yyidx].stateno;
104049  
104050   if( stateno>YY_SHIFT_COUNT
104051    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104052     return yy_default[stateno];
104053   }
104054   assert( iLookAhead!=YYNOCODE );
104055   i += iLookAhead;
104056   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104057     if( iLookAhead>0 ){
104058 #ifdef YYFALLBACK
104059       YYCODETYPE iFallback;            /* Fallback token */
104060       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104061              && (iFallback = yyFallback[iLookAhead])!=0 ){
104062 #ifndef NDEBUG
104063         if( yyTraceFILE ){
104064           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104065              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104066         }
104067 #endif
104068         return yy_find_shift_action(pParser, iFallback);
104069       }
104070 #endif
104071 #ifdef YYWILDCARD
104072       {
104073         int j = i - iLookAhead + YYWILDCARD;
104074         if( 
104075 #if YY_SHIFT_MIN+YYWILDCARD<0
104076           j>=0 &&
104077 #endif
104078 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104079           j<YY_ACTTAB_COUNT &&
104080 #endif
104081           yy_lookahead[j]==YYWILDCARD
104082         ){
104083 #ifndef NDEBUG
104084           if( yyTraceFILE ){
104085             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104086                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104087           }
104088 #endif /* NDEBUG */
104089           return yy_action[j];
104090         }
104091       }
104092 #endif /* YYWILDCARD */
104093     }
104094     return yy_default[stateno];
104095   }else{
104096     return yy_action[i];
104097   }
104098 }
104099
104100 /*
104101 ** Find the appropriate action for a parser given the non-terminal
104102 ** look-ahead token iLookAhead.
104103 **
104104 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104105 ** independent of the look-ahead.  If it is, return the action, otherwise
104106 ** return YY_NO_ACTION.
104107 */
104108 static int yy_find_reduce_action(
104109   int stateno,              /* Current state number */
104110   YYCODETYPE iLookAhead     /* The look-ahead token */
104111 ){
104112   int i;
104113 #ifdef YYERRORSYMBOL
104114   if( stateno>YY_REDUCE_COUNT ){
104115     return yy_default[stateno];
104116   }
104117 #else
104118   assert( stateno<=YY_REDUCE_COUNT );
104119 #endif
104120   i = yy_reduce_ofst[stateno];
104121   assert( i!=YY_REDUCE_USE_DFLT );
104122   assert( iLookAhead!=YYNOCODE );
104123   i += iLookAhead;
104124 #ifdef YYERRORSYMBOL
104125   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104126     return yy_default[stateno];
104127   }
104128 #else
104129   assert( i>=0 && i<YY_ACTTAB_COUNT );
104130   assert( yy_lookahead[i]==iLookAhead );
104131 #endif
104132   return yy_action[i];
104133 }
104134
104135 /*
104136 ** The following routine is called if the stack overflows.
104137 */
104138 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104139    sqlite3ParserARG_FETCH;
104140    yypParser->yyidx--;
104141 #ifndef NDEBUG
104142    if( yyTraceFILE ){
104143      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104144    }
104145 #endif
104146    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104147    /* Here code is inserted which will execute if the parser
104148    ** stack every overflows */
104149
104150   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104151   sqlite3ErrorMsg(pParse, "parser stack overflow");
104152   pParse->parseError = 1;
104153    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104154 }
104155
104156 /*
104157 ** Perform a shift action.
104158 */
104159 static void yy_shift(
104160   yyParser *yypParser,          /* The parser to be shifted */
104161   int yyNewState,               /* The new state to shift in */
104162   int yyMajor,                  /* The major token to shift in */
104163   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
104164 ){
104165   yyStackEntry *yytos;
104166   yypParser->yyidx++;
104167 #ifdef YYTRACKMAXSTACKDEPTH
104168   if( yypParser->yyidx>yypParser->yyidxMax ){
104169     yypParser->yyidxMax = yypParser->yyidx;
104170   }
104171 #endif
104172 #if YYSTACKDEPTH>0 
104173   if( yypParser->yyidx>=YYSTACKDEPTH ){
104174     yyStackOverflow(yypParser, yypMinor);
104175     return;
104176   }
104177 #else
104178   if( yypParser->yyidx>=yypParser->yystksz ){
104179     yyGrowStack(yypParser);
104180     if( yypParser->yyidx>=yypParser->yystksz ){
104181       yyStackOverflow(yypParser, yypMinor);
104182       return;
104183     }
104184   }
104185 #endif
104186   yytos = &yypParser->yystack[yypParser->yyidx];
104187   yytos->stateno = (YYACTIONTYPE)yyNewState;
104188   yytos->major = (YYCODETYPE)yyMajor;
104189   yytos->minor = *yypMinor;
104190 #ifndef NDEBUG
104191   if( yyTraceFILE && yypParser->yyidx>0 ){
104192     int i;
104193     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104194     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104195     for(i=1; i<=yypParser->yyidx; i++)
104196       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104197     fprintf(yyTraceFILE,"\n");
104198   }
104199 #endif
104200 }
104201
104202 /* The following table contains information about every rule that
104203 ** is used during the reduce.
104204 */
104205 static const struct {
104206   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
104207   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
104208 } yyRuleInfo[] = {
104209   { 142, 1 },
104210   { 143, 2 },
104211   { 143, 1 },
104212   { 144, 1 },
104213   { 144, 3 },
104214   { 145, 0 },
104215   { 145, 1 },
104216   { 145, 3 },
104217   { 146, 1 },
104218   { 147, 3 },
104219   { 149, 0 },
104220   { 149, 1 },
104221   { 149, 2 },
104222   { 148, 0 },
104223   { 148, 1 },
104224   { 148, 1 },
104225   { 148, 1 },
104226   { 147, 2 },
104227   { 147, 2 },
104228   { 147, 2 },
104229   { 151, 1 },
104230   { 151, 0 },
104231   { 147, 2 },
104232   { 147, 3 },
104233   { 147, 5 },
104234   { 147, 2 },
104235   { 152, 6 },
104236   { 154, 1 },
104237   { 156, 0 },
104238   { 156, 3 },
104239   { 155, 1 },
104240   { 155, 0 },
104241   { 153, 4 },
104242   { 153, 2 },
104243   { 158, 3 },
104244   { 158, 1 },
104245   { 161, 3 },
104246   { 162, 1 },
104247   { 165, 1 },
104248   { 165, 1 },
104249   { 166, 1 },
104250   { 150, 1 },
104251   { 150, 1 },
104252   { 150, 1 },
104253   { 163, 0 },
104254   { 163, 1 },
104255   { 167, 1 },
104256   { 167, 4 },
104257   { 167, 6 },
104258   { 168, 1 },
104259   { 168, 2 },
104260   { 169, 1 },
104261   { 169, 1 },
104262   { 164, 2 },
104263   { 164, 0 },
104264   { 172, 3 },
104265   { 172, 1 },
104266   { 173, 2 },
104267   { 173, 4 },
104268   { 173, 3 },
104269   { 173, 3 },
104270   { 173, 2 },
104271   { 173, 2 },
104272   { 173, 3 },
104273   { 173, 5 },
104274   { 173, 2 },
104275   { 173, 4 },
104276   { 173, 4 },
104277   { 173, 1 },
104278   { 173, 2 },
104279   { 178, 0 },
104280   { 178, 1 },
104281   { 180, 0 },
104282   { 180, 2 },
104283   { 182, 2 },
104284   { 182, 3 },
104285   { 182, 3 },
104286   { 182, 3 },
104287   { 183, 2 },
104288   { 183, 2 },
104289   { 183, 1 },
104290   { 183, 1 },
104291   { 183, 2 },
104292   { 181, 3 },
104293   { 181, 2 },
104294   { 184, 0 },
104295   { 184, 2 },
104296   { 184, 2 },
104297   { 159, 0 },
104298   { 159, 2 },
104299   { 185, 3 },
104300   { 185, 2 },
104301   { 185, 1 },
104302   { 186, 2 },
104303   { 186, 7 },
104304   { 186, 5 },
104305   { 186, 5 },
104306   { 186, 10 },
104307   { 188, 0 },
104308   { 188, 1 },
104309   { 176, 0 },
104310   { 176, 3 },
104311   { 189, 0 },
104312   { 189, 2 },
104313   { 190, 1 },
104314   { 190, 1 },
104315   { 190, 1 },
104316   { 147, 4 },
104317   { 192, 2 },
104318   { 192, 0 },
104319   { 147, 8 },
104320   { 147, 4 },
104321   { 147, 1 },
104322   { 160, 1 },
104323   { 160, 3 },
104324   { 195, 1 },
104325   { 195, 2 },
104326   { 195, 1 },
104327   { 194, 9 },
104328   { 196, 1 },
104329   { 196, 1 },
104330   { 196, 0 },
104331   { 204, 2 },
104332   { 204, 0 },
104333   { 197, 3 },
104334   { 197, 2 },
104335   { 197, 4 },
104336   { 205, 2 },
104337   { 205, 1 },
104338   { 205, 0 },
104339   { 198, 0 },
104340   { 198, 2 },
104341   { 207, 2 },
104342   { 207, 0 },
104343   { 206, 7 },
104344   { 206, 7 },
104345   { 206, 7 },
104346   { 157, 0 },
104347   { 157, 2 },
104348   { 193, 2 },
104349   { 208, 1 },
104350   { 208, 2 },
104351   { 208, 3 },
104352   { 208, 4 },
104353   { 210, 2 },
104354   { 210, 0 },
104355   { 209, 0 },
104356   { 209, 3 },
104357   { 209, 2 },
104358   { 211, 4 },
104359   { 211, 0 },
104360   { 202, 0 },
104361   { 202, 3 },
104362   { 214, 4 },
104363   { 214, 2 },
104364   { 215, 1 },
104365   { 177, 1 },
104366   { 177, 1 },
104367   { 177, 0 },
104368   { 200, 0 },
104369   { 200, 3 },
104370   { 201, 0 },
104371   { 201, 2 },
104372   { 203, 0 },
104373   { 203, 2 },
104374   { 203, 4 },
104375   { 203, 4 },
104376   { 147, 5 },
104377   { 199, 0 },
104378   { 199, 2 },
104379   { 147, 7 },
104380   { 217, 5 },
104381   { 217, 3 },
104382   { 147, 8 },
104383   { 147, 5 },
104384   { 147, 6 },
104385   { 218, 2 },
104386   { 218, 1 },
104387   { 220, 3 },
104388   { 220, 1 },
104389   { 219, 0 },
104390   { 219, 3 },
104391   { 213, 3 },
104392   { 213, 1 },
104393   { 175, 1 },
104394   { 175, 3 },
104395   { 174, 1 },
104396   { 175, 1 },
104397   { 175, 1 },
104398   { 175, 3 },
104399   { 175, 5 },
104400   { 174, 1 },
104401   { 174, 1 },
104402   { 175, 1 },
104403   { 175, 1 },
104404   { 175, 3 },
104405   { 175, 6 },
104406   { 175, 5 },
104407   { 175, 4 },
104408   { 174, 1 },
104409   { 175, 3 },
104410   { 175, 3 },
104411   { 175, 3 },
104412   { 175, 3 },
104413   { 175, 3 },
104414   { 175, 3 },
104415   { 175, 3 },
104416   { 175, 3 },
104417   { 222, 1 },
104418   { 222, 2 },
104419   { 222, 1 },
104420   { 222, 2 },
104421   { 175, 3 },
104422   { 175, 5 },
104423   { 175, 2 },
104424   { 175, 3 },
104425   { 175, 3 },
104426   { 175, 4 },
104427   { 175, 2 },
104428   { 175, 2 },
104429   { 175, 2 },
104430   { 175, 2 },
104431   { 223, 1 },
104432   { 223, 2 },
104433   { 175, 5 },
104434   { 224, 1 },
104435   { 224, 2 },
104436   { 175, 5 },
104437   { 175, 3 },
104438   { 175, 5 },
104439   { 175, 4 },
104440   { 175, 4 },
104441   { 175, 5 },
104442   { 226, 5 },
104443   { 226, 4 },
104444   { 227, 2 },
104445   { 227, 0 },
104446   { 225, 1 },
104447   { 225, 0 },
104448   { 221, 1 },
104449   { 221, 0 },
104450   { 216, 3 },
104451   { 216, 1 },
104452   { 147, 11 },
104453   { 228, 1 },
104454   { 228, 0 },
104455   { 179, 0 },
104456   { 179, 3 },
104457   { 187, 5 },
104458   { 187, 3 },
104459   { 229, 0 },
104460   { 229, 2 },
104461   { 147, 4 },
104462   { 147, 1 },
104463   { 147, 2 },
104464   { 147, 3 },
104465   { 147, 5 },
104466   { 147, 6 },
104467   { 147, 5 },
104468   { 147, 6 },
104469   { 230, 1 },
104470   { 230, 1 },
104471   { 230, 1 },
104472   { 230, 1 },
104473   { 230, 1 },
104474   { 170, 2 },
104475   { 171, 2 },
104476   { 232, 1 },
104477   { 231, 1 },
104478   { 231, 0 },
104479   { 147, 5 },
104480   { 233, 11 },
104481   { 235, 1 },
104482   { 235, 1 },
104483   { 235, 2 },
104484   { 235, 0 },
104485   { 236, 1 },
104486   { 236, 1 },
104487   { 236, 3 },
104488   { 237, 0 },
104489   { 237, 3 },
104490   { 238, 0 },
104491   { 238, 2 },
104492   { 234, 3 },
104493   { 234, 2 },
104494   { 240, 1 },
104495   { 240, 3 },
104496   { 241, 0 },
104497   { 241, 3 },
104498   { 241, 2 },
104499   { 239, 7 },
104500   { 239, 8 },
104501   { 239, 5 },
104502   { 239, 5 },
104503   { 239, 1 },
104504   { 175, 4 },
104505   { 175, 6 },
104506   { 191, 1 },
104507   { 191, 1 },
104508   { 191, 1 },
104509   { 147, 4 },
104510   { 147, 6 },
104511   { 147, 3 },
104512   { 243, 0 },
104513   { 243, 2 },
104514   { 242, 1 },
104515   { 242, 0 },
104516   { 147, 1 },
104517   { 147, 3 },
104518   { 147, 1 },
104519   { 147, 3 },
104520   { 147, 6 },
104521   { 147, 6 },
104522   { 244, 1 },
104523   { 245, 0 },
104524   { 245, 1 },
104525   { 147, 1 },
104526   { 147, 4 },
104527   { 246, 7 },
104528   { 247, 1 },
104529   { 247, 3 },
104530   { 248, 0 },
104531   { 248, 2 },
104532   { 249, 1 },
104533   { 249, 3 },
104534   { 250, 1 },
104535   { 251, 0 },
104536   { 251, 4 },
104537   { 251, 2 },
104538 };
104539
104540 static void yy_accept(yyParser*);  /* Forward Declaration */
104541
104542 /*
104543 ** Perform a reduce action and the shift that must immediately
104544 ** follow the reduce.
104545 */
104546 static void yy_reduce(
104547   yyParser *yypParser,         /* The parser */
104548   int yyruleno                 /* Number of the rule by which to reduce */
104549 ){
104550   int yygoto;                     /* The next state */
104551   int yyact;                      /* The next action */
104552   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
104553   yyStackEntry *yymsp;            /* The top of the parser's stack */
104554   int yysize;                     /* Amount to pop the stack */
104555   sqlite3ParserARG_FETCH;
104556   yymsp = &yypParser->yystack[yypParser->yyidx];
104557 #ifndef NDEBUG
104558   if( yyTraceFILE && yyruleno>=0 
104559         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
104560     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
104561       yyRuleName[yyruleno]);
104562   }
104563 #endif /* NDEBUG */
104564
104565   /* Silence complaints from purify about yygotominor being uninitialized
104566   ** in some cases when it is copied into the stack after the following
104567   ** switch.  yygotominor is uninitialized when a rule reduces that does
104568   ** not set the value of its left-hand side nonterminal.  Leaving the
104569   ** value of the nonterminal uninitialized is utterly harmless as long
104570   ** as the value is never used.  So really the only thing this code
104571   ** accomplishes is to quieten purify.  
104572   **
104573   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
104574   ** without this code, their parser segfaults.  I'm not sure what there
104575   ** parser is doing to make this happen.  This is the second bug report
104576   ** from wireshark this week.  Clearly they are stressing Lemon in ways
104577   ** that it has not been previously stressed...  (SQLite ticket #2172)
104578   */
104579   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
104580   yygotominor = yyzerominor;
104581
104582
104583   switch( yyruleno ){
104584   /* Beginning here are the reduction cases.  A typical example
104585   ** follows:
104586   **   case 0:
104587   **  #line <lineno> <grammarfile>
104588   **     { ... }           // User supplied code
104589   **  #line <lineno> <thisfile>
104590   **     break;
104591   */
104592       case 5: /* explain ::= */
104593 { sqlite3BeginParse(pParse, 0); }
104594         break;
104595       case 6: /* explain ::= EXPLAIN */
104596 { sqlite3BeginParse(pParse, 1); }
104597         break;
104598       case 7: /* explain ::= EXPLAIN QUERY PLAN */
104599 { sqlite3BeginParse(pParse, 2); }
104600         break;
104601       case 8: /* cmdx ::= cmd */
104602 { sqlite3FinishCoding(pParse); }
104603         break;
104604       case 9: /* cmd ::= BEGIN transtype trans_opt */
104605 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
104606         break;
104607       case 13: /* transtype ::= */
104608 {yygotominor.yy4 = TK_DEFERRED;}
104609         break;
104610       case 14: /* transtype ::= DEFERRED */
104611       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
104612       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
104613       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
104614       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
104615 {yygotominor.yy4 = yymsp[0].major;}
104616         break;
104617       case 17: /* cmd ::= COMMIT trans_opt */
104618       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
104619 {sqlite3CommitTransaction(pParse);}
104620         break;
104621       case 19: /* cmd ::= ROLLBACK trans_opt */
104622 {sqlite3RollbackTransaction(pParse);}
104623         break;
104624       case 22: /* cmd ::= SAVEPOINT nm */
104625 {
104626   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
104627 }
104628         break;
104629       case 23: /* cmd ::= RELEASE savepoint_opt nm */
104630 {
104631   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
104632 }
104633         break;
104634       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
104635 {
104636   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
104637 }
104638         break;
104639       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
104640 {
104641    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
104642 }
104643         break;
104644       case 27: /* createkw ::= CREATE */
104645 {
104646   pParse->db->lookaside.bEnabled = 0;
104647   yygotominor.yy0 = yymsp[0].minor.yy0;
104648 }
104649         break;
104650       case 28: /* ifnotexists ::= */
104651       case 31: /* temp ::= */ yytestcase(yyruleno==31);
104652       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
104653       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
104654       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
104655       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
104656       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
104657       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
104658       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
104659       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
104660       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
104661       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
104662 {yygotominor.yy4 = 0;}
104663         break;
104664       case 29: /* ifnotexists ::= IF NOT EXISTS */
104665       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
104666       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
104667       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
104668       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
104669       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
104670       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
104671       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
104672 {yygotominor.yy4 = 1;}
104673         break;
104674       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
104675 {
104676   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
104677 }
104678         break;
104679       case 33: /* create_table_args ::= AS select */
104680 {
104681   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
104682   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104683 }
104684         break;
104685       case 36: /* column ::= columnid type carglist */
104686 {
104687   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
104688   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
104689 }
104690         break;
104691       case 37: /* columnid ::= nm */
104692 {
104693   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
104694   yygotominor.yy0 = yymsp[0].minor.yy0;
104695 }
104696         break;
104697       case 38: /* id ::= ID */
104698       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
104699       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
104700       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
104701       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
104702       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
104703       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
104704       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
104705       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
104706       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
104707       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
104708       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
104709       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
104710       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
104711       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
104712       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
104713       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
104714       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
104715       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
104716       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
104717       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
104718       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
104719 {yygotominor.yy0 = yymsp[0].minor.yy0;}
104720         break;
104721       case 45: /* type ::= typetoken */
104722 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
104723         break;
104724       case 47: /* typetoken ::= typename LP signed RP */
104725 {
104726   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
104727   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
104728 }
104729         break;
104730       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
104731 {
104732   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
104733   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
104734 }
104735         break;
104736       case 50: /* typename ::= typename ids */
104737 {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);}
104738         break;
104739       case 57: /* ccons ::= DEFAULT term */
104740       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
104741 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
104742         break;
104743       case 58: /* ccons ::= DEFAULT LP expr RP */
104744 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
104745         break;
104746       case 60: /* ccons ::= DEFAULT MINUS term */
104747 {
104748   ExprSpan v;
104749   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
104750   v.zStart = yymsp[-1].minor.yy0.z;
104751   v.zEnd = yymsp[0].minor.yy118.zEnd;
104752   sqlite3AddDefaultValue(pParse,&v);
104753 }
104754         break;
104755       case 61: /* ccons ::= DEFAULT id */
104756 {
104757   ExprSpan v;
104758   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
104759   sqlite3AddDefaultValue(pParse,&v);
104760 }
104761         break;
104762       case 63: /* ccons ::= NOT NULL onconf */
104763 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
104764         break;
104765       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
104766 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
104767         break;
104768       case 65: /* ccons ::= UNIQUE onconf */
104769 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
104770         break;
104771       case 66: /* ccons ::= CHECK LP expr RP */
104772 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
104773         break;
104774       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
104775 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
104776         break;
104777       case 68: /* ccons ::= defer_subclause */
104778 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
104779         break;
104780       case 69: /* ccons ::= COLLATE ids */
104781 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
104782         break;
104783       case 72: /* refargs ::= */
104784 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
104785         break;
104786       case 73: /* refargs ::= refargs refarg */
104787 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
104788         break;
104789       case 74: /* refarg ::= MATCH nm */
104790       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
104791 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
104792         break;
104793       case 76: /* refarg ::= ON DELETE refact */
104794 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
104795         break;
104796       case 77: /* refarg ::= ON UPDATE refact */
104797 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
104798         break;
104799       case 78: /* refact ::= SET NULL */
104800 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
104801         break;
104802       case 79: /* refact ::= SET DEFAULT */
104803 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
104804         break;
104805       case 80: /* refact ::= CASCADE */
104806 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
104807         break;
104808       case 81: /* refact ::= RESTRICT */
104809 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
104810         break;
104811       case 82: /* refact ::= NO ACTION */
104812 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
104813         break;
104814       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
104815       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
104816       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
104817       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
104818 {yygotominor.yy4 = yymsp[0].minor.yy4;}
104819         break;
104820       case 88: /* conslist_opt ::= */
104821 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
104822         break;
104823       case 89: /* conslist_opt ::= COMMA conslist */
104824 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
104825         break;
104826       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
104827 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
104828         break;
104829       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
104830 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
104831         break;
104832       case 96: /* tcons ::= CHECK LP expr RP onconf */
104833 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
104834         break;
104835       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
104836 {
104837     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
104838     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
104839 }
104840         break;
104841       case 100: /* onconf ::= */
104842 {yygotominor.yy4 = OE_Default;}
104843         break;
104844       case 102: /* orconf ::= */
104845 {yygotominor.yy210 = OE_Default;}
104846         break;
104847       case 103: /* orconf ::= OR resolvetype */
104848 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
104849         break;
104850       case 105: /* resolvetype ::= IGNORE */
104851 {yygotominor.yy4 = OE_Ignore;}
104852         break;
104853       case 106: /* resolvetype ::= REPLACE */
104854 {yygotominor.yy4 = OE_Replace;}
104855         break;
104856       case 107: /* cmd ::= DROP TABLE ifexists fullname */
104857 {
104858   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
104859 }
104860         break;
104861       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
104862 {
104863   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);
104864 }
104865         break;
104866       case 111: /* cmd ::= DROP VIEW ifexists fullname */
104867 {
104868   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
104869 }
104870         break;
104871       case 112: /* cmd ::= select */
104872 {
104873   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
104874   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
104875   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
104876 }
104877         break;
104878       case 113: /* select ::= oneselect */
104879 {yygotominor.yy387 = yymsp[0].minor.yy387;}
104880         break;
104881       case 114: /* select ::= select multiselect_op oneselect */
104882 {
104883   if( yymsp[0].minor.yy387 ){
104884     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
104885     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
104886   }else{
104887     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
104888   }
104889   yygotominor.yy387 = yymsp[0].minor.yy387;
104890 }
104891         break;
104892       case 116: /* multiselect_op ::= UNION ALL */
104893 {yygotominor.yy4 = TK_ALL;}
104894         break;
104895       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
104896 {
104897   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);
104898 }
104899         break;
104900       case 122: /* sclp ::= selcollist COMMA */
104901       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
104902 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
104903         break;
104904       case 123: /* sclp ::= */
104905       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
104906       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
104907       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
104908       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
104909 {yygotominor.yy322 = 0;}
104910         break;
104911       case 124: /* selcollist ::= sclp expr as */
104912 {
104913    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
104914    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
104915    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
104916 }
104917         break;
104918       case 125: /* selcollist ::= sclp STAR */
104919 {
104920   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
104921   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
104922 }
104923         break;
104924       case 126: /* selcollist ::= sclp nm DOT STAR */
104925 {
104926   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
104927   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
104928   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
104929   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
104930 }
104931         break;
104932       case 129: /* as ::= */
104933 {yygotominor.yy0.n = 0;}
104934         break;
104935       case 130: /* from ::= */
104936 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
104937         break;
104938       case 131: /* from ::= FROM seltablist */
104939 {
104940   yygotominor.yy259 = yymsp[0].minor.yy259;
104941   sqlite3SrcListShiftJoinType(yygotominor.yy259);
104942 }
104943         break;
104944       case 132: /* stl_prefix ::= seltablist joinop */
104945 {
104946    yygotominor.yy259 = yymsp[-1].minor.yy259;
104947    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
104948 }
104949         break;
104950       case 133: /* stl_prefix ::= */
104951 {yygotominor.yy259 = 0;}
104952         break;
104953       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
104954 {
104955   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);
104956   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
104957 }
104958         break;
104959       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
104960 {
104961     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);
104962   }
104963         break;
104964       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
104965 {
104966     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
104967       yygotominor.yy259 = yymsp[-4].minor.yy259;
104968     }else{
104969       Select *pSubquery;
104970       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
104971       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
104972       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
104973     }
104974   }
104975         break;
104976       case 137: /* dbnm ::= */
104977       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
104978 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
104979         break;
104980       case 139: /* fullname ::= nm dbnm */
104981 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
104982         break;
104983       case 140: /* joinop ::= COMMA|JOIN */
104984 { yygotominor.yy4 = JT_INNER; }
104985         break;
104986       case 141: /* joinop ::= JOIN_KW JOIN */
104987 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
104988         break;
104989       case 142: /* joinop ::= JOIN_KW nm JOIN */
104990 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
104991         break;
104992       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
104993 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
104994         break;
104995       case 144: /* on_opt ::= ON expr */
104996       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
104997       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
104998       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
104999       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
105000       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
105001 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
105002         break;
105003       case 145: /* on_opt ::= */
105004       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
105005       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
105006       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
105007       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
105008 {yygotominor.yy314 = 0;}
105009         break;
105010       case 148: /* indexed_opt ::= NOT INDEXED */
105011 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105012         break;
105013       case 149: /* using_opt ::= USING LP inscollist RP */
105014       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105015 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
105016         break;
105017       case 150: /* using_opt ::= */
105018       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105019 {yygotominor.yy384 = 0;}
105020         break;
105021       case 152: /* orderby_opt ::= ORDER BY sortlist */
105022       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105023       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105024 {yygotominor.yy322 = yymsp[0].minor.yy322;}
105025         break;
105026       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105027 {
105028   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105029   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105030 }
105031         break;
105032       case 154: /* sortlist ::= sortitem sortorder */
105033 {
105034   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105035   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105036 }
105037         break;
105038       case 156: /* sortorder ::= ASC */
105039       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105040 {yygotominor.yy4 = SQLITE_SO_ASC;}
105041         break;
105042       case 157: /* sortorder ::= DESC */
105043 {yygotominor.yy4 = SQLITE_SO_DESC;}
105044         break;
105045       case 163: /* limit_opt ::= */
105046 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105047         break;
105048       case 164: /* limit_opt ::= LIMIT expr */
105049 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105050         break;
105051       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105052 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105053         break;
105054       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105055 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105056         break;
105057       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105058 {
105059   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105060   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105061 }
105062         break;
105063       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105064 {
105065   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105066   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
105067   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105068 }
105069         break;
105070       case 171: /* setlist ::= setlist COMMA nm EQ expr */
105071 {
105072   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105073   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105074 }
105075         break;
105076       case 172: /* setlist ::= nm EQ expr */
105077 {
105078   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105079   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105080 }
105081         break;
105082       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105083 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105084         break;
105085       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105086 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105087         break;
105088       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105089 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105090         break;
105091       case 176: /* insert_cmd ::= INSERT orconf */
105092 {yygotominor.yy210 = yymsp[0].minor.yy210;}
105093         break;
105094       case 177: /* insert_cmd ::= REPLACE */
105095 {yygotominor.yy210 = OE_Replace;}
105096         break;
105097       case 178: /* itemlist ::= itemlist COMMA expr */
105098       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105099 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105100         break;
105101       case 179: /* itemlist ::= expr */
105102       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105103 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105104         break;
105105       case 182: /* inscollist ::= inscollist COMMA nm */
105106 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105107         break;
105108       case 183: /* inscollist ::= nm */
105109 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105110         break;
105111       case 184: /* expr ::= term */
105112 {yygotominor.yy118 = yymsp[0].minor.yy118;}
105113         break;
105114       case 185: /* expr ::= LP expr RP */
105115 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105116         break;
105117       case 186: /* term ::= NULL */
105118       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105119       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105120 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105121         break;
105122       case 187: /* expr ::= id */
105123       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105124 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105125         break;
105126       case 189: /* expr ::= nm DOT nm */
105127 {
105128   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105129   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105130   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105131   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105132 }
105133         break;
105134       case 190: /* expr ::= nm DOT nm DOT nm */
105135 {
105136   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105137   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105138   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105139   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105140   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105141   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105142 }
105143         break;
105144       case 193: /* expr ::= REGISTER */
105145 {
105146   /* When doing a nested parse, one can include terms in an expression
105147   ** that look like this:   #1 #2 ...  These terms refer to registers
105148   ** in the virtual machine.  #N is the N-th register. */
105149   if( pParse->nested==0 ){
105150     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105151     yygotominor.yy118.pExpr = 0;
105152   }else{
105153     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105154     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105155   }
105156   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105157 }
105158         break;
105159       case 194: /* expr ::= VARIABLE */
105160 {
105161   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105162   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105163   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105164 }
105165         break;
105166       case 195: /* expr ::= expr COLLATE ids */
105167 {
105168   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105169   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105170   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105171 }
105172         break;
105173       case 196: /* expr ::= CAST LP expr AS typetoken RP */
105174 {
105175   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105176   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105177 }
105178         break;
105179       case 197: /* expr ::= ID LP distinct exprlist RP */
105180 {
105181   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105182     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105183   }
105184   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105185   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105186   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105187     yygotominor.yy118.pExpr->flags |= EP_Distinct;
105188   }
105189 }
105190         break;
105191       case 198: /* expr ::= ID LP STAR RP */
105192 {
105193   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105194   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105195 }
105196         break;
105197       case 199: /* term ::= CTIME_KW */
105198 {
105199   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105200   ** treated as functions that return constants */
105201   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
105202   if( yygotominor.yy118.pExpr ){
105203     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
105204   }
105205   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105206 }
105207         break;
105208       case 200: /* expr ::= expr AND expr */
105209       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
105210       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
105211       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
105212       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
105213       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
105214       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
105215       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
105216 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
105217         break;
105218       case 208: /* likeop ::= LIKE_KW */
105219       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
105220 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
105221         break;
105222       case 209: /* likeop ::= NOT LIKE_KW */
105223       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
105224 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
105225         break;
105226       case 212: /* expr ::= expr likeop expr */
105227 {
105228   ExprList *pList;
105229   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
105230   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
105231   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
105232   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105233   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105234   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105235   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105236 }
105237         break;
105238       case 213: /* expr ::= expr likeop expr ESCAPE expr */
105239 {
105240   ExprList *pList;
105241   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105242   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
105243   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105244   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
105245   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105246   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105247   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105248   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105249 }
105250         break;
105251       case 214: /* expr ::= expr ISNULL|NOTNULL */
105252 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
105253         break;
105254       case 215: /* expr ::= expr NOT NULL */
105255 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
105256         break;
105257       case 216: /* expr ::= expr IS expr */
105258 {
105259   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
105260   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
105261 }
105262         break;
105263       case 217: /* expr ::= expr IS NOT expr */
105264 {
105265   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
105266   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
105267 }
105268         break;
105269       case 218: /* expr ::= NOT expr */
105270       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
105271 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105272         break;
105273       case 220: /* expr ::= MINUS expr */
105274 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105275         break;
105276       case 221: /* expr ::= PLUS expr */
105277 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105278         break;
105279       case 224: /* expr ::= expr between_op expr AND expr */
105280 {
105281   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105282   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105283   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105284   if( yygotominor.yy118.pExpr ){
105285     yygotominor.yy118.pExpr->x.pList = pList;
105286   }else{
105287     sqlite3ExprListDelete(pParse->db, pList);
105288   } 
105289   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105290   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105291   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105292 }
105293         break;
105294       case 227: /* expr ::= expr in_op LP exprlist RP */
105295 {
105296     if( yymsp[-1].minor.yy322==0 ){
105297       /* Expressions of the form
105298       **
105299       **      expr1 IN ()
105300       **      expr1 NOT IN ()
105301       **
105302       ** simplify to constants 0 (false) and 1 (true), respectively,
105303       ** regardless of the value of expr1.
105304       */
105305       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
105306       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
105307     }else{
105308       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105309       if( yygotominor.yy118.pExpr ){
105310         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
105311         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105312       }else{
105313         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
105314       }
105315       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105316     }
105317     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105318     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105319   }
105320         break;
105321       case 228: /* expr ::= LP select RP */
105322 {
105323     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
105324     if( yygotominor.yy118.pExpr ){
105325       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105326       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105327       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105328     }else{
105329       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105330     }
105331     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
105332     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105333   }
105334         break;
105335       case 229: /* expr ::= expr in_op LP select RP */
105336 {
105337     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105338     if( yygotominor.yy118.pExpr ){
105339       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105340       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105341       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105342     }else{
105343       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105344     }
105345     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105346     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105347     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105348   }
105349         break;
105350       case 230: /* expr ::= expr in_op nm dbnm */
105351 {
105352     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
105353     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
105354     if( yygotominor.yy118.pExpr ){
105355       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
105356       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105357       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105358     }else{
105359       sqlite3SrcListDelete(pParse->db, pSrc);
105360     }
105361     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105362     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
105363     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];
105364   }
105365         break;
105366       case 231: /* expr ::= EXISTS LP select RP */
105367 {
105368     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
105369     if( p ){
105370       p->x.pSelect = yymsp[-1].minor.yy387;
105371       ExprSetProperty(p, EP_xIsSelect);
105372       sqlite3ExprSetHeight(pParse, p);
105373     }else{
105374       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105375     }
105376     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105377     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105378   }
105379         break;
105380       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
105381 {
105382   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
105383   if( yygotominor.yy118.pExpr ){
105384     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
105385     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105386   }else{
105387     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
105388   }
105389   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
105390   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105391 }
105392         break;
105393       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
105394 {
105395   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
105396   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105397 }
105398         break;
105399       case 234: /* case_exprlist ::= WHEN expr THEN expr */
105400 {
105401   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105402   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105403 }
105404         break;
105405       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
105406 {
105407   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
105408                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
105409                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
105410 }
105411         break;
105412       case 244: /* uniqueflag ::= UNIQUE */
105413       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
105414 {yygotominor.yy4 = OE_Abort;}
105415         break;
105416       case 245: /* uniqueflag ::= */
105417 {yygotominor.yy4 = OE_None;}
105418         break;
105419       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
105420 {
105421   Expr *p = 0;
105422   if( yymsp[-1].minor.yy0.n>0 ){
105423     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
105424     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105425   }
105426   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
105427   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
105428   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105429   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105430 }
105431         break;
105432       case 249: /* idxlist ::= nm collate sortorder */
105433 {
105434   Expr *p = 0;
105435   if( yymsp[-1].minor.yy0.n>0 ){
105436     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
105437     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105438   }
105439   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
105440   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105441   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105442   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105443 }
105444         break;
105445       case 250: /* collate ::= */
105446 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
105447         break;
105448       case 252: /* cmd ::= DROP INDEX ifexists fullname */
105449 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
105450         break;
105451       case 253: /* cmd ::= VACUUM */
105452       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
105453 {sqlite3Vacuum(pParse);}
105454         break;
105455       case 255: /* cmd ::= PRAGMA nm dbnm */
105456 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
105457         break;
105458       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
105459 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
105460         break;
105461       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
105462 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
105463         break;
105464       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
105465 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
105466         break;
105467       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
105468 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
105469         break;
105470       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
105471 {
105472   Token all;
105473   all.z = yymsp[-3].minor.yy0.z;
105474   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
105475   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
105476 }
105477         break;
105478       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
105479 {
105480   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);
105481   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
105482 }
105483         break;
105484       case 272: /* trigger_time ::= BEFORE */
105485       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
105486 { yygotominor.yy4 = TK_BEFORE; }
105487         break;
105488       case 273: /* trigger_time ::= AFTER */
105489 { yygotominor.yy4 = TK_AFTER;  }
105490         break;
105491       case 274: /* trigger_time ::= INSTEAD OF */
105492 { yygotominor.yy4 = TK_INSTEAD;}
105493         break;
105494       case 276: /* trigger_event ::= DELETE|INSERT */
105495       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
105496 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
105497         break;
105498       case 278: /* trigger_event ::= UPDATE OF inscollist */
105499 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
105500         break;
105501       case 281: /* when_clause ::= */
105502       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
105503 { yygotominor.yy314 = 0; }
105504         break;
105505       case 282: /* when_clause ::= WHEN expr */
105506       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
105507 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
105508         break;
105509       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
105510 {
105511   assert( yymsp[-2].minor.yy203!=0 );
105512   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
105513   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
105514   yygotominor.yy203 = yymsp[-2].minor.yy203;
105515 }
105516         break;
105517       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
105518
105519   assert( yymsp[-1].minor.yy203!=0 );
105520   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
105521   yygotominor.yy203 = yymsp[-1].minor.yy203;
105522 }
105523         break;
105524       case 286: /* trnm ::= nm DOT nm */
105525 {
105526   yygotominor.yy0 = yymsp[0].minor.yy0;
105527   sqlite3ErrorMsg(pParse, 
105528         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
105529         "statements within triggers");
105530 }
105531         break;
105532       case 288: /* tridxby ::= INDEXED BY nm */
105533 {
105534   sqlite3ErrorMsg(pParse,
105535         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
105536         "within triggers");
105537 }
105538         break;
105539       case 289: /* tridxby ::= NOT INDEXED */
105540 {
105541   sqlite3ErrorMsg(pParse,
105542         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
105543         "within triggers");
105544 }
105545         break;
105546       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
105547 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
105548         break;
105549       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
105550 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
105551         break;
105552       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
105553 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
105554         break;
105555       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
105556 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
105557         break;
105558       case 294: /* trigger_cmd ::= select */
105559 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
105560         break;
105561       case 295: /* expr ::= RAISE LP IGNORE RP */
105562 {
105563   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
105564   if( yygotominor.yy118.pExpr ){
105565     yygotominor.yy118.pExpr->affinity = OE_Ignore;
105566   }
105567   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105568   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105569 }
105570         break;
105571       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
105572 {
105573   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
105574   if( yygotominor.yy118.pExpr ) {
105575     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
105576   }
105577   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
105578   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105579 }
105580         break;
105581       case 297: /* raisetype ::= ROLLBACK */
105582 {yygotominor.yy4 = OE_Rollback;}
105583         break;
105584       case 299: /* raisetype ::= FAIL */
105585 {yygotominor.yy4 = OE_Fail;}
105586         break;
105587       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
105588 {
105589   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
105590 }
105591         break;
105592       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
105593 {
105594   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
105595 }
105596         break;
105597       case 302: /* cmd ::= DETACH database_kw_opt expr */
105598 {
105599   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
105600 }
105601         break;
105602       case 307: /* cmd ::= REINDEX */
105603 {sqlite3Reindex(pParse, 0, 0);}
105604         break;
105605       case 308: /* cmd ::= REINDEX nm dbnm */
105606 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105607         break;
105608       case 309: /* cmd ::= ANALYZE */
105609 {sqlite3Analyze(pParse, 0, 0);}
105610         break;
105611       case 310: /* cmd ::= ANALYZE nm dbnm */
105612 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105613         break;
105614       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
105615 {
105616   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
105617 }
105618         break;
105619       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
105620 {
105621   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
105622 }
105623         break;
105624       case 313: /* add_column_fullname ::= fullname */
105625 {
105626   pParse->db->lookaside.bEnabled = 0;
105627   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
105628 }
105629         break;
105630       case 316: /* cmd ::= create_vtab */
105631 {sqlite3VtabFinishParse(pParse,0);}
105632         break;
105633       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
105634 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
105635         break;
105636       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
105637 {
105638     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
105639 }
105640         break;
105641       case 321: /* vtabarg ::= */
105642 {sqlite3VtabArgInit(pParse);}
105643         break;
105644       case 323: /* vtabargtoken ::= ANY */
105645       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
105646       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
105647 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
105648         break;
105649       default:
105650       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
105651       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
105652       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
105653       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
105654       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
105655       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
105656       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
105657       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
105658       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
105659       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
105660       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
105661       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
105662       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
105663       /* (44) type ::= */ yytestcase(yyruleno==44);
105664       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
105665       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
105666       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
105667       /* (54) carglist ::= */ yytestcase(yyruleno==54);
105668       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
105669       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
105670       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
105671       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
105672       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
105673       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
105674       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
105675       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
105676       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
105677       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
105678       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
105679       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
105680       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
105681       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
105682       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
105683       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
105684       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
105685       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
105686       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
105687       /* (326) anylist ::= */ yytestcase(yyruleno==326);
105688       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
105689       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
105690         break;
105691   };
105692   yygoto = yyRuleInfo[yyruleno].lhs;
105693   yysize = yyRuleInfo[yyruleno].nrhs;
105694   yypParser->yyidx -= yysize;
105695   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
105696   if( yyact < YYNSTATE ){
105697 #ifdef NDEBUG
105698     /* If we are not debugging and the reduce action popped at least
105699     ** one element off the stack, then we can push the new element back
105700     ** onto the stack here, and skip the stack overflow test in yy_shift().
105701     ** That gives a significant speed improvement. */
105702     if( yysize ){
105703       yypParser->yyidx++;
105704       yymsp -= yysize-1;
105705       yymsp->stateno = (YYACTIONTYPE)yyact;
105706       yymsp->major = (YYCODETYPE)yygoto;
105707       yymsp->minor = yygotominor;
105708     }else
105709 #endif
105710     {
105711       yy_shift(yypParser,yyact,yygoto,&yygotominor);
105712     }
105713   }else{
105714     assert( yyact == YYNSTATE + YYNRULE + 1 );
105715     yy_accept(yypParser);
105716   }
105717 }
105718
105719 /*
105720 ** The following code executes when the parse fails
105721 */
105722 #ifndef YYNOERRORRECOVERY
105723 static void yy_parse_failed(
105724   yyParser *yypParser           /* The parser */
105725 ){
105726   sqlite3ParserARG_FETCH;
105727 #ifndef NDEBUG
105728   if( yyTraceFILE ){
105729     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
105730   }
105731 #endif
105732   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105733   /* Here code is inserted which will be executed whenever the
105734   ** parser fails */
105735   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105736 }
105737 #endif /* YYNOERRORRECOVERY */
105738
105739 /*
105740 ** The following code executes when a syntax error first occurs.
105741 */
105742 static void yy_syntax_error(
105743   yyParser *yypParser,           /* The parser */
105744   int yymajor,                   /* The major type of the error token */
105745   YYMINORTYPE yyminor            /* The minor type of the error token */
105746 ){
105747   sqlite3ParserARG_FETCH;
105748 #define TOKEN (yyminor.yy0)
105749
105750   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
105751   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
105752   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
105753   pParse->parseError = 1;
105754   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105755 }
105756
105757 /*
105758 ** The following is executed when the parser accepts
105759 */
105760 static void yy_accept(
105761   yyParser *yypParser           /* The parser */
105762 ){
105763   sqlite3ParserARG_FETCH;
105764 #ifndef NDEBUG
105765   if( yyTraceFILE ){
105766     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
105767   }
105768 #endif
105769   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
105770   /* Here code is inserted which will be executed whenever the
105771   ** parser accepts */
105772   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
105773 }
105774
105775 /* The main parser program.
105776 ** The first argument is a pointer to a structure obtained from
105777 ** "sqlite3ParserAlloc" which describes the current state of the parser.
105778 ** The second argument is the major token number.  The third is
105779 ** the minor token.  The fourth optional argument is whatever the
105780 ** user wants (and specified in the grammar) and is available for
105781 ** use by the action routines.
105782 **
105783 ** Inputs:
105784 ** <ul>
105785 ** <li> A pointer to the parser (an opaque structure.)
105786 ** <li> The major token number.
105787 ** <li> The minor token number.
105788 ** <li> An option argument of a grammar-specified type.
105789 ** </ul>
105790 **
105791 ** Outputs:
105792 ** None.
105793 */
105794 SQLITE_PRIVATE void sqlite3Parser(
105795   void *yyp,                   /* The parser */
105796   int yymajor,                 /* The major token code number */
105797   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
105798   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
105799 ){
105800   YYMINORTYPE yyminorunion;
105801   int yyact;            /* The parser action. */
105802   int yyendofinput;     /* True if we are at the end of input */
105803 #ifdef YYERRORSYMBOL
105804   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
105805 #endif
105806   yyParser *yypParser;  /* The parser */
105807
105808   /* (re)initialize the parser, if necessary */
105809   yypParser = (yyParser*)yyp;
105810   if( yypParser->yyidx<0 ){
105811 #if YYSTACKDEPTH<=0
105812     if( yypParser->yystksz <=0 ){
105813       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
105814       yyminorunion = yyzerominor;
105815       yyStackOverflow(yypParser, &yyminorunion);
105816       return;
105817     }
105818 #endif
105819     yypParser->yyidx = 0;
105820     yypParser->yyerrcnt = -1;
105821     yypParser->yystack[0].stateno = 0;
105822     yypParser->yystack[0].major = 0;
105823   }
105824   yyminorunion.yy0 = yyminor;
105825   yyendofinput = (yymajor==0);
105826   sqlite3ParserARG_STORE;
105827
105828 #ifndef NDEBUG
105829   if( yyTraceFILE ){
105830     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
105831   }
105832 #endif
105833
105834   do{
105835     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
105836     if( yyact<YYNSTATE ){
105837       assert( !yyendofinput );  /* Impossible to shift the $ token */
105838       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
105839       yypParser->yyerrcnt--;
105840       yymajor = YYNOCODE;
105841     }else if( yyact < YYNSTATE + YYNRULE ){
105842       yy_reduce(yypParser,yyact-YYNSTATE);
105843     }else{
105844       assert( yyact == YY_ERROR_ACTION );
105845 #ifdef YYERRORSYMBOL
105846       int yymx;
105847 #endif
105848 #ifndef NDEBUG
105849       if( yyTraceFILE ){
105850         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
105851       }
105852 #endif
105853 #ifdef YYERRORSYMBOL
105854       /* A syntax error has occurred.
105855       ** The response to an error depends upon whether or not the
105856       ** grammar defines an error token "ERROR".  
105857       **
105858       ** This is what we do if the grammar does define ERROR:
105859       **
105860       **  * Call the %syntax_error function.
105861       **
105862       **  * Begin popping the stack until we enter a state where
105863       **    it is legal to shift the error symbol, then shift
105864       **    the error symbol.
105865       **
105866       **  * Set the error count to three.
105867       **
105868       **  * Begin accepting and shifting new tokens.  No new error
105869       **    processing will occur until three tokens have been
105870       **    shifted successfully.
105871       **
105872       */
105873       if( yypParser->yyerrcnt<0 ){
105874         yy_syntax_error(yypParser,yymajor,yyminorunion);
105875       }
105876       yymx = yypParser->yystack[yypParser->yyidx].major;
105877       if( yymx==YYERRORSYMBOL || yyerrorhit ){
105878 #ifndef NDEBUG
105879         if( yyTraceFILE ){
105880           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
105881              yyTracePrompt,yyTokenName[yymajor]);
105882         }
105883 #endif
105884         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
105885         yymajor = YYNOCODE;
105886       }else{
105887          while(
105888           yypParser->yyidx >= 0 &&
105889           yymx != YYERRORSYMBOL &&
105890           (yyact = yy_find_reduce_action(
105891                         yypParser->yystack[yypParser->yyidx].stateno,
105892                         YYERRORSYMBOL)) >= YYNSTATE
105893         ){
105894           yy_pop_parser_stack(yypParser);
105895         }
105896         if( yypParser->yyidx < 0 || yymajor==0 ){
105897           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105898           yy_parse_failed(yypParser);
105899           yymajor = YYNOCODE;
105900         }else if( yymx!=YYERRORSYMBOL ){
105901           YYMINORTYPE u2;
105902           u2.YYERRSYMDT = 0;
105903           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
105904         }
105905       }
105906       yypParser->yyerrcnt = 3;
105907       yyerrorhit = 1;
105908 #elif defined(YYNOERRORRECOVERY)
105909       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
105910       ** do any kind of error recovery.  Instead, simply invoke the syntax
105911       ** error routine and continue going as if nothing had happened.
105912       **
105913       ** Applications can set this macro (for example inside %include) if
105914       ** they intend to abandon the parse upon the first syntax error seen.
105915       */
105916       yy_syntax_error(yypParser,yymajor,yyminorunion);
105917       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105918       yymajor = YYNOCODE;
105919       
105920 #else  /* YYERRORSYMBOL is not defined */
105921       /* This is what we do if the grammar does not define ERROR:
105922       **
105923       **  * Report an error message, and throw away the input token.
105924       **
105925       **  * If the input token is $, then fail the parse.
105926       **
105927       ** As before, subsequent error messages are suppressed until
105928       ** three input tokens have been successfully shifted.
105929       */
105930       if( yypParser->yyerrcnt<=0 ){
105931         yy_syntax_error(yypParser,yymajor,yyminorunion);
105932       }
105933       yypParser->yyerrcnt = 3;
105934       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
105935       if( yyendofinput ){
105936         yy_parse_failed(yypParser);
105937       }
105938       yymajor = YYNOCODE;
105939 #endif
105940     }
105941   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
105942   return;
105943 }
105944
105945 /************** End of parse.c ***********************************************/
105946 /************** Begin file tokenize.c ****************************************/
105947 /*
105948 ** 2001 September 15
105949 **
105950 ** The author disclaims copyright to this source code.  In place of
105951 ** a legal notice, here is a blessing:
105952 **
105953 **    May you do good and not evil.
105954 **    May you find forgiveness for yourself and forgive others.
105955 **    May you share freely, never taking more than you give.
105956 **
105957 *************************************************************************
105958 ** An tokenizer for SQL
105959 **
105960 ** This file contains C code that splits an SQL input string up into
105961 ** individual tokens and sends those tokens one-by-one over to the
105962 ** parser for analysis.
105963 */
105964
105965 /*
105966 ** The charMap() macro maps alphabetic characters into their
105967 ** lower-case ASCII equivalent.  On ASCII machines, this is just
105968 ** an upper-to-lower case map.  On EBCDIC machines we also need
105969 ** to adjust the encoding.  Only alphabetic characters and underscores
105970 ** need to be translated.
105971 */
105972 #ifdef SQLITE_ASCII
105973 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
105974 #endif
105975 #ifdef SQLITE_EBCDIC
105976 # define charMap(X) ebcdicToAscii[(unsigned char)X]
105977 const unsigned char ebcdicToAscii[] = {
105978 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
105979    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
105980    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
105981    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
105982    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
105983    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
105984    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
105985    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
105986    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
105987    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
105988    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
105989    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
105990    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
105991    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
105992    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
105993    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
105994    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
105995 };
105996 #endif
105997
105998 /*
105999 ** The sqlite3KeywordCode function looks up an identifier to determine if
106000 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
106001 ** returned.  If the input is not a keyword, TK_ID is returned.
106002 **
106003 ** The implementation of this routine was generated by a program,
106004 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
106005 ** The output of the mkkeywordhash.c program is written into a file
106006 ** named keywordhash.h and then included into this source file by
106007 ** the #include below.
106008 */
106009 /************** Include keywordhash.h in the middle of tokenize.c ************/
106010 /************** Begin file keywordhash.h *************************************/
106011 /***** This file contains automatically generated code ******
106012 **
106013 ** The code in this file has been automatically generated by
106014 **
106015 **   sqlite/tool/mkkeywordhash.c
106016 **
106017 ** The code in this file implements a function that determines whether
106018 ** or not a given identifier is really an SQL keyword.  The same thing
106019 ** might be implemented more directly using a hand-written hash table.
106020 ** But by using this automatically generated code, the size of the code
106021 ** is substantially reduced.  This is important for embedded applications
106022 ** on platforms with limited memory.
106023 */
106024 /* Hash score: 175 */
106025 static int keywordCode(const char *z, int n){
106026   /* zText[] encodes 811 bytes of keywords in 541 bytes */
106027   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
106028   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
106029   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
106030   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
106031   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
106032   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
106033   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
106034   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
106035   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
106036   /*   INITIALLY                                                          */
106037   static const char zText[540] = {
106038     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106039     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106040     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106041     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106042     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106043     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106044     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106045     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106046     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106047     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106048     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106049     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106050     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106051     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106052     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106053     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106054     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106055     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106056     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106057     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106058     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106059     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106060     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106061     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106062     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106063     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106064     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106065     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106066     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106067     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106068   };
106069   static const unsigned char aHash[127] = {
106070       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
106071       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
106072      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
106073        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
106074        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
106075       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
106076       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
106077       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
106078       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
106079       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
106080   };
106081   static const unsigned char aNext[121] = {
106082        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
106083        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
106084        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
106085        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
106086        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
106087       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
106088       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
106089        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
106090      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
106091       35,  64,   0,   0,
106092   };
106093   static const unsigned char aLen[121] = {
106094        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
106095        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
106096       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
106097        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
106098        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
106099        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
106100        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
106101        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
106102        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
106103        6,   4,   9,   3,
106104   };
106105   static const unsigned short int aOffset[121] = {
106106        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
106107       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
106108       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106109      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106110      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106111      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106112      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106113      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106114      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106115      521, 527, 531, 536,
106116   };
106117   static const unsigned char aCode[121] = {
106118     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
106119     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
106120     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
106121     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
106122     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
106123     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
106124     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
106125     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
106126     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
106127     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
106128     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
106129     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
106130     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
106131     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
106132     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
106133     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
106134     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
106135     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
106136     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
106137     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
106138     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
106139     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
106140     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
106141     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
106142     TK_ALL,        
106143   };
106144   int h, i;
106145   if( n<2 ) return TK_ID;
106146   h = ((charMap(z[0])*4) ^
106147       (charMap(z[n-1])*3) ^
106148       n) % 127;
106149   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106150     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106151       testcase( i==0 ); /* REINDEX */
106152       testcase( i==1 ); /* INDEXED */
106153       testcase( i==2 ); /* INDEX */
106154       testcase( i==3 ); /* DESC */
106155       testcase( i==4 ); /* ESCAPE */
106156       testcase( i==5 ); /* EACH */
106157       testcase( i==6 ); /* CHECK */
106158       testcase( i==7 ); /* KEY */
106159       testcase( i==8 ); /* BEFORE */
106160       testcase( i==9 ); /* FOREIGN */
106161       testcase( i==10 ); /* FOR */
106162       testcase( i==11 ); /* IGNORE */
106163       testcase( i==12 ); /* REGEXP */
106164       testcase( i==13 ); /* EXPLAIN */
106165       testcase( i==14 ); /* INSTEAD */
106166       testcase( i==15 ); /* ADD */
106167       testcase( i==16 ); /* DATABASE */
106168       testcase( i==17 ); /* AS */
106169       testcase( i==18 ); /* SELECT */
106170       testcase( i==19 ); /* TABLE */
106171       testcase( i==20 ); /* LEFT */
106172       testcase( i==21 ); /* THEN */
106173       testcase( i==22 ); /* END */
106174       testcase( i==23 ); /* DEFERRABLE */
106175       testcase( i==24 ); /* ELSE */
106176       testcase( i==25 ); /* EXCEPT */
106177       testcase( i==26 ); /* TRANSACTION */
106178       testcase( i==27 ); /* ACTION */
106179       testcase( i==28 ); /* ON */
106180       testcase( i==29 ); /* NATURAL */
106181       testcase( i==30 ); /* ALTER */
106182       testcase( i==31 ); /* RAISE */
106183       testcase( i==32 ); /* EXCLUSIVE */
106184       testcase( i==33 ); /* EXISTS */
106185       testcase( i==34 ); /* SAVEPOINT */
106186       testcase( i==35 ); /* INTERSECT */
106187       testcase( i==36 ); /* TRIGGER */
106188       testcase( i==37 ); /* REFERENCES */
106189       testcase( i==38 ); /* CONSTRAINT */
106190       testcase( i==39 ); /* INTO */
106191       testcase( i==40 ); /* OFFSET */
106192       testcase( i==41 ); /* OF */
106193       testcase( i==42 ); /* SET */
106194       testcase( i==43 ); /* TEMPORARY */
106195       testcase( i==44 ); /* TEMP */
106196       testcase( i==45 ); /* OR */
106197       testcase( i==46 ); /* UNIQUE */
106198       testcase( i==47 ); /* QUERY */
106199       testcase( i==48 ); /* ATTACH */
106200       testcase( i==49 ); /* HAVING */
106201       testcase( i==50 ); /* GROUP */
106202       testcase( i==51 ); /* UPDATE */
106203       testcase( i==52 ); /* BEGIN */
106204       testcase( i==53 ); /* INNER */
106205       testcase( i==54 ); /* RELEASE */
106206       testcase( i==55 ); /* BETWEEN */
106207       testcase( i==56 ); /* NOTNULL */
106208       testcase( i==57 ); /* NOT */
106209       testcase( i==58 ); /* NO */
106210       testcase( i==59 ); /* NULL */
106211       testcase( i==60 ); /* LIKE */
106212       testcase( i==61 ); /* CASCADE */
106213       testcase( i==62 ); /* ASC */
106214       testcase( i==63 ); /* DELETE */
106215       testcase( i==64 ); /* CASE */
106216       testcase( i==65 ); /* COLLATE */
106217       testcase( i==66 ); /* CREATE */
106218       testcase( i==67 ); /* CURRENT_DATE */
106219       testcase( i==68 ); /* DETACH */
106220       testcase( i==69 ); /* IMMEDIATE */
106221       testcase( i==70 ); /* JOIN */
106222       testcase( i==71 ); /* INSERT */
106223       testcase( i==72 ); /* MATCH */
106224       testcase( i==73 ); /* PLAN */
106225       testcase( i==74 ); /* ANALYZE */
106226       testcase( i==75 ); /* PRAGMA */
106227       testcase( i==76 ); /* ABORT */
106228       testcase( i==77 ); /* VALUES */
106229       testcase( i==78 ); /* VIRTUAL */
106230       testcase( i==79 ); /* LIMIT */
106231       testcase( i==80 ); /* WHEN */
106232       testcase( i==81 ); /* WHERE */
106233       testcase( i==82 ); /* RENAME */
106234       testcase( i==83 ); /* AFTER */
106235       testcase( i==84 ); /* REPLACE */
106236       testcase( i==85 ); /* AND */
106237       testcase( i==86 ); /* DEFAULT */
106238       testcase( i==87 ); /* AUTOINCREMENT */
106239       testcase( i==88 ); /* TO */
106240       testcase( i==89 ); /* IN */
106241       testcase( i==90 ); /* CAST */
106242       testcase( i==91 ); /* COLUMN */
106243       testcase( i==92 ); /* COMMIT */
106244       testcase( i==93 ); /* CONFLICT */
106245       testcase( i==94 ); /* CROSS */
106246       testcase( i==95 ); /* CURRENT_TIMESTAMP */
106247       testcase( i==96 ); /* CURRENT_TIME */
106248       testcase( i==97 ); /* PRIMARY */
106249       testcase( i==98 ); /* DEFERRED */
106250       testcase( i==99 ); /* DISTINCT */
106251       testcase( i==100 ); /* IS */
106252       testcase( i==101 ); /* DROP */
106253       testcase( i==102 ); /* FAIL */
106254       testcase( i==103 ); /* FROM */
106255       testcase( i==104 ); /* FULL */
106256       testcase( i==105 ); /* GLOB */
106257       testcase( i==106 ); /* BY */
106258       testcase( i==107 ); /* IF */
106259       testcase( i==108 ); /* ISNULL */
106260       testcase( i==109 ); /* ORDER */
106261       testcase( i==110 ); /* RESTRICT */
106262       testcase( i==111 ); /* OUTER */
106263       testcase( i==112 ); /* RIGHT */
106264       testcase( i==113 ); /* ROLLBACK */
106265       testcase( i==114 ); /* ROW */
106266       testcase( i==115 ); /* UNION */
106267       testcase( i==116 ); /* USING */
106268       testcase( i==117 ); /* VACUUM */
106269       testcase( i==118 ); /* VIEW */
106270       testcase( i==119 ); /* INITIALLY */
106271       testcase( i==120 ); /* ALL */
106272       return aCode[i];
106273     }
106274   }
106275   return TK_ID;
106276 }
106277 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
106278   return keywordCode((char*)z, n);
106279 }
106280 #define SQLITE_N_KEYWORD 121
106281
106282 /************** End of keywordhash.h *****************************************/
106283 /************** Continuing where we left off in tokenize.c *******************/
106284
106285
106286 /*
106287 ** If X is a character that can be used in an identifier then
106288 ** IdChar(X) will be true.  Otherwise it is false.
106289 **
106290 ** For ASCII, any character with the high-order bit set is
106291 ** allowed in an identifier.  For 7-bit characters, 
106292 ** sqlite3IsIdChar[X] must be 1.
106293 **
106294 ** For EBCDIC, the rules are more complex but have the same
106295 ** end result.
106296 **
106297 ** Ticket #1066.  the SQL standard does not allow '$' in the
106298 ** middle of identfiers.  But many SQL implementations do. 
106299 ** SQLite will allow '$' in identifiers for compatibility.
106300 ** But the feature is undocumented.
106301 */
106302 #ifdef SQLITE_ASCII
106303 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106304 #endif
106305 #ifdef SQLITE_EBCDIC
106306 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
106307 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
106308     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
106309     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
106310     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
106311     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
106312     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
106313     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
106314     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
106315     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
106316     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
106317     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
106318     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
106319     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
106320 };
106321 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106322 #endif
106323
106324
106325 /*
106326 ** Return the length of the token that begins at z[0]. 
106327 ** Store the token type in *tokenType before returning.
106328 */
106329 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
106330   int i, c;
106331   switch( *z ){
106332     case ' ': case '\t': case '\n': case '\f': case '\r': {
106333       testcase( z[0]==' ' );
106334       testcase( z[0]=='\t' );
106335       testcase( z[0]=='\n' );
106336       testcase( z[0]=='\f' );
106337       testcase( z[0]=='\r' );
106338       for(i=1; sqlite3Isspace(z[i]); i++){}
106339       *tokenType = TK_SPACE;
106340       return i;
106341     }
106342     case '-': {
106343       if( z[1]=='-' ){
106344         /* IMP: R-15891-05542 -- syntax diagram for comments */
106345         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
106346         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106347         return i;
106348       }
106349       *tokenType = TK_MINUS;
106350       return 1;
106351     }
106352     case '(': {
106353       *tokenType = TK_LP;
106354       return 1;
106355     }
106356     case ')': {
106357       *tokenType = TK_RP;
106358       return 1;
106359     }
106360     case ';': {
106361       *tokenType = TK_SEMI;
106362       return 1;
106363     }
106364     case '+': {
106365       *tokenType = TK_PLUS;
106366       return 1;
106367     }
106368     case '*': {
106369       *tokenType = TK_STAR;
106370       return 1;
106371     }
106372     case '/': {
106373       if( z[1]!='*' || z[2]==0 ){
106374         *tokenType = TK_SLASH;
106375         return 1;
106376       }
106377       /* IMP: R-15891-05542 -- syntax diagram for comments */
106378       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
106379       if( c ) i++;
106380       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
106381       return i;
106382     }
106383     case '%': {
106384       *tokenType = TK_REM;
106385       return 1;
106386     }
106387     case '=': {
106388       *tokenType = TK_EQ;
106389       return 1 + (z[1]=='=');
106390     }
106391     case '<': {
106392       if( (c=z[1])=='=' ){
106393         *tokenType = TK_LE;
106394         return 2;
106395       }else if( c=='>' ){
106396         *tokenType = TK_NE;
106397         return 2;
106398       }else if( c=='<' ){
106399         *tokenType = TK_LSHIFT;
106400         return 2;
106401       }else{
106402         *tokenType = TK_LT;
106403         return 1;
106404       }
106405     }
106406     case '>': {
106407       if( (c=z[1])=='=' ){
106408         *tokenType = TK_GE;
106409         return 2;
106410       }else if( c=='>' ){
106411         *tokenType = TK_RSHIFT;
106412         return 2;
106413       }else{
106414         *tokenType = TK_GT;
106415         return 1;
106416       }
106417     }
106418     case '!': {
106419       if( z[1]!='=' ){
106420         *tokenType = TK_ILLEGAL;
106421         return 2;
106422       }else{
106423         *tokenType = TK_NE;
106424         return 2;
106425       }
106426     }
106427     case '|': {
106428       if( z[1]!='|' ){
106429         *tokenType = TK_BITOR;
106430         return 1;
106431       }else{
106432         *tokenType = TK_CONCAT;
106433         return 2;
106434       }
106435     }
106436     case ',': {
106437       *tokenType = TK_COMMA;
106438       return 1;
106439     }
106440     case '&': {
106441       *tokenType = TK_BITAND;
106442       return 1;
106443     }
106444     case '~': {
106445       *tokenType = TK_BITNOT;
106446       return 1;
106447     }
106448     case '`':
106449     case '\'':
106450     case '"': {
106451       int delim = z[0];
106452       testcase( delim=='`' );
106453       testcase( delim=='\'' );
106454       testcase( delim=='"' );
106455       for(i=1; (c=z[i])!=0; i++){
106456         if( c==delim ){
106457           if( z[i+1]==delim ){
106458             i++;
106459           }else{
106460             break;
106461           }
106462         }
106463       }
106464       if( c=='\'' ){
106465         *tokenType = TK_STRING;
106466         return i+1;
106467       }else if( c!=0 ){
106468         *tokenType = TK_ID;
106469         return i+1;
106470       }else{
106471         *tokenType = TK_ILLEGAL;
106472         return i;
106473       }
106474     }
106475     case '.': {
106476 #ifndef SQLITE_OMIT_FLOATING_POINT
106477       if( !sqlite3Isdigit(z[1]) )
106478 #endif
106479       {
106480         *tokenType = TK_DOT;
106481         return 1;
106482       }
106483       /* If the next character is a digit, this is a floating point
106484       ** number that begins with ".".  Fall thru into the next case */
106485     }
106486     case '0': case '1': case '2': case '3': case '4':
106487     case '5': case '6': case '7': case '8': case '9': {
106488       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
106489       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
106490       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
106491       testcase( z[0]=='9' );
106492       *tokenType = TK_INTEGER;
106493       for(i=0; sqlite3Isdigit(z[i]); i++){}
106494 #ifndef SQLITE_OMIT_FLOATING_POINT
106495       if( z[i]=='.' ){
106496         i++;
106497         while( sqlite3Isdigit(z[i]) ){ i++; }
106498         *tokenType = TK_FLOAT;
106499       }
106500       if( (z[i]=='e' || z[i]=='E') &&
106501            ( sqlite3Isdigit(z[i+1]) 
106502             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
106503            )
106504       ){
106505         i += 2;
106506         while( sqlite3Isdigit(z[i]) ){ i++; }
106507         *tokenType = TK_FLOAT;
106508       }
106509 #endif
106510       while( IdChar(z[i]) ){
106511         *tokenType = TK_ILLEGAL;
106512         i++;
106513       }
106514       return i;
106515     }
106516     case '[': {
106517       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
106518       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
106519       return i;
106520     }
106521     case '?': {
106522       *tokenType = TK_VARIABLE;
106523       for(i=1; sqlite3Isdigit(z[i]); i++){}
106524       return i;
106525     }
106526     case '#': {
106527       for(i=1; sqlite3Isdigit(z[i]); i++){}
106528       if( i>1 ){
106529         /* Parameters of the form #NNN (where NNN is a number) are used
106530         ** internally by sqlite3NestedParse.  */
106531         *tokenType = TK_REGISTER;
106532         return i;
106533       }
106534       /* Fall through into the next case if the '#' is not followed by
106535       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
106536     }
106537 #ifndef SQLITE_OMIT_TCL_VARIABLE
106538     case '$':
106539 #endif
106540     case '@':  /* For compatibility with MS SQL Server */
106541     case ':': {
106542       int n = 0;
106543       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
106544       *tokenType = TK_VARIABLE;
106545       for(i=1; (c=z[i])!=0; i++){
106546         if( IdChar(c) ){
106547           n++;
106548 #ifndef SQLITE_OMIT_TCL_VARIABLE
106549         }else if( c=='(' && n>0 ){
106550           do{
106551             i++;
106552           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
106553           if( c==')' ){
106554             i++;
106555           }else{
106556             *tokenType = TK_ILLEGAL;
106557           }
106558           break;
106559         }else if( c==':' && z[i+1]==':' ){
106560           i++;
106561 #endif
106562         }else{
106563           break;
106564         }
106565       }
106566       if( n==0 ) *tokenType = TK_ILLEGAL;
106567       return i;
106568     }
106569 #ifndef SQLITE_OMIT_BLOB_LITERAL
106570     case 'x': case 'X': {
106571       testcase( z[0]=='x' ); testcase( z[0]=='X' );
106572       if( z[1]=='\'' ){
106573         *tokenType = TK_BLOB;
106574         for(i=2; (c=z[i])!=0 && c!='\''; i++){
106575           if( !sqlite3Isxdigit(c) ){
106576             *tokenType = TK_ILLEGAL;
106577           }
106578         }
106579         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
106580         if( c ) i++;
106581         return i;
106582       }
106583       /* Otherwise fall through to the next case */
106584     }
106585 #endif
106586     default: {
106587       if( !IdChar(*z) ){
106588         break;
106589       }
106590       for(i=1; IdChar(z[i]); i++){}
106591       *tokenType = keywordCode((char*)z, i);
106592       return i;
106593     }
106594   }
106595   *tokenType = TK_ILLEGAL;
106596   return 1;
106597 }
106598
106599 /*
106600 ** Run the parser on the given SQL string.  The parser structure is
106601 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
106602 ** then an and attempt is made to write an error message into 
106603 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
106604 ** error message.
106605 */
106606 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
106607   int nErr = 0;                   /* Number of errors encountered */
106608   int i;                          /* Loop counter */
106609   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
106610   int tokenType;                  /* type of the next token */
106611   int lastTokenParsed = -1;       /* type of the previous token */
106612   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
106613   sqlite3 *db = pParse->db;       /* The database connection */
106614   int mxSqlLen;                   /* Max length of an SQL string */
106615
106616
106617   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106618   if( db->activeVdbeCnt==0 ){
106619     db->u1.isInterrupted = 0;
106620   }
106621   pParse->rc = SQLITE_OK;
106622   pParse->zTail = zSql;
106623   i = 0;
106624   assert( pzErrMsg!=0 );
106625   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
106626   if( pEngine==0 ){
106627     db->mallocFailed = 1;
106628     return SQLITE_NOMEM;
106629   }
106630   assert( pParse->pNewTable==0 );
106631   assert( pParse->pNewTrigger==0 );
106632   assert( pParse->nVar==0 );
106633   assert( pParse->nVarExpr==0 );
106634   assert( pParse->nVarExprAlloc==0 );
106635   assert( pParse->apVarExpr==0 );
106636   enableLookaside = db->lookaside.bEnabled;
106637   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
106638   while( !db->mallocFailed && zSql[i]!=0 ){
106639     assert( i>=0 );
106640     pParse->sLastToken.z = &zSql[i];
106641     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
106642     i += pParse->sLastToken.n;
106643     if( i>mxSqlLen ){
106644       pParse->rc = SQLITE_TOOBIG;
106645       break;
106646     }
106647     switch( tokenType ){
106648       case TK_SPACE: {
106649         if( db->u1.isInterrupted ){
106650           sqlite3ErrorMsg(pParse, "interrupt");
106651           pParse->rc = SQLITE_INTERRUPT;
106652           goto abort_parse;
106653         }
106654         break;
106655       }
106656       case TK_ILLEGAL: {
106657         sqlite3DbFree(db, *pzErrMsg);
106658         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
106659                         &pParse->sLastToken);
106660         nErr++;
106661         goto abort_parse;
106662       }
106663       case TK_SEMI: {
106664         pParse->zTail = &zSql[i];
106665         /* Fall thru into the default case */
106666       }
106667       default: {
106668         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
106669         lastTokenParsed = tokenType;
106670         if( pParse->rc!=SQLITE_OK ){
106671           goto abort_parse;
106672         }
106673         break;
106674       }
106675     }
106676   }
106677 abort_parse:
106678   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
106679     if( lastTokenParsed!=TK_SEMI ){
106680       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
106681       pParse->zTail = &zSql[i];
106682     }
106683     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
106684   }
106685 #ifdef YYTRACKMAXSTACKDEPTH
106686   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
106687       sqlite3ParserStackPeak(pEngine)
106688   );
106689 #endif /* YYDEBUG */
106690   sqlite3ParserFree(pEngine, sqlite3_free);
106691   db->lookaside.bEnabled = enableLookaside;
106692   if( db->mallocFailed ){
106693     pParse->rc = SQLITE_NOMEM;
106694   }
106695   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
106696     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
106697   }
106698   assert( pzErrMsg!=0 );
106699   if( pParse->zErrMsg ){
106700     *pzErrMsg = pParse->zErrMsg;
106701     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
106702     pParse->zErrMsg = 0;
106703     nErr++;
106704   }
106705   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
106706     sqlite3VdbeDelete(pParse->pVdbe);
106707     pParse->pVdbe = 0;
106708   }
106709 #ifndef SQLITE_OMIT_SHARED_CACHE
106710   if( pParse->nested==0 ){
106711     sqlite3DbFree(db, pParse->aTableLock);
106712     pParse->aTableLock = 0;
106713     pParse->nTableLock = 0;
106714   }
106715 #endif
106716 #ifndef SQLITE_OMIT_VIRTUALTABLE
106717   sqlite3_free(pParse->apVtabLock);
106718 #endif
106719
106720   if( !IN_DECLARE_VTAB ){
106721     /* If the pParse->declareVtab flag is set, do not delete any table 
106722     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
106723     ** will take responsibility for freeing the Table structure.
106724     */
106725     sqlite3DeleteTable(db, pParse->pNewTable);
106726   }
106727
106728   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
106729   sqlite3DbFree(db, pParse->apVarExpr);
106730   sqlite3DbFree(db, pParse->aAlias);
106731   while( pParse->pAinc ){
106732     AutoincInfo *p = pParse->pAinc;
106733     pParse->pAinc = p->pNext;
106734     sqlite3DbFree(db, p);
106735   }
106736   while( pParse->pZombieTab ){
106737     Table *p = pParse->pZombieTab;
106738     pParse->pZombieTab = p->pNextZombie;
106739     sqlite3DeleteTable(db, p);
106740   }
106741   if( nErr>0 && pParse->rc==SQLITE_OK ){
106742     pParse->rc = SQLITE_ERROR;
106743   }
106744   return nErr;
106745 }
106746
106747 /************** End of tokenize.c ********************************************/
106748 /************** Begin file complete.c ****************************************/
106749 /*
106750 ** 2001 September 15
106751 **
106752 ** The author disclaims copyright to this source code.  In place of
106753 ** a legal notice, here is a blessing:
106754 **
106755 **    May you do good and not evil.
106756 **    May you find forgiveness for yourself and forgive others.
106757 **    May you share freely, never taking more than you give.
106758 **
106759 *************************************************************************
106760 ** An tokenizer for SQL
106761 **
106762 ** This file contains C code that implements the sqlite3_complete() API.
106763 ** This code used to be part of the tokenizer.c source file.  But by
106764 ** separating it out, the code will be automatically omitted from
106765 ** static links that do not use it.
106766 */
106767 #ifndef SQLITE_OMIT_COMPLETE
106768
106769 /*
106770 ** This is defined in tokenize.c.  We just have to import the definition.
106771 */
106772 #ifndef SQLITE_AMALGAMATION
106773 #ifdef SQLITE_ASCII
106774 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106775 #endif
106776 #ifdef SQLITE_EBCDIC
106777 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
106778 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106779 #endif
106780 #endif /* SQLITE_AMALGAMATION */
106781
106782
106783 /*
106784 ** Token types used by the sqlite3_complete() routine.  See the header
106785 ** comments on that procedure for additional information.
106786 */
106787 #define tkSEMI    0
106788 #define tkWS      1
106789 #define tkOTHER   2
106790 #ifndef SQLITE_OMIT_TRIGGER
106791 #define tkEXPLAIN 3
106792 #define tkCREATE  4
106793 #define tkTEMP    5
106794 #define tkTRIGGER 6
106795 #define tkEND     7
106796 #endif
106797
106798 /*
106799 ** Return TRUE if the given SQL string ends in a semicolon.
106800 **
106801 ** Special handling is require for CREATE TRIGGER statements.
106802 ** Whenever the CREATE TRIGGER keywords are seen, the statement
106803 ** must end with ";END;".
106804 **
106805 ** This implementation uses a state machine with 8 states:
106806 **
106807 **   (0) INVALID   We have not yet seen a non-whitespace character.
106808 **
106809 **   (1) START     At the beginning or end of an SQL statement.  This routine
106810 **                 returns 1 if it ends in the START state and 0 if it ends
106811 **                 in any other state.
106812 **
106813 **   (2) NORMAL    We are in the middle of statement which ends with a single
106814 **                 semicolon.
106815 **
106816 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
106817 **                 a statement.
106818 **
106819 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
106820 **                 statement, possibly preceeded by EXPLAIN and/or followed by
106821 **                 TEMP or TEMPORARY
106822 **
106823 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
106824 **                 ended by a semicolon, the keyword END, and another semicolon.
106825 **
106826 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
106827 **                 the end of a trigger definition.
106828 **
106829 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
106830 **                 of a trigger difinition.
106831 **
106832 ** Transitions between states above are determined by tokens extracted
106833 ** from the input.  The following tokens are significant:
106834 **
106835 **   (0) tkSEMI      A semicolon.
106836 **   (1) tkWS        Whitespace.
106837 **   (2) tkOTHER     Any other SQL token.
106838 **   (3) tkEXPLAIN   The "explain" keyword.
106839 **   (4) tkCREATE    The "create" keyword.
106840 **   (5) tkTEMP      The "temp" or "temporary" keyword.
106841 **   (6) tkTRIGGER   The "trigger" keyword.
106842 **   (7) tkEND       The "end" keyword.
106843 **
106844 ** Whitespace never causes a state transition and is always ignored.
106845 ** This means that a SQL string of all whitespace is invalid.
106846 **
106847 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
106848 ** to recognize the end of a trigger can be omitted.  All we have to do
106849 ** is look for a semicolon that is not part of an string or comment.
106850 */
106851 SQLITE_API int sqlite3_complete(const char *zSql){
106852   u8 state = 0;   /* Current state, using numbers defined in header comment */
106853   u8 token;       /* Value of the next token */
106854
106855 #ifndef SQLITE_OMIT_TRIGGER
106856   /* A complex statement machine used to detect the end of a CREATE TRIGGER
106857   ** statement.  This is the normal case.
106858   */
106859   static const u8 trans[8][8] = {
106860                      /* Token:                                                */
106861      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
106862      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
106863      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
106864      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
106865      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
106866      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
106867      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
106868      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
106869      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
106870   };
106871 #else
106872   /* If triggers are not supported by this compile then the statement machine
106873   ** used to detect the end of a statement is much simplier
106874   */
106875   static const u8 trans[3][3] = {
106876                      /* Token:           */
106877      /* State:       **  SEMI  WS  OTHER */
106878      /* 0 INVALID: */ {    1,  0,     2, },
106879      /* 1   START: */ {    1,  1,     2, },
106880      /* 2  NORMAL: */ {    1,  2,     2, },
106881   };
106882 #endif /* SQLITE_OMIT_TRIGGER */
106883
106884   while( *zSql ){
106885     switch( *zSql ){
106886       case ';': {  /* A semicolon */
106887         token = tkSEMI;
106888         break;
106889       }
106890       case ' ':
106891       case '\r':
106892       case '\t':
106893       case '\n':
106894       case '\f': {  /* White space is ignored */
106895         token = tkWS;
106896         break;
106897       }
106898       case '/': {   /* C-style comments */
106899         if( zSql[1]!='*' ){
106900           token = tkOTHER;
106901           break;
106902         }
106903         zSql += 2;
106904         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
106905         if( zSql[0]==0 ) return 0;
106906         zSql++;
106907         token = tkWS;
106908         break;
106909       }
106910       case '-': {   /* SQL-style comments from "--" to end of line */
106911         if( zSql[1]!='-' ){
106912           token = tkOTHER;
106913           break;
106914         }
106915         while( *zSql && *zSql!='\n' ){ zSql++; }
106916         if( *zSql==0 ) return state==1;
106917         token = tkWS;
106918         break;
106919       }
106920       case '[': {   /* Microsoft-style identifiers in [...] */
106921         zSql++;
106922         while( *zSql && *zSql!=']' ){ zSql++; }
106923         if( *zSql==0 ) return 0;
106924         token = tkOTHER;
106925         break;
106926       }
106927       case '`':     /* Grave-accent quoted symbols used by MySQL */
106928       case '"':     /* single- and double-quoted strings */
106929       case '\'': {
106930         int c = *zSql;
106931         zSql++;
106932         while( *zSql && *zSql!=c ){ zSql++; }
106933         if( *zSql==0 ) return 0;
106934         token = tkOTHER;
106935         break;
106936       }
106937       default: {
106938 #ifdef SQLITE_EBCDIC
106939         unsigned char c;
106940 #endif
106941         if( IdChar((u8)*zSql) ){
106942           /* Keywords and unquoted identifiers */
106943           int nId;
106944           for(nId=1; IdChar(zSql[nId]); nId++){}
106945 #ifdef SQLITE_OMIT_TRIGGER
106946           token = tkOTHER;
106947 #else
106948           switch( *zSql ){
106949             case 'c': case 'C': {
106950               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
106951                 token = tkCREATE;
106952               }else{
106953                 token = tkOTHER;
106954               }
106955               break;
106956             }
106957             case 't': case 'T': {
106958               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
106959                 token = tkTRIGGER;
106960               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
106961                 token = tkTEMP;
106962               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
106963                 token = tkTEMP;
106964               }else{
106965                 token = tkOTHER;
106966               }
106967               break;
106968             }
106969             case 'e':  case 'E': {
106970               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
106971                 token = tkEND;
106972               }else
106973 #ifndef SQLITE_OMIT_EXPLAIN
106974               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
106975                 token = tkEXPLAIN;
106976               }else
106977 #endif
106978               {
106979                 token = tkOTHER;
106980               }
106981               break;
106982             }
106983             default: {
106984               token = tkOTHER;
106985               break;
106986             }
106987           }
106988 #endif /* SQLITE_OMIT_TRIGGER */
106989           zSql += nId-1;
106990         }else{
106991           /* Operators and special symbols */
106992           token = tkOTHER;
106993         }
106994         break;
106995       }
106996     }
106997     state = trans[state][token];
106998     zSql++;
106999   }
107000   return state==1;
107001 }
107002
107003 #ifndef SQLITE_OMIT_UTF16
107004 /*
107005 ** This routine is the same as the sqlite3_complete() routine described
107006 ** above, except that the parameter is required to be UTF-16 encoded, not
107007 ** UTF-8.
107008 */
107009 SQLITE_API int sqlite3_complete16(const void *zSql){
107010   sqlite3_value *pVal;
107011   char const *zSql8;
107012   int rc = SQLITE_NOMEM;
107013
107014 #ifndef SQLITE_OMIT_AUTOINIT
107015   rc = sqlite3_initialize();
107016   if( rc ) return rc;
107017 #endif
107018   pVal = sqlite3ValueNew(0);
107019   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107020   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107021   if( zSql8 ){
107022     rc = sqlite3_complete(zSql8);
107023   }else{
107024     rc = SQLITE_NOMEM;
107025   }
107026   sqlite3ValueFree(pVal);
107027   return sqlite3ApiExit(0, rc);
107028 }
107029 #endif /* SQLITE_OMIT_UTF16 */
107030 #endif /* SQLITE_OMIT_COMPLETE */
107031
107032 /************** End of complete.c ********************************************/
107033 /************** Begin file main.c ********************************************/
107034 /*
107035 ** 2001 September 15
107036 **
107037 ** The author disclaims copyright to this source code.  In place of
107038 ** a legal notice, here is a blessing:
107039 **
107040 **    May you do good and not evil.
107041 **    May you find forgiveness for yourself and forgive others.
107042 **    May you share freely, never taking more than you give.
107043 **
107044 *************************************************************************
107045 ** Main file for the SQLite library.  The routines in this file
107046 ** implement the programmer interface to the library.  Routines in
107047 ** other files are for internal use by SQLite and should not be
107048 ** accessed by users of the library.
107049 */
107050
107051 #ifdef SQLITE_ENABLE_FTS3
107052 /************** Include fts3.h in the middle of main.c ***********************/
107053 /************** Begin file fts3.h ********************************************/
107054 /*
107055 ** 2006 Oct 10
107056 **
107057 ** The author disclaims copyright to this source code.  In place of
107058 ** a legal notice, here is a blessing:
107059 **
107060 **    May you do good and not evil.
107061 **    May you find forgiveness for yourself and forgive others.
107062 **    May you share freely, never taking more than you give.
107063 **
107064 ******************************************************************************
107065 **
107066 ** This header file is used by programs that want to link against the
107067 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
107068 */
107069
107070 #if 0
107071 extern "C" {
107072 #endif  /* __cplusplus */
107073
107074 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107075
107076 #if 0
107077 }  /* extern "C" */
107078 #endif  /* __cplusplus */
107079
107080 /************** End of fts3.h ************************************************/
107081 /************** Continuing where we left off in main.c ***********************/
107082 #endif
107083 #ifdef SQLITE_ENABLE_RTREE
107084 /************** Include rtree.h in the middle of main.c **********************/
107085 /************** Begin file rtree.h *******************************************/
107086 /*
107087 ** 2008 May 26
107088 **
107089 ** The author disclaims copyright to this source code.  In place of
107090 ** a legal notice, here is a blessing:
107091 **
107092 **    May you do good and not evil.
107093 **    May you find forgiveness for yourself and forgive others.
107094 **    May you share freely, never taking more than you give.
107095 **
107096 ******************************************************************************
107097 **
107098 ** This header file is used by programs that want to link against the
107099 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
107100 */
107101
107102 #if 0
107103 extern "C" {
107104 #endif  /* __cplusplus */
107105
107106 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107107
107108 #if 0
107109 }  /* extern "C" */
107110 #endif  /* __cplusplus */
107111
107112 /************** End of rtree.h ***********************************************/
107113 /************** Continuing where we left off in main.c ***********************/
107114 #endif
107115 #ifdef SQLITE_ENABLE_ICU
107116 /************** Include sqliteicu.h in the middle of main.c ******************/
107117 /************** Begin file sqliteicu.h ***************************************/
107118 /*
107119 ** 2008 May 26
107120 **
107121 ** The author disclaims copyright to this source code.  In place of
107122 ** a legal notice, here is a blessing:
107123 **
107124 **    May you do good and not evil.
107125 **    May you find forgiveness for yourself and forgive others.
107126 **    May you share freely, never taking more than you give.
107127 **
107128 ******************************************************************************
107129 **
107130 ** This header file is used by programs that want to link against the
107131 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
107132 */
107133
107134 #if 0
107135 extern "C" {
107136 #endif  /* __cplusplus */
107137
107138 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107139
107140 #if 0
107141 }  /* extern "C" */
107142 #endif  /* __cplusplus */
107143
107144
107145 /************** End of sqliteicu.h *******************************************/
107146 /************** Continuing where we left off in main.c ***********************/
107147 #endif
107148
107149 #ifndef SQLITE_AMALGAMATION
107150 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107151 ** contains the text of SQLITE_VERSION macro. 
107152 */
107153 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107154 #endif
107155
107156 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107157 ** a pointer to the to the sqlite3_version[] string constant. 
107158 */
107159 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107160
107161 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107162 ** pointer to a string constant whose value is the same as the
107163 ** SQLITE_SOURCE_ID C preprocessor macro. 
107164 */
107165 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107166
107167 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107168 ** returns an integer equal to SQLITE_VERSION_NUMBER.
107169 */
107170 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107171
107172 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107173 ** zero if and only if SQLite was compiled mutexing code omitted due to
107174 ** the SQLITE_THREADSAFE compile-time option being set to 0.
107175 */
107176 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107177
107178 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107179 /*
107180 ** If the following function pointer is not NULL and if
107181 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107182 ** I/O active are written using this function.  These messages
107183 ** are intended for debugging activity only.
107184 */
107185 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107186 #endif
107187
107188 /*
107189 ** If the following global variable points to a string which is the
107190 ** name of a directory, then that directory will be used to store
107191 ** temporary files.
107192 **
107193 ** See also the "PRAGMA temp_store_directory" SQL command.
107194 */
107195 SQLITE_API char *sqlite3_temp_directory = 0;
107196
107197 /*
107198 ** Initialize SQLite.  
107199 **
107200 ** This routine must be called to initialize the memory allocation,
107201 ** VFS, and mutex subsystems prior to doing any serious work with
107202 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
107203 ** this routine will be called automatically by key routines such as
107204 ** sqlite3_open().  
107205 **
107206 ** This routine is a no-op except on its very first call for the process,
107207 ** or for the first call after a call to sqlite3_shutdown.
107208 **
107209 ** The first thread to call this routine runs the initialization to
107210 ** completion.  If subsequent threads call this routine before the first
107211 ** thread has finished the initialization process, then the subsequent
107212 ** threads must block until the first thread finishes with the initialization.
107213 **
107214 ** The first thread might call this routine recursively.  Recursive
107215 ** calls to this routine should not block, of course.  Otherwise the
107216 ** initialization process would never complete.
107217 **
107218 ** Let X be the first thread to enter this routine.  Let Y be some other
107219 ** thread.  Then while the initial invocation of this routine by X is
107220 ** incomplete, it is required that:
107221 **
107222 **    *  Calls to this routine from Y must block until the outer-most
107223 **       call by X completes.
107224 **
107225 **    *  Recursive calls to this routine from thread X return immediately
107226 **       without blocking.
107227 */
107228 SQLITE_API int sqlite3_initialize(void){
107229   sqlite3_mutex *pMaster;                      /* The main static mutex */
107230   int rc;                                      /* Result code */
107231
107232 #ifdef SQLITE_OMIT_WSD
107233   rc = sqlite3_wsd_init(4096, 24);
107234   if( rc!=SQLITE_OK ){
107235     return rc;
107236   }
107237 #endif
107238
107239   /* If SQLite is already completely initialized, then this call
107240   ** to sqlite3_initialize() should be a no-op.  But the initialization
107241   ** must be complete.  So isInit must not be set until the very end
107242   ** of this routine.
107243   */
107244   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
107245
107246   /* Make sure the mutex subsystem is initialized.  If unable to 
107247   ** initialize the mutex subsystem, return early with the error.
107248   ** If the system is so sick that we are unable to allocate a mutex,
107249   ** there is not much SQLite is going to be able to do.
107250   **
107251   ** The mutex subsystem must take care of serializing its own
107252   ** initialization.
107253   */
107254   rc = sqlite3MutexInit();
107255   if( rc ) return rc;
107256
107257   /* Initialize the malloc() system and the recursive pInitMutex mutex.
107258   ** This operation is protected by the STATIC_MASTER mutex.  Note that
107259   ** MutexAlloc() is called for a static mutex prior to initializing the
107260   ** malloc subsystem - this implies that the allocation of a static
107261   ** mutex must not require support from the malloc subsystem.
107262   */
107263   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
107264   sqlite3_mutex_enter(pMaster);
107265   sqlite3GlobalConfig.isMutexInit = 1;
107266   if( !sqlite3GlobalConfig.isMallocInit ){
107267     rc = sqlite3MallocInit();
107268   }
107269   if( rc==SQLITE_OK ){
107270     sqlite3GlobalConfig.isMallocInit = 1;
107271     if( !sqlite3GlobalConfig.pInitMutex ){
107272       sqlite3GlobalConfig.pInitMutex =
107273            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
107274       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
107275         rc = SQLITE_NOMEM;
107276       }
107277     }
107278   }
107279   if( rc==SQLITE_OK ){
107280     sqlite3GlobalConfig.nRefInitMutex++;
107281   }
107282   sqlite3_mutex_leave(pMaster);
107283
107284   /* If rc is not SQLITE_OK at this point, then either the malloc
107285   ** subsystem could not be initialized or the system failed to allocate
107286   ** the pInitMutex mutex. Return an error in either case.  */
107287   if( rc!=SQLITE_OK ){
107288     return rc;
107289   }
107290
107291   /* Do the rest of the initialization under the recursive mutex so
107292   ** that we will be able to handle recursive calls into
107293   ** sqlite3_initialize().  The recursive calls normally come through
107294   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
107295   ** recursive calls might also be possible.
107296   **
107297   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
107298   ** to the xInit method, so the xInit method need not be threadsafe.
107299   **
107300   ** The following mutex is what serializes access to the appdef pcache xInit
107301   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
107302   ** call to sqlite3PcacheInitialize().
107303   */
107304   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
107305   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
107306     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
107307     sqlite3GlobalConfig.inProgress = 1;
107308     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
107309     sqlite3RegisterGlobalFunctions();
107310     if( sqlite3GlobalConfig.isPCacheInit==0 ){
107311       rc = sqlite3PcacheInitialize();
107312     }
107313     if( rc==SQLITE_OK ){
107314       sqlite3GlobalConfig.isPCacheInit = 1;
107315       rc = sqlite3OsInit();
107316     }
107317     if( rc==SQLITE_OK ){
107318       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
107319           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
107320       sqlite3GlobalConfig.isInit = 1;
107321     }
107322     sqlite3GlobalConfig.inProgress = 0;
107323   }
107324   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
107325
107326   /* Go back under the static mutex and clean up the recursive
107327   ** mutex to prevent a resource leak.
107328   */
107329   sqlite3_mutex_enter(pMaster);
107330   sqlite3GlobalConfig.nRefInitMutex--;
107331   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
107332     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
107333     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
107334     sqlite3GlobalConfig.pInitMutex = 0;
107335   }
107336   sqlite3_mutex_leave(pMaster);
107337
107338   /* The following is just a sanity check to make sure SQLite has
107339   ** been compiled correctly.  It is important to run this code, but
107340   ** we don't want to run it too often and soak up CPU cycles for no
107341   ** reason.  So we run it once during initialization.
107342   */
107343 #ifndef NDEBUG
107344 #ifndef SQLITE_OMIT_FLOATING_POINT
107345   /* This section of code's only "output" is via assert() statements. */
107346   if ( rc==SQLITE_OK ){
107347     u64 x = (((u64)1)<<63)-1;
107348     double y;
107349     assert(sizeof(x)==8);
107350     assert(sizeof(x)==sizeof(y));
107351     memcpy(&y, &x, 8);
107352     assert( sqlite3IsNaN(y) );
107353   }
107354 #endif
107355 #endif
107356
107357   return rc;
107358 }
107359
107360 /*
107361 ** Undo the effects of sqlite3_initialize().  Must not be called while
107362 ** there are outstanding database connections or memory allocations or
107363 ** while any part of SQLite is otherwise in use in any thread.  This
107364 ** routine is not threadsafe.  But it is safe to invoke this routine
107365 ** on when SQLite is already shut down.  If SQLite is already shut down
107366 ** when this routine is invoked, then this routine is a harmless no-op.
107367 */
107368 SQLITE_API int sqlite3_shutdown(void){
107369   if( sqlite3GlobalConfig.isInit ){
107370     sqlite3_os_end();
107371     sqlite3_reset_auto_extension();
107372     sqlite3GlobalConfig.isInit = 0;
107373   }
107374   if( sqlite3GlobalConfig.isPCacheInit ){
107375     sqlite3PcacheShutdown();
107376     sqlite3GlobalConfig.isPCacheInit = 0;
107377   }
107378   if( sqlite3GlobalConfig.isMallocInit ){
107379     sqlite3MallocEnd();
107380     sqlite3GlobalConfig.isMallocInit = 0;
107381   }
107382   if( sqlite3GlobalConfig.isMutexInit ){
107383     sqlite3MutexEnd();
107384     sqlite3GlobalConfig.isMutexInit = 0;
107385   }
107386
107387   return SQLITE_OK;
107388 }
107389
107390 /*
107391 ** This API allows applications to modify the global configuration of
107392 ** the SQLite library at run-time.
107393 **
107394 ** This routine should only be called when there are no outstanding
107395 ** database connections or memory allocations.  This routine is not
107396 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
107397 ** behavior.
107398 */
107399 SQLITE_API int sqlite3_config(int op, ...){
107400   va_list ap;
107401   int rc = SQLITE_OK;
107402
107403   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
107404   ** the SQLite library is in use. */
107405   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
107406
107407   va_start(ap, op);
107408   switch( op ){
107409
107410     /* Mutex configuration options are only available in a threadsafe
107411     ** compile. 
107412     */
107413 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
107414     case SQLITE_CONFIG_SINGLETHREAD: {
107415       /* Disable all mutexing */
107416       sqlite3GlobalConfig.bCoreMutex = 0;
107417       sqlite3GlobalConfig.bFullMutex = 0;
107418       break;
107419     }
107420     case SQLITE_CONFIG_MULTITHREAD: {
107421       /* Disable mutexing of database connections */
107422       /* Enable mutexing of core data structures */
107423       sqlite3GlobalConfig.bCoreMutex = 1;
107424       sqlite3GlobalConfig.bFullMutex = 0;
107425       break;
107426     }
107427     case SQLITE_CONFIG_SERIALIZED: {
107428       /* Enable all mutexing */
107429       sqlite3GlobalConfig.bCoreMutex = 1;
107430       sqlite3GlobalConfig.bFullMutex = 1;
107431       break;
107432     }
107433     case SQLITE_CONFIG_MUTEX: {
107434       /* Specify an alternative mutex implementation */
107435       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
107436       break;
107437     }
107438     case SQLITE_CONFIG_GETMUTEX: {
107439       /* Retrieve the current mutex implementation */
107440       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
107441       break;
107442     }
107443 #endif
107444
107445
107446     case SQLITE_CONFIG_MALLOC: {
107447       /* Specify an alternative malloc implementation */
107448       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
107449       break;
107450     }
107451     case SQLITE_CONFIG_GETMALLOC: {
107452       /* Retrieve the current malloc() implementation */
107453       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
107454       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
107455       break;
107456     }
107457     case SQLITE_CONFIG_MEMSTATUS: {
107458       /* Enable or disable the malloc status collection */
107459       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
107460       break;
107461     }
107462     case SQLITE_CONFIG_SCRATCH: {
107463       /* Designate a buffer for scratch memory space */
107464       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
107465       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
107466       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
107467       break;
107468     }
107469     case SQLITE_CONFIG_PAGECACHE: {
107470       /* Designate a buffer for page cache memory space */
107471       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
107472       sqlite3GlobalConfig.szPage = va_arg(ap, int);
107473       sqlite3GlobalConfig.nPage = va_arg(ap, int);
107474       break;
107475     }
107476
107477     case SQLITE_CONFIG_PCACHE: {
107478       /* Specify an alternative page cache implementation */
107479       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
107480       break;
107481     }
107482
107483     case SQLITE_CONFIG_GETPCACHE: {
107484       if( sqlite3GlobalConfig.pcache.xInit==0 ){
107485         sqlite3PCacheSetDefault();
107486       }
107487       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
107488       break;
107489     }
107490
107491 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
107492     case SQLITE_CONFIG_HEAP: {
107493       /* Designate a buffer for heap memory space */
107494       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
107495       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
107496       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
107497
107498       if( sqlite3GlobalConfig.mnReq<1 ){
107499         sqlite3GlobalConfig.mnReq = 1;
107500       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
107501         /* cap min request size at 2^12 */
107502         sqlite3GlobalConfig.mnReq = (1<<12);
107503       }
107504
107505       if( sqlite3GlobalConfig.pHeap==0 ){
107506         /* If the heap pointer is NULL, then restore the malloc implementation
107507         ** back to NULL pointers too.  This will cause the malloc to go
107508         ** back to its default implementation when sqlite3_initialize() is
107509         ** run.
107510         */
107511         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
107512       }else{
107513         /* The heap pointer is not NULL, then install one of the
107514         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
107515         ** ENABLE_MEMSYS5 is defined, return an error.
107516         */
107517 #ifdef SQLITE_ENABLE_MEMSYS3
107518         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
107519 #endif
107520 #ifdef SQLITE_ENABLE_MEMSYS5
107521         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
107522 #endif
107523       }
107524       break;
107525     }
107526 #endif
107527
107528     case SQLITE_CONFIG_LOOKASIDE: {
107529       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
107530       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
107531       break;
107532     }
107533     
107534     /* Record a pointer to the logger funcction and its first argument.
107535     ** The default is NULL.  Logging is disabled if the function pointer is
107536     ** NULL.
107537     */
107538     case SQLITE_CONFIG_LOG: {
107539       /* MSVC is picky about pulling func ptrs from va lists.
107540       ** http://support.microsoft.com/kb/47961
107541       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
107542       */
107543       typedef void(*LOGFUNC_t)(void*,int,const char*);
107544       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
107545       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
107546       break;
107547     }
107548
107549     default: {
107550       rc = SQLITE_ERROR;
107551       break;
107552     }
107553   }
107554   va_end(ap);
107555   return rc;
107556 }
107557
107558 /*
107559 ** Set up the lookaside buffers for a database connection.
107560 ** Return SQLITE_OK on success.  
107561 ** If lookaside is already active, return SQLITE_BUSY.
107562 **
107563 ** The sz parameter is the number of bytes in each lookaside slot.
107564 ** The cnt parameter is the number of slots.  If pStart is NULL the
107565 ** space for the lookaside memory is obtained from sqlite3_malloc().
107566 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
107567 ** the lookaside memory.
107568 */
107569 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
107570   void *pStart;
107571   if( db->lookaside.nOut ){
107572     return SQLITE_BUSY;
107573   }
107574   /* Free any existing lookaside buffer for this handle before
107575   ** allocating a new one so we don't have to have space for 
107576   ** both at the same time.
107577   */
107578   if( db->lookaside.bMalloced ){
107579     sqlite3_free(db->lookaside.pStart);
107580   }
107581   /* The size of a lookaside slot needs to be larger than a pointer
107582   ** to be useful.
107583   */
107584   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
107585   if( cnt<0 ) cnt = 0;
107586   if( sz==0 || cnt==0 ){
107587     sz = 0;
107588     pStart = 0;
107589   }else if( pBuf==0 ){
107590     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107591     sqlite3BeginBenignMalloc();
107592     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
107593     sqlite3EndBenignMalloc();
107594   }else{
107595     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107596     pStart = pBuf;
107597   }
107598   db->lookaside.pStart = pStart;
107599   db->lookaside.pFree = 0;
107600   db->lookaside.sz = (u16)sz;
107601   if( pStart ){
107602     int i;
107603     LookasideSlot *p;
107604     assert( sz > (int)sizeof(LookasideSlot*) );
107605     p = (LookasideSlot*)pStart;
107606     for(i=cnt-1; i>=0; i--){
107607       p->pNext = db->lookaside.pFree;
107608       db->lookaside.pFree = p;
107609       p = (LookasideSlot*)&((u8*)p)[sz];
107610     }
107611     db->lookaside.pEnd = p;
107612     db->lookaside.bEnabled = 1;
107613     db->lookaside.bMalloced = pBuf==0 ?1:0;
107614   }else{
107615     db->lookaside.pEnd = 0;
107616     db->lookaside.bEnabled = 0;
107617     db->lookaside.bMalloced = 0;
107618   }
107619   return SQLITE_OK;
107620 }
107621
107622 /*
107623 ** Return the mutex associated with a database connection.
107624 */
107625 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
107626   return db->mutex;
107627 }
107628
107629 /*
107630 ** Configuration settings for an individual database connection
107631 */
107632 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
107633   va_list ap;
107634   int rc;
107635   va_start(ap, op);
107636   switch( op ){
107637     case SQLITE_DBCONFIG_LOOKASIDE: {
107638       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
107639       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
107640       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
107641       rc = setupLookaside(db, pBuf, sz, cnt);
107642       break;
107643     }
107644     default: {
107645       static const struct {
107646         int op;      /* The opcode */
107647         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
107648       } aFlagOp[] = {
107649         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
107650         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
107651       };
107652       unsigned int i;
107653       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
107654       for(i=0; i<ArraySize(aFlagOp); i++){
107655         if( aFlagOp[i].op==op ){
107656           int onoff = va_arg(ap, int);
107657           int *pRes = va_arg(ap, int*);
107658           int oldFlags = db->flags;
107659           if( onoff>0 ){
107660             db->flags |= aFlagOp[i].mask;
107661           }else if( onoff==0 ){
107662             db->flags &= ~aFlagOp[i].mask;
107663           }
107664           if( oldFlags!=db->flags ){
107665             sqlite3ExpirePreparedStatements(db);
107666           }
107667           if( pRes ){
107668             *pRes = (db->flags & aFlagOp[i].mask)!=0;
107669           }
107670           rc = SQLITE_OK;
107671           break;
107672         }
107673       }
107674       break;
107675     }
107676   }
107677   va_end(ap);
107678   return rc;
107679 }
107680
107681
107682 /*
107683 ** Return true if the buffer z[0..n-1] contains all spaces.
107684 */
107685 static int allSpaces(const char *z, int n){
107686   while( n>0 && z[n-1]==' ' ){ n--; }
107687   return n==0;
107688 }
107689
107690 /*
107691 ** This is the default collating function named "BINARY" which is always
107692 ** available.
107693 **
107694 ** If the padFlag argument is not NULL then space padding at the end
107695 ** of strings is ignored.  This implements the RTRIM collation.
107696 */
107697 static int binCollFunc(
107698   void *padFlag,
107699   int nKey1, const void *pKey1,
107700   int nKey2, const void *pKey2
107701 ){
107702   int rc, n;
107703   n = nKey1<nKey2 ? nKey1 : nKey2;
107704   rc = memcmp(pKey1, pKey2, n);
107705   if( rc==0 ){
107706     if( padFlag
107707      && allSpaces(((char*)pKey1)+n, nKey1-n)
107708      && allSpaces(((char*)pKey2)+n, nKey2-n)
107709     ){
107710       /* Leave rc unchanged at 0 */
107711     }else{
107712       rc = nKey1 - nKey2;
107713     }
107714   }
107715   return rc;
107716 }
107717
107718 /*
107719 ** Another built-in collating sequence: NOCASE. 
107720 **
107721 ** This collating sequence is intended to be used for "case independant
107722 ** comparison". SQLite's knowledge of upper and lower case equivalents
107723 ** extends only to the 26 characters used in the English language.
107724 **
107725 ** At the moment there is only a UTF-8 implementation.
107726 */
107727 static int nocaseCollatingFunc(
107728   void *NotUsed,
107729   int nKey1, const void *pKey1,
107730   int nKey2, const void *pKey2
107731 ){
107732   int r = sqlite3StrNICmp(
107733       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
107734   UNUSED_PARAMETER(NotUsed);
107735   if( 0==r ){
107736     r = nKey1-nKey2;
107737   }
107738   return r;
107739 }
107740
107741 /*
107742 ** Return the ROWID of the most recent insert
107743 */
107744 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
107745   return db->lastRowid;
107746 }
107747
107748 /*
107749 ** Return the number of changes in the most recent call to sqlite3_exec().
107750 */
107751 SQLITE_API int sqlite3_changes(sqlite3 *db){
107752   return db->nChange;
107753 }
107754
107755 /*
107756 ** Return the number of changes since the database handle was opened.
107757 */
107758 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
107759   return db->nTotalChange;
107760 }
107761
107762 /*
107763 ** Close all open savepoints. This function only manipulates fields of the
107764 ** database handle object, it does not close any savepoints that may be open
107765 ** at the b-tree/pager level.
107766 */
107767 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
107768   while( db->pSavepoint ){
107769     Savepoint *pTmp = db->pSavepoint;
107770     db->pSavepoint = pTmp->pNext;
107771     sqlite3DbFree(db, pTmp);
107772   }
107773   db->nSavepoint = 0;
107774   db->nStatement = 0;
107775   db->isTransactionSavepoint = 0;
107776 }
107777
107778 /*
107779 ** Invoke the destructor function associated with FuncDef p, if any. Except,
107780 ** if this is not the last copy of the function, do not invoke it. Multiple
107781 ** copies of a single function are created when create_function() is called
107782 ** with SQLITE_ANY as the encoding.
107783 */
107784 static void functionDestroy(sqlite3 *db, FuncDef *p){
107785   FuncDestructor *pDestructor = p->pDestructor;
107786   if( pDestructor ){
107787     pDestructor->nRef--;
107788     if( pDestructor->nRef==0 ){
107789       pDestructor->xDestroy(pDestructor->pUserData);
107790       sqlite3DbFree(db, pDestructor);
107791     }
107792   }
107793 }
107794
107795 /*
107796 ** Close an existing SQLite database
107797 */
107798 SQLITE_API int sqlite3_close(sqlite3 *db){
107799   HashElem *i;                    /* Hash table iterator */
107800   int j;
107801
107802   if( !db ){
107803     return SQLITE_OK;
107804   }
107805   if( !sqlite3SafetyCheckSickOrOk(db) ){
107806     return SQLITE_MISUSE_BKPT;
107807   }
107808   sqlite3_mutex_enter(db->mutex);
107809
107810   /* Force xDestroy calls on all virtual tables */
107811   sqlite3ResetInternalSchema(db, -1);
107812
107813   /* If a transaction is open, the ResetInternalSchema() call above
107814   ** will not have called the xDisconnect() method on any virtual
107815   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
107816   ** call will do so. We need to do this before the check for active
107817   ** SQL statements below, as the v-table implementation may be storing
107818   ** some prepared statements internally.
107819   */
107820   sqlite3VtabRollback(db);
107821
107822   /* If there are any outstanding VMs, return SQLITE_BUSY. */
107823   if( db->pVdbe ){
107824     sqlite3Error(db, SQLITE_BUSY, 
107825         "unable to close due to unfinalised statements");
107826     sqlite3_mutex_leave(db->mutex);
107827     return SQLITE_BUSY;
107828   }
107829   assert( sqlite3SafetyCheckSickOrOk(db) );
107830
107831   for(j=0; j<db->nDb; j++){
107832     Btree *pBt = db->aDb[j].pBt;
107833     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
107834       sqlite3Error(db, SQLITE_BUSY, 
107835           "unable to close due to unfinished backup operation");
107836       sqlite3_mutex_leave(db->mutex);
107837       return SQLITE_BUSY;
107838     }
107839   }
107840
107841   /* Free any outstanding Savepoint structures. */
107842   sqlite3CloseSavepoints(db);
107843
107844   for(j=0; j<db->nDb; j++){
107845     struct Db *pDb = &db->aDb[j];
107846     if( pDb->pBt ){
107847       sqlite3BtreeClose(pDb->pBt);
107848       pDb->pBt = 0;
107849       if( j!=1 ){
107850         pDb->pSchema = 0;
107851       }
107852     }
107853   }
107854   sqlite3ResetInternalSchema(db, -1);
107855
107856   /* Tell the code in notify.c that the connection no longer holds any
107857   ** locks and does not require any further unlock-notify callbacks.
107858   */
107859   sqlite3ConnectionClosed(db);
107860
107861   assert( db->nDb<=2 );
107862   assert( db->aDb==db->aDbStatic );
107863   for(j=0; j<ArraySize(db->aFunc.a); j++){
107864     FuncDef *pNext, *pHash, *p;
107865     for(p=db->aFunc.a[j]; p; p=pHash){
107866       pHash = p->pHash;
107867       while( p ){
107868         functionDestroy(db, p);
107869         pNext = p->pNext;
107870         sqlite3DbFree(db, p);
107871         p = pNext;
107872       }
107873     }
107874   }
107875   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
107876     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
107877     /* Invoke any destructors registered for collation sequence user data. */
107878     for(j=0; j<3; j++){
107879       if( pColl[j].xDel ){
107880         pColl[j].xDel(pColl[j].pUser);
107881       }
107882     }
107883     sqlite3DbFree(db, pColl);
107884   }
107885   sqlite3HashClear(&db->aCollSeq);
107886 #ifndef SQLITE_OMIT_VIRTUALTABLE
107887   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
107888     Module *pMod = (Module *)sqliteHashData(i);
107889     if( pMod->xDestroy ){
107890       pMod->xDestroy(pMod->pAux);
107891     }
107892     sqlite3DbFree(db, pMod);
107893   }
107894   sqlite3HashClear(&db->aModule);
107895 #endif
107896
107897   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
107898   if( db->pErr ){
107899     sqlite3ValueFree(db->pErr);
107900   }
107901   sqlite3CloseExtensions(db);
107902
107903   db->magic = SQLITE_MAGIC_ERROR;
107904
107905   /* The temp-database schema is allocated differently from the other schema
107906   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
107907   ** So it needs to be freed here. Todo: Why not roll the temp schema into
107908   ** the same sqliteMalloc() as the one that allocates the database 
107909   ** structure?
107910   */
107911   sqlite3DbFree(db, db->aDb[1].pSchema);
107912   sqlite3_mutex_leave(db->mutex);
107913   db->magic = SQLITE_MAGIC_CLOSED;
107914   sqlite3_mutex_free(db->mutex);
107915   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
107916   if( db->lookaside.bMalloced ){
107917     sqlite3_free(db->lookaside.pStart);
107918   }
107919   sqlite3_free(db);
107920   return SQLITE_OK;
107921 }
107922
107923 /*
107924 ** Rollback all database files.
107925 */
107926 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
107927   int i;
107928   int inTrans = 0;
107929   assert( sqlite3_mutex_held(db->mutex) );
107930   sqlite3BeginBenignMalloc();
107931   for(i=0; i<db->nDb; i++){
107932     if( db->aDb[i].pBt ){
107933       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
107934         inTrans = 1;
107935       }
107936       sqlite3BtreeRollback(db->aDb[i].pBt);
107937       db->aDb[i].inTrans = 0;
107938     }
107939   }
107940   sqlite3VtabRollback(db);
107941   sqlite3EndBenignMalloc();
107942
107943   if( db->flags&SQLITE_InternChanges ){
107944     sqlite3ExpirePreparedStatements(db);
107945     sqlite3ResetInternalSchema(db, -1);
107946   }
107947
107948   /* Any deferred constraint violations have now been resolved. */
107949   db->nDeferredCons = 0;
107950
107951   /* If one has been configured, invoke the rollback-hook callback */
107952   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
107953     db->xRollbackCallback(db->pRollbackArg);
107954   }
107955 }
107956
107957 /*
107958 ** Return a static string that describes the kind of error specified in the
107959 ** argument.
107960 */
107961 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
107962   static const char* const aMsg[] = {
107963     /* SQLITE_OK          */ "not an error",
107964     /* SQLITE_ERROR       */ "SQL logic error or missing database",
107965     /* SQLITE_INTERNAL    */ 0,
107966     /* SQLITE_PERM        */ "access permission denied",
107967     /* SQLITE_ABORT       */ "callback requested query abort",
107968     /* SQLITE_BUSY        */ "database is locked",
107969     /* SQLITE_LOCKED      */ "database table is locked",
107970     /* SQLITE_NOMEM       */ "out of memory",
107971     /* SQLITE_READONLY    */ "attempt to write a readonly database",
107972     /* SQLITE_INTERRUPT   */ "interrupted",
107973     /* SQLITE_IOERR       */ "disk I/O error",
107974     /* SQLITE_CORRUPT     */ "database disk image is malformed",
107975     /* SQLITE_NOTFOUND    */ "unknown operation",
107976     /* SQLITE_FULL        */ "database or disk is full",
107977     /* SQLITE_CANTOPEN    */ "unable to open database file",
107978     /* SQLITE_PROTOCOL    */ "locking protocol",
107979     /* SQLITE_EMPTY       */ "table contains no data",
107980     /* SQLITE_SCHEMA      */ "database schema has changed",
107981     /* SQLITE_TOOBIG      */ "string or blob too big",
107982     /* SQLITE_CONSTRAINT  */ "constraint failed",
107983     /* SQLITE_MISMATCH    */ "datatype mismatch",
107984     /* SQLITE_MISUSE      */ "library routine called out of sequence",
107985     /* SQLITE_NOLFS       */ "large file support is disabled",
107986     /* SQLITE_AUTH        */ "authorization denied",
107987     /* SQLITE_FORMAT      */ "auxiliary database format error",
107988     /* SQLITE_RANGE       */ "bind or column index out of range",
107989     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
107990   };
107991   rc &= 0xff;
107992   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
107993     return aMsg[rc];
107994   }else{
107995     return "unknown error";
107996   }
107997 }
107998
107999 /*
108000 ** This routine implements a busy callback that sleeps and tries
108001 ** again until a timeout value is reached.  The timeout value is
108002 ** an integer number of milliseconds passed in as the first
108003 ** argument.
108004 */
108005 static int sqliteDefaultBusyCallback(
108006  void *ptr,               /* Database connection */
108007  int count                /* Number of times table has been busy */
108008 ){
108009 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108010   static const u8 delays[] =
108011      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
108012   static const u8 totals[] =
108013      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
108014 # define NDELAY ArraySize(delays)
108015   sqlite3 *db = (sqlite3 *)ptr;
108016   int timeout = db->busyTimeout;
108017   int delay, prior;
108018
108019   assert( count>=0 );
108020   if( count < NDELAY ){
108021     delay = delays[count];
108022     prior = totals[count];
108023   }else{
108024     delay = delays[NDELAY-1];
108025     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108026   }
108027   if( prior + delay > timeout ){
108028     delay = timeout - prior;
108029     if( delay<=0 ) return 0;
108030   }
108031   sqlite3OsSleep(db->pVfs, delay*1000);
108032   return 1;
108033 #else
108034   sqlite3 *db = (sqlite3 *)ptr;
108035   int timeout = ((sqlite3 *)ptr)->busyTimeout;
108036   if( (count+1)*1000 > timeout ){
108037     return 0;
108038   }
108039   sqlite3OsSleep(db->pVfs, 1000000);
108040   return 1;
108041 #endif
108042 }
108043
108044 /*
108045 ** Invoke the given busy handler.
108046 **
108047 ** This routine is called when an operation failed with a lock.
108048 ** If this routine returns non-zero, the lock is retried.  If it
108049 ** returns 0, the operation aborts with an SQLITE_BUSY error.
108050 */
108051 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108052   int rc;
108053   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108054   rc = p->xFunc(p->pArg, p->nBusy);
108055   if( rc==0 ){
108056     p->nBusy = -1;
108057   }else{
108058     p->nBusy++;
108059   }
108060   return rc; 
108061 }
108062
108063 /*
108064 ** This routine sets the busy callback for an Sqlite database to the
108065 ** given callback function with the given argument.
108066 */
108067 SQLITE_API int sqlite3_busy_handler(
108068   sqlite3 *db,
108069   int (*xBusy)(void*,int),
108070   void *pArg
108071 ){
108072   sqlite3_mutex_enter(db->mutex);
108073   db->busyHandler.xFunc = xBusy;
108074   db->busyHandler.pArg = pArg;
108075   db->busyHandler.nBusy = 0;
108076   sqlite3_mutex_leave(db->mutex);
108077   return SQLITE_OK;
108078 }
108079
108080 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108081 /*
108082 ** This routine sets the progress callback for an Sqlite database to the
108083 ** given callback function with the given argument. The progress callback will
108084 ** be invoked every nOps opcodes.
108085 */
108086 SQLITE_API void sqlite3_progress_handler(
108087   sqlite3 *db, 
108088   int nOps,
108089   int (*xProgress)(void*), 
108090   void *pArg
108091 ){
108092   sqlite3_mutex_enter(db->mutex);
108093   if( nOps>0 ){
108094     db->xProgress = xProgress;
108095     db->nProgressOps = nOps;
108096     db->pProgressArg = pArg;
108097   }else{
108098     db->xProgress = 0;
108099     db->nProgressOps = 0;
108100     db->pProgressArg = 0;
108101   }
108102   sqlite3_mutex_leave(db->mutex);
108103 }
108104 #endif
108105
108106
108107 /*
108108 ** This routine installs a default busy handler that waits for the
108109 ** specified number of milliseconds before returning 0.
108110 */
108111 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108112   if( ms>0 ){
108113     db->busyTimeout = ms;
108114     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108115   }else{
108116     sqlite3_busy_handler(db, 0, 0);
108117   }
108118   return SQLITE_OK;
108119 }
108120
108121 /*
108122 ** Cause any pending operation to stop at its earliest opportunity.
108123 */
108124 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108125   db->u1.isInterrupted = 1;
108126 }
108127
108128
108129 /*
108130 ** This function is exactly the same as sqlite3_create_function(), except
108131 ** that it is designed to be called by internal code. The difference is
108132 ** that if a malloc() fails in sqlite3_create_function(), an error code
108133 ** is returned and the mallocFailed flag cleared. 
108134 */
108135 SQLITE_PRIVATE int sqlite3CreateFunc(
108136   sqlite3 *db,
108137   const char *zFunctionName,
108138   int nArg,
108139   int enc,
108140   void *pUserData,
108141   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108142   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108143   void (*xFinal)(sqlite3_context*),
108144   FuncDestructor *pDestructor
108145 ){
108146   FuncDef *p;
108147   int nName;
108148
108149   assert( sqlite3_mutex_held(db->mutex) );
108150   if( zFunctionName==0 ||
108151       (xFunc && (xFinal || xStep)) || 
108152       (!xFunc && (xFinal && !xStep)) ||
108153       (!xFunc && (!xFinal && xStep)) ||
108154       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108155       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108156     return SQLITE_MISUSE_BKPT;
108157   }
108158   
108159 #ifndef SQLITE_OMIT_UTF16
108160   /* If SQLITE_UTF16 is specified as the encoding type, transform this
108161   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108162   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108163   **
108164   ** If SQLITE_ANY is specified, add three versions of the function
108165   ** to the hash table.
108166   */
108167   if( enc==SQLITE_UTF16 ){
108168     enc = SQLITE_UTF16NATIVE;
108169   }else if( enc==SQLITE_ANY ){
108170     int rc;
108171     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108172          pUserData, xFunc, xStep, xFinal, pDestructor);
108173     if( rc==SQLITE_OK ){
108174       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108175           pUserData, xFunc, xStep, xFinal, pDestructor);
108176     }
108177     if( rc!=SQLITE_OK ){
108178       return rc;
108179     }
108180     enc = SQLITE_UTF16BE;
108181   }
108182 #else
108183   enc = SQLITE_UTF8;
108184 #endif
108185   
108186   /* Check if an existing function is being overridden or deleted. If so,
108187   ** and there are active VMs, then return SQLITE_BUSY. If a function
108188   ** is being overridden/deleted but there are no active VMs, allow the
108189   ** operation to continue but invalidate all precompiled statements.
108190   */
108191   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108192   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108193     if( db->activeVdbeCnt ){
108194       sqlite3Error(db, SQLITE_BUSY, 
108195         "unable to delete/modify user-function due to active statements");
108196       assert( !db->mallocFailed );
108197       return SQLITE_BUSY;
108198     }else{
108199       sqlite3ExpirePreparedStatements(db);
108200     }
108201   }
108202
108203   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
108204   assert(p || db->mallocFailed);
108205   if( !p ){
108206     return SQLITE_NOMEM;
108207   }
108208
108209   /* If an older version of the function with a configured destructor is
108210   ** being replaced invoke the destructor function here. */
108211   functionDestroy(db, p);
108212
108213   if( pDestructor ){
108214     pDestructor->nRef++;
108215   }
108216   p->pDestructor = pDestructor;
108217   p->flags = 0;
108218   p->xFunc = xFunc;
108219   p->xStep = xStep;
108220   p->xFinalize = xFinal;
108221   p->pUserData = pUserData;
108222   p->nArg = (u16)nArg;
108223   return SQLITE_OK;
108224 }
108225
108226 /*
108227 ** Create new user functions.
108228 */
108229 SQLITE_API int sqlite3_create_function(
108230   sqlite3 *db,
108231   const char *zFunc,
108232   int nArg,
108233   int enc,
108234   void *p,
108235   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108236   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108237   void (*xFinal)(sqlite3_context*)
108238 ){
108239   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
108240                                     xFinal, 0);
108241 }
108242
108243 SQLITE_API int sqlite3_create_function_v2(
108244   sqlite3 *db,
108245   const char *zFunc,
108246   int nArg,
108247   int enc,
108248   void *p,
108249   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108250   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108251   void (*xFinal)(sqlite3_context*),
108252   void (*xDestroy)(void *)
108253 ){
108254   int rc = SQLITE_ERROR;
108255   FuncDestructor *pArg = 0;
108256   sqlite3_mutex_enter(db->mutex);
108257   if( xDestroy ){
108258     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
108259     if( !pArg ){
108260       xDestroy(p);
108261       goto out;
108262     }
108263     pArg->xDestroy = xDestroy;
108264     pArg->pUserData = p;
108265   }
108266   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
108267   if( pArg && pArg->nRef==0 ){
108268     assert( rc!=SQLITE_OK );
108269     xDestroy(p);
108270     sqlite3DbFree(db, pArg);
108271   }
108272
108273  out:
108274   rc = sqlite3ApiExit(db, rc);
108275   sqlite3_mutex_leave(db->mutex);
108276   return rc;
108277 }
108278
108279 #ifndef SQLITE_OMIT_UTF16
108280 SQLITE_API int sqlite3_create_function16(
108281   sqlite3 *db,
108282   const void *zFunctionName,
108283   int nArg,
108284   int eTextRep,
108285   void *p,
108286   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108287   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108288   void (*xFinal)(sqlite3_context*)
108289 ){
108290   int rc;
108291   char *zFunc8;
108292   sqlite3_mutex_enter(db->mutex);
108293   assert( !db->mallocFailed );
108294   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
108295   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
108296   sqlite3DbFree(db, zFunc8);
108297   rc = sqlite3ApiExit(db, rc);
108298   sqlite3_mutex_leave(db->mutex);
108299   return rc;
108300 }
108301 #endif
108302
108303
108304 /*
108305 ** Declare that a function has been overloaded by a virtual table.
108306 **
108307 ** If the function already exists as a regular global function, then
108308 ** this routine is a no-op.  If the function does not exist, then create
108309 ** a new one that always throws a run-time error.  
108310 **
108311 ** When virtual tables intend to provide an overloaded function, they
108312 ** should call this routine to make sure the global function exists.
108313 ** A global function must exist in order for name resolution to work
108314 ** properly.
108315 */
108316 SQLITE_API int sqlite3_overload_function(
108317   sqlite3 *db,
108318   const char *zName,
108319   int nArg
108320 ){
108321   int nName = sqlite3Strlen30(zName);
108322   int rc;
108323   sqlite3_mutex_enter(db->mutex);
108324   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
108325     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
108326                       0, sqlite3InvalidFunction, 0, 0, 0);
108327   }
108328   rc = sqlite3ApiExit(db, SQLITE_OK);
108329   sqlite3_mutex_leave(db->mutex);
108330   return rc;
108331 }
108332
108333 #ifndef SQLITE_OMIT_TRACE
108334 /*
108335 ** Register a trace function.  The pArg from the previously registered trace
108336 ** is returned.  
108337 **
108338 ** A NULL trace function means that no tracing is executes.  A non-NULL
108339 ** trace is a pointer to a function that is invoked at the start of each
108340 ** SQL statement.
108341 */
108342 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
108343   void *pOld;
108344   sqlite3_mutex_enter(db->mutex);
108345   pOld = db->pTraceArg;
108346   db->xTrace = xTrace;
108347   db->pTraceArg = pArg;
108348   sqlite3_mutex_leave(db->mutex);
108349   return pOld;
108350 }
108351 /*
108352 ** Register a profile function.  The pArg from the previously registered 
108353 ** profile function is returned.  
108354 **
108355 ** A NULL profile function means that no profiling is executes.  A non-NULL
108356 ** profile is a pointer to a function that is invoked at the conclusion of
108357 ** each SQL statement that is run.
108358 */
108359 SQLITE_API void *sqlite3_profile(
108360   sqlite3 *db,
108361   void (*xProfile)(void*,const char*,sqlite_uint64),
108362   void *pArg
108363 ){
108364   void *pOld;
108365   sqlite3_mutex_enter(db->mutex);
108366   pOld = db->pProfileArg;
108367   db->xProfile = xProfile;
108368   db->pProfileArg = pArg;
108369   sqlite3_mutex_leave(db->mutex);
108370   return pOld;
108371 }
108372 #endif /* SQLITE_OMIT_TRACE */
108373
108374 /*** EXPERIMENTAL ***
108375 **
108376 ** Register a function to be invoked when a transaction comments.
108377 ** If the invoked function returns non-zero, then the commit becomes a
108378 ** rollback.
108379 */
108380 SQLITE_API void *sqlite3_commit_hook(
108381   sqlite3 *db,              /* Attach the hook to this database */
108382   int (*xCallback)(void*),  /* Function to invoke on each commit */
108383   void *pArg                /* Argument to the function */
108384 ){
108385   void *pOld;
108386   sqlite3_mutex_enter(db->mutex);
108387   pOld = db->pCommitArg;
108388   db->xCommitCallback = xCallback;
108389   db->pCommitArg = pArg;
108390   sqlite3_mutex_leave(db->mutex);
108391   return pOld;
108392 }
108393
108394 /*
108395 ** Register a callback to be invoked each time a row is updated,
108396 ** inserted or deleted using this database connection.
108397 */
108398 SQLITE_API void *sqlite3_update_hook(
108399   sqlite3 *db,              /* Attach the hook to this database */
108400   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
108401   void *pArg                /* Argument to the function */
108402 ){
108403   void *pRet;
108404   sqlite3_mutex_enter(db->mutex);
108405   pRet = db->pUpdateArg;
108406   db->xUpdateCallback = xCallback;
108407   db->pUpdateArg = pArg;
108408   sqlite3_mutex_leave(db->mutex);
108409   return pRet;
108410 }
108411
108412 /*
108413 ** Register a callback to be invoked each time a transaction is rolled
108414 ** back by this database connection.
108415 */
108416 SQLITE_API void *sqlite3_rollback_hook(
108417   sqlite3 *db,              /* Attach the hook to this database */
108418   void (*xCallback)(void*), /* Callback function */
108419   void *pArg                /* Argument to the function */
108420 ){
108421   void *pRet;
108422   sqlite3_mutex_enter(db->mutex);
108423   pRet = db->pRollbackArg;
108424   db->xRollbackCallback = xCallback;
108425   db->pRollbackArg = pArg;
108426   sqlite3_mutex_leave(db->mutex);
108427   return pRet;
108428 }
108429
108430 #ifndef SQLITE_OMIT_WAL
108431 /*
108432 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
108433 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
108434 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
108435 ** wal_autocheckpoint()).
108436 */ 
108437 SQLITE_PRIVATE int sqlite3WalDefaultHook(
108438   void *pClientData,     /* Argument */
108439   sqlite3 *db,           /* Connection */
108440   const char *zDb,       /* Database */
108441   int nFrame             /* Size of WAL */
108442 ){
108443   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
108444     sqlite3BeginBenignMalloc();
108445     sqlite3_wal_checkpoint(db, zDb);
108446     sqlite3EndBenignMalloc();
108447   }
108448   return SQLITE_OK;
108449 }
108450 #endif /* SQLITE_OMIT_WAL */
108451
108452 /*
108453 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
108454 ** a database after committing a transaction if there are nFrame or
108455 ** more frames in the log file. Passing zero or a negative value as the
108456 ** nFrame parameter disables automatic checkpoints entirely.
108457 **
108458 ** The callback registered by this function replaces any existing callback
108459 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
108460 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
108461 ** configured by this function.
108462 */
108463 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
108464 #ifdef SQLITE_OMIT_WAL
108465   UNUSED_PARAMETER(db);
108466   UNUSED_PARAMETER(nFrame);
108467 #else
108468   if( nFrame>0 ){
108469     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
108470   }else{
108471     sqlite3_wal_hook(db, 0, 0);
108472   }
108473 #endif
108474   return SQLITE_OK;
108475 }
108476
108477 /*
108478 ** Register a callback to be invoked each time a transaction is written
108479 ** into the write-ahead-log by this database connection.
108480 */
108481 SQLITE_API void *sqlite3_wal_hook(
108482   sqlite3 *db,                    /* Attach the hook to this db handle */
108483   int(*xCallback)(void *, sqlite3*, const char*, int),
108484   void *pArg                      /* First argument passed to xCallback() */
108485 ){
108486 #ifndef SQLITE_OMIT_WAL
108487   void *pRet;
108488   sqlite3_mutex_enter(db->mutex);
108489   pRet = db->pWalArg;
108490   db->xWalCallback = xCallback;
108491   db->pWalArg = pArg;
108492   sqlite3_mutex_leave(db->mutex);
108493   return pRet;
108494 #else
108495   return 0;
108496 #endif
108497 }
108498
108499 /*
108500 ** Checkpoint database zDb.
108501 */
108502 SQLITE_API int sqlite3_wal_checkpoint_v2(
108503   sqlite3 *db,                    /* Database handle */
108504   const char *zDb,                /* Name of attached database (or NULL) */
108505   int eMode,                      /* SQLITE_CHECKPOINT_* value */
108506   int *pnLog,                     /* OUT: Size of WAL log in frames */
108507   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
108508 ){
108509 #ifdef SQLITE_OMIT_WAL
108510   return SQLITE_OK;
108511 #else
108512   int rc;                         /* Return code */
108513   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
108514
108515   /* Initialize the output variables to -1 in case an error occurs. */
108516   if( pnLog ) *pnLog = -1;
108517   if( pnCkpt ) *pnCkpt = -1;
108518
108519   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
108520   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
108521   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
108522   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
108523     return SQLITE_MISUSE;
108524   }
108525
108526   sqlite3_mutex_enter(db->mutex);
108527   if( zDb && zDb[0] ){
108528     iDb = sqlite3FindDbName(db, zDb);
108529   }
108530   if( iDb<0 ){
108531     rc = SQLITE_ERROR;
108532     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
108533   }else{
108534     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
108535     sqlite3Error(db, rc, 0);
108536   }
108537   rc = sqlite3ApiExit(db, rc);
108538   sqlite3_mutex_leave(db->mutex);
108539   return rc;
108540 #endif
108541 }
108542
108543
108544 /*
108545 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
108546 ** to contains a zero-length string, all attached databases are 
108547 ** checkpointed.
108548 */
108549 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
108550   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
108551 }
108552
108553 #ifndef SQLITE_OMIT_WAL
108554 /*
108555 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
108556 ** not currently open in WAL mode.
108557 **
108558 ** If a transaction is open on the database being checkpointed, this 
108559 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
108560 ** an error occurs while running the checkpoint, an SQLite error code is 
108561 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
108562 **
108563 ** The mutex on database handle db should be held by the caller. The mutex
108564 ** associated with the specific b-tree being checkpointed is taken by
108565 ** this function while the checkpoint is running.
108566 **
108567 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
108568 ** checkpointed. If an error is encountered it is returned immediately -
108569 ** no attempt is made to checkpoint any remaining databases.
108570 **
108571 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
108572 */
108573 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
108574   int rc = SQLITE_OK;             /* Return code */
108575   int i;                          /* Used to iterate through attached dbs */
108576   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
108577
108578   assert( sqlite3_mutex_held(db->mutex) );
108579   assert( !pnLog || *pnLog==-1 );
108580   assert( !pnCkpt || *pnCkpt==-1 );
108581
108582   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
108583     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
108584       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
108585       pnLog = 0;
108586       pnCkpt = 0;
108587       if( rc==SQLITE_BUSY ){
108588         bBusy = 1;
108589         rc = SQLITE_OK;
108590       }
108591     }
108592   }
108593
108594   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
108595 }
108596 #endif /* SQLITE_OMIT_WAL */
108597
108598 /*
108599 ** This function returns true if main-memory should be used instead of
108600 ** a temporary file for transient pager files and statement journals.
108601 ** The value returned depends on the value of db->temp_store (runtime
108602 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
108603 ** following table describes the relationship between these two values
108604 ** and this functions return value.
108605 **
108606 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
108607 **   -----------------     --------------     ------------------------------
108608 **   0                     any                file      (return 0)
108609 **   1                     1                  file      (return 0)
108610 **   1                     2                  memory    (return 1)
108611 **   1                     0                  file      (return 0)
108612 **   2                     1                  file      (return 0)
108613 **   2                     2                  memory    (return 1)
108614 **   2                     0                  memory    (return 1)
108615 **   3                     any                memory    (return 1)
108616 */
108617 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
108618 #if SQLITE_TEMP_STORE==1
108619   return ( db->temp_store==2 );
108620 #endif
108621 #if SQLITE_TEMP_STORE==2
108622   return ( db->temp_store!=1 );
108623 #endif
108624 #if SQLITE_TEMP_STORE==3
108625   return 1;
108626 #endif
108627 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
108628   return 0;
108629 #endif
108630 }
108631
108632 /*
108633 ** Return UTF-8 encoded English language explanation of the most recent
108634 ** error.
108635 */
108636 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
108637   const char *z;
108638   if( !db ){
108639     return sqlite3ErrStr(SQLITE_NOMEM);
108640   }
108641   if( !sqlite3SafetyCheckSickOrOk(db) ){
108642     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
108643   }
108644   sqlite3_mutex_enter(db->mutex);
108645   if( db->mallocFailed ){
108646     z = sqlite3ErrStr(SQLITE_NOMEM);
108647   }else{
108648     z = (char*)sqlite3_value_text(db->pErr);
108649     assert( !db->mallocFailed );
108650     if( z==0 ){
108651       z = sqlite3ErrStr(db->errCode);
108652     }
108653   }
108654   sqlite3_mutex_leave(db->mutex);
108655   return z;
108656 }
108657
108658 #ifndef SQLITE_OMIT_UTF16
108659 /*
108660 ** Return UTF-16 encoded English language explanation of the most recent
108661 ** error.
108662 */
108663 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
108664   static const u16 outOfMem[] = {
108665     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
108666   };
108667   static const u16 misuse[] = {
108668     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
108669     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
108670     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
108671     'o', 'u', 't', ' ', 
108672     'o', 'f', ' ', 
108673     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
108674   };
108675
108676   const void *z;
108677   if( !db ){
108678     return (void *)outOfMem;
108679   }
108680   if( !sqlite3SafetyCheckSickOrOk(db) ){
108681     return (void *)misuse;
108682   }
108683   sqlite3_mutex_enter(db->mutex);
108684   if( db->mallocFailed ){
108685     z = (void *)outOfMem;
108686   }else{
108687     z = sqlite3_value_text16(db->pErr);
108688     if( z==0 ){
108689       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
108690            SQLITE_UTF8, SQLITE_STATIC);
108691       z = sqlite3_value_text16(db->pErr);
108692     }
108693     /* A malloc() may have failed within the call to sqlite3_value_text16()
108694     ** above. If this is the case, then the db->mallocFailed flag needs to
108695     ** be cleared before returning. Do this directly, instead of via
108696     ** sqlite3ApiExit(), to avoid setting the database handle error message.
108697     */
108698     db->mallocFailed = 0;
108699   }
108700   sqlite3_mutex_leave(db->mutex);
108701   return z;
108702 }
108703 #endif /* SQLITE_OMIT_UTF16 */
108704
108705 /*
108706 ** Return the most recent error code generated by an SQLite routine. If NULL is
108707 ** passed to this function, we assume a malloc() failed during sqlite3_open().
108708 */
108709 SQLITE_API int sqlite3_errcode(sqlite3 *db){
108710   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108711     return SQLITE_MISUSE_BKPT;
108712   }
108713   if( !db || db->mallocFailed ){
108714     return SQLITE_NOMEM;
108715   }
108716   return db->errCode & db->errMask;
108717 }
108718 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
108719   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
108720     return SQLITE_MISUSE_BKPT;
108721   }
108722   if( !db || db->mallocFailed ){
108723     return SQLITE_NOMEM;
108724   }
108725   return db->errCode;
108726 }
108727
108728 /*
108729 ** Create a new collating function for database "db".  The name is zName
108730 ** and the encoding is enc.
108731 */
108732 static int createCollation(
108733   sqlite3* db,
108734   const char *zName, 
108735   u8 enc,
108736   u8 collType,
108737   void* pCtx,
108738   int(*xCompare)(void*,int,const void*,int,const void*),
108739   void(*xDel)(void*)
108740 ){
108741   CollSeq *pColl;
108742   int enc2;
108743   int nName = sqlite3Strlen30(zName);
108744   
108745   assert( sqlite3_mutex_held(db->mutex) );
108746
108747   /* If SQLITE_UTF16 is specified as the encoding type, transform this
108748   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108749   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108750   */
108751   enc2 = enc;
108752   testcase( enc2==SQLITE_UTF16 );
108753   testcase( enc2==SQLITE_UTF16_ALIGNED );
108754   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
108755     enc2 = SQLITE_UTF16NATIVE;
108756   }
108757   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
108758     return SQLITE_MISUSE_BKPT;
108759   }
108760
108761   /* Check if this call is removing or replacing an existing collation 
108762   ** sequence. If so, and there are active VMs, return busy. If there
108763   ** are no active VMs, invalidate any pre-compiled statements.
108764   */
108765   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
108766   if( pColl && pColl->xCmp ){
108767     if( db->activeVdbeCnt ){
108768       sqlite3Error(db, SQLITE_BUSY, 
108769         "unable to delete/modify collation sequence due to active statements");
108770       return SQLITE_BUSY;
108771     }
108772     sqlite3ExpirePreparedStatements(db);
108773
108774     /* If collation sequence pColl was created directly by a call to
108775     ** sqlite3_create_collation, and not generated by synthCollSeq(),
108776     ** then any copies made by synthCollSeq() need to be invalidated.
108777     ** Also, collation destructor - CollSeq.xDel() - function may need
108778     ** to be called.
108779     */ 
108780     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
108781       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
108782       int j;
108783       for(j=0; j<3; j++){
108784         CollSeq *p = &aColl[j];
108785         if( p->enc==pColl->enc ){
108786           if( p->xDel ){
108787             p->xDel(p->pUser);
108788           }
108789           p->xCmp = 0;
108790         }
108791       }
108792     }
108793   }
108794
108795   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
108796   if( pColl==0 ) return SQLITE_NOMEM;
108797   pColl->xCmp = xCompare;
108798   pColl->pUser = pCtx;
108799   pColl->xDel = xDel;
108800   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
108801   pColl->type = collType;
108802   sqlite3Error(db, SQLITE_OK, 0);
108803   return SQLITE_OK;
108804 }
108805
108806
108807 /*
108808 ** This array defines hard upper bounds on limit values.  The
108809 ** initializer must be kept in sync with the SQLITE_LIMIT_*
108810 ** #defines in sqlite3.h.
108811 */
108812 static const int aHardLimit[] = {
108813   SQLITE_MAX_LENGTH,
108814   SQLITE_MAX_SQL_LENGTH,
108815   SQLITE_MAX_COLUMN,
108816   SQLITE_MAX_EXPR_DEPTH,
108817   SQLITE_MAX_COMPOUND_SELECT,
108818   SQLITE_MAX_VDBE_OP,
108819   SQLITE_MAX_FUNCTION_ARG,
108820   SQLITE_MAX_ATTACHED,
108821   SQLITE_MAX_LIKE_PATTERN_LENGTH,
108822   SQLITE_MAX_VARIABLE_NUMBER,
108823   SQLITE_MAX_TRIGGER_DEPTH,
108824 };
108825
108826 /*
108827 ** Make sure the hard limits are set to reasonable values
108828 */
108829 #if SQLITE_MAX_LENGTH<100
108830 # error SQLITE_MAX_LENGTH must be at least 100
108831 #endif
108832 #if SQLITE_MAX_SQL_LENGTH<100
108833 # error SQLITE_MAX_SQL_LENGTH must be at least 100
108834 #endif
108835 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
108836 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
108837 #endif
108838 #if SQLITE_MAX_COMPOUND_SELECT<2
108839 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
108840 #endif
108841 #if SQLITE_MAX_VDBE_OP<40
108842 # error SQLITE_MAX_VDBE_OP must be at least 40
108843 #endif
108844 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
108845 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
108846 #endif
108847 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
108848 # error SQLITE_MAX_ATTACHED must be between 0 and 62
108849 #endif
108850 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
108851 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
108852 #endif
108853 #if SQLITE_MAX_COLUMN>32767
108854 # error SQLITE_MAX_COLUMN must not exceed 32767
108855 #endif
108856 #if SQLITE_MAX_TRIGGER_DEPTH<1
108857 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
108858 #endif
108859
108860
108861 /*
108862 ** Change the value of a limit.  Report the old value.
108863 ** If an invalid limit index is supplied, report -1.
108864 ** Make no changes but still report the old value if the
108865 ** new limit is negative.
108866 **
108867 ** A new lower limit does not shrink existing constructs.
108868 ** It merely prevents new constructs that exceed the limit
108869 ** from forming.
108870 */
108871 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
108872   int oldLimit;
108873
108874
108875   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
108876   ** there is a hard upper bound set at compile-time by a C preprocessor
108877   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
108878   ** "_MAX_".)
108879   */
108880   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
108881   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
108882   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
108883   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
108884   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
108885   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
108886   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
108887   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
108888   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
108889                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
108890   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
108891   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
108892   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
108893
108894
108895   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
108896     return -1;
108897   }
108898   oldLimit = db->aLimit[limitId];
108899   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
108900     if( newLimit>aHardLimit[limitId] ){
108901       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
108902     }
108903     db->aLimit[limitId] = newLimit;
108904   }
108905   return oldLimit;                     /* IMP: R-53341-35419 */
108906 }
108907
108908 /*
108909 ** This routine does the work of opening a database on behalf of
108910 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
108911 ** is UTF-8 encoded.
108912 */
108913 static int openDatabase(
108914   const char *zFilename, /* Database filename UTF-8 encoded */
108915   sqlite3 **ppDb,        /* OUT: Returned database handle */
108916   unsigned flags,        /* Operational flags */
108917   const char *zVfs       /* Name of the VFS to use */
108918 ){
108919   sqlite3 *db;
108920   int rc;
108921   int isThreadsafe;
108922
108923   *ppDb = 0;
108924 #ifndef SQLITE_OMIT_AUTOINIT
108925   rc = sqlite3_initialize();
108926   if( rc ) return rc;
108927 #endif
108928
108929   /* Only allow sensible combinations of bits in the flags argument.  
108930   ** Throw an error if any non-sense combination is used.  If we
108931   ** do not block illegal combinations here, it could trigger
108932   ** assert() statements in deeper layers.  Sensible combinations
108933   ** are:
108934   **
108935   **  1:  SQLITE_OPEN_READONLY
108936   **  2:  SQLITE_OPEN_READWRITE
108937   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
108938   */
108939   assert( SQLITE_OPEN_READONLY  == 0x01 );
108940   assert( SQLITE_OPEN_READWRITE == 0x02 );
108941   assert( SQLITE_OPEN_CREATE    == 0x04 );
108942   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
108943   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
108944   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
108945   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
108946
108947   if( sqlite3GlobalConfig.bCoreMutex==0 ){
108948     isThreadsafe = 0;
108949   }else if( flags & SQLITE_OPEN_NOMUTEX ){
108950     isThreadsafe = 0;
108951   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
108952     isThreadsafe = 1;
108953   }else{
108954     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
108955   }
108956   if( flags & SQLITE_OPEN_PRIVATECACHE ){
108957     flags &= ~SQLITE_OPEN_SHAREDCACHE;
108958   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
108959     flags |= SQLITE_OPEN_SHAREDCACHE;
108960   }
108961
108962   /* Remove harmful bits from the flags parameter
108963   **
108964   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
108965   ** dealt with in the previous code block.  Besides these, the only
108966   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
108967   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
108968   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
108969   ** off all other flags.
108970   */
108971   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
108972                SQLITE_OPEN_EXCLUSIVE |
108973                SQLITE_OPEN_MAIN_DB |
108974                SQLITE_OPEN_TEMP_DB | 
108975                SQLITE_OPEN_TRANSIENT_DB | 
108976                SQLITE_OPEN_MAIN_JOURNAL | 
108977                SQLITE_OPEN_TEMP_JOURNAL | 
108978                SQLITE_OPEN_SUBJOURNAL | 
108979                SQLITE_OPEN_MASTER_JOURNAL |
108980                SQLITE_OPEN_NOMUTEX |
108981                SQLITE_OPEN_FULLMUTEX |
108982                SQLITE_OPEN_WAL
108983              );
108984
108985   /* Allocate the sqlite data structure */
108986   db = sqlite3MallocZero( sizeof(sqlite3) );
108987   if( db==0 ) goto opendb_out;
108988   if( isThreadsafe ){
108989     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
108990     if( db->mutex==0 ){
108991       sqlite3_free(db);
108992       db = 0;
108993       goto opendb_out;
108994     }
108995   }
108996   sqlite3_mutex_enter(db->mutex);
108997   db->errMask = 0xff;
108998   db->nDb = 2;
108999   db->magic = SQLITE_MAGIC_BUSY;
109000   db->aDb = db->aDbStatic;
109001
109002   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
109003   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
109004   db->autoCommit = 1;
109005   db->nextAutovac = -1;
109006   db->nextPagesize = 0;
109007   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
109008 #if SQLITE_DEFAULT_FILE_FORMAT<4
109009                  | SQLITE_LegacyFileFmt
109010 #endif
109011 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
109012                  | SQLITE_LoadExtension
109013 #endif
109014 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
109015                  | SQLITE_RecTriggers
109016 #endif
109017 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
109018                  | SQLITE_ForeignKeys
109019 #endif
109020       ;
109021   sqlite3HashInit(&db->aCollSeq);
109022 #ifndef SQLITE_OMIT_VIRTUALTABLE
109023   sqlite3HashInit(&db->aModule);
109024 #endif
109025
109026   db->pVfs = sqlite3_vfs_find(zVfs);
109027   if( !db->pVfs ){
109028     rc = SQLITE_ERROR;
109029     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
109030     goto opendb_out;
109031   }
109032
109033   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
109034   ** and UTF-16, so add a version for each to avoid any unnecessary
109035   ** conversions. The only error that can occur here is a malloc() failure.
109036   */
109037   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
109038                   binCollFunc, 0);
109039   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
109040                   binCollFunc, 0);
109041   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
109042                   binCollFunc, 0);
109043   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
109044                   binCollFunc, 0);
109045   if( db->mallocFailed ){
109046     goto opendb_out;
109047   }
109048   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
109049   assert( db->pDfltColl!=0 );
109050
109051   /* Also add a UTF-8 case-insensitive collation sequence. */
109052   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
109053                   nocaseCollatingFunc, 0);
109054
109055   /* Open the backend database driver */
109056   db->openFlags = flags;
109057   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
109058                         flags | SQLITE_OPEN_MAIN_DB);
109059   if( rc!=SQLITE_OK ){
109060     if( rc==SQLITE_IOERR_NOMEM ){
109061       rc = SQLITE_NOMEM;
109062     }
109063     sqlite3Error(db, rc, 0);
109064     goto opendb_out;
109065   }
109066   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
109067   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
109068
109069
109070   /* The default safety_level for the main database is 'full'; for the temp
109071   ** database it is 'NONE'. This matches the pager layer defaults.  
109072   */
109073   db->aDb[0].zName = "main";
109074   db->aDb[0].safety_level = 3;
109075   db->aDb[1].zName = "temp";
109076   db->aDb[1].safety_level = 1;
109077
109078   db->magic = SQLITE_MAGIC_OPEN;
109079   if( db->mallocFailed ){
109080     goto opendb_out;
109081   }
109082
109083   /* Register all built-in functions, but do not attempt to read the
109084   ** database schema yet. This is delayed until the first time the database
109085   ** is accessed.
109086   */
109087   sqlite3Error(db, SQLITE_OK, 0);
109088   sqlite3RegisterBuiltinFunctions(db);
109089
109090   /* Load automatic extensions - extensions that have been registered
109091   ** using the sqlite3_automatic_extension() API.
109092   */
109093   sqlite3AutoLoadExtensions(db);
109094   rc = sqlite3_errcode(db);
109095   if( rc!=SQLITE_OK ){
109096     goto opendb_out;
109097   }
109098
109099 #ifdef SQLITE_ENABLE_FTS1
109100   if( !db->mallocFailed ){
109101     extern int sqlite3Fts1Init(sqlite3*);
109102     rc = sqlite3Fts1Init(db);
109103   }
109104 #endif
109105
109106 #ifdef SQLITE_ENABLE_FTS2
109107   if( !db->mallocFailed && rc==SQLITE_OK ){
109108     extern int sqlite3Fts2Init(sqlite3*);
109109     rc = sqlite3Fts2Init(db);
109110   }
109111 #endif
109112
109113 #ifdef SQLITE_ENABLE_FTS3
109114   if( !db->mallocFailed && rc==SQLITE_OK ){
109115     rc = sqlite3Fts3Init(db);
109116   }
109117 #endif
109118
109119 #ifdef SQLITE_ENABLE_ICU
109120   if( !db->mallocFailed && rc==SQLITE_OK ){
109121     rc = sqlite3IcuInit(db);
109122   }
109123 #endif
109124
109125 #ifdef SQLITE_ENABLE_RTREE
109126   if( !db->mallocFailed && rc==SQLITE_OK){
109127     rc = sqlite3RtreeInit(db);
109128   }
109129 #endif
109130
109131   sqlite3Error(db, rc, 0);
109132
109133   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
109134   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
109135   ** mode.  Doing nothing at all also makes NORMAL the default.
109136   */
109137 #ifdef SQLITE_DEFAULT_LOCKING_MODE
109138   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
109139   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
109140                           SQLITE_DEFAULT_LOCKING_MODE);
109141 #endif
109142
109143   /* Enable the lookaside-malloc subsystem */
109144   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
109145                         sqlite3GlobalConfig.nLookaside);
109146
109147   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
109148
109149 opendb_out:
109150   if( db ){
109151     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
109152     sqlite3_mutex_leave(db->mutex);
109153   }
109154   rc = sqlite3_errcode(db);
109155   if( rc==SQLITE_NOMEM ){
109156     sqlite3_close(db);
109157     db = 0;
109158   }else if( rc!=SQLITE_OK ){
109159     db->magic = SQLITE_MAGIC_SICK;
109160   }
109161   *ppDb = db;
109162   return sqlite3ApiExit(0, rc);
109163 }
109164
109165 /*
109166 ** Open a new database handle.
109167 */
109168 SQLITE_API int sqlite3_open(
109169   const char *zFilename, 
109170   sqlite3 **ppDb 
109171 ){
109172   return openDatabase(zFilename, ppDb,
109173                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109174 }
109175 SQLITE_API int sqlite3_open_v2(
109176   const char *filename,   /* Database filename (UTF-8) */
109177   sqlite3 **ppDb,         /* OUT: SQLite db handle */
109178   int flags,              /* Flags */
109179   const char *zVfs        /* Name of VFS module to use */
109180 ){
109181   return openDatabase(filename, ppDb, flags, zVfs);
109182 }
109183
109184 #ifndef SQLITE_OMIT_UTF16
109185 /*
109186 ** Open a new database handle.
109187 */
109188 SQLITE_API int sqlite3_open16(
109189   const void *zFilename, 
109190   sqlite3 **ppDb
109191 ){
109192   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
109193   sqlite3_value *pVal;
109194   int rc;
109195
109196   assert( zFilename );
109197   assert( ppDb );
109198   *ppDb = 0;
109199 #ifndef SQLITE_OMIT_AUTOINIT
109200   rc = sqlite3_initialize();
109201   if( rc ) return rc;
109202 #endif
109203   pVal = sqlite3ValueNew(0);
109204   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
109205   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
109206   if( zFilename8 ){
109207     rc = openDatabase(zFilename8, ppDb,
109208                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109209     assert( *ppDb || rc==SQLITE_NOMEM );
109210     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
109211       ENC(*ppDb) = SQLITE_UTF16NATIVE;
109212     }
109213   }else{
109214     rc = SQLITE_NOMEM;
109215   }
109216   sqlite3ValueFree(pVal);
109217
109218   return sqlite3ApiExit(0, rc);
109219 }
109220 #endif /* SQLITE_OMIT_UTF16 */
109221
109222 /*
109223 ** Register a new collation sequence with the database handle db.
109224 */
109225 SQLITE_API int sqlite3_create_collation(
109226   sqlite3* db, 
109227   const char *zName, 
109228   int enc, 
109229   void* pCtx,
109230   int(*xCompare)(void*,int,const void*,int,const void*)
109231 ){
109232   int rc;
109233   sqlite3_mutex_enter(db->mutex);
109234   assert( !db->mallocFailed );
109235   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109236   rc = sqlite3ApiExit(db, rc);
109237   sqlite3_mutex_leave(db->mutex);
109238   return rc;
109239 }
109240
109241 /*
109242 ** Register a new collation sequence with the database handle db.
109243 */
109244 SQLITE_API int sqlite3_create_collation_v2(
109245   sqlite3* db, 
109246   const char *zName, 
109247   int enc, 
109248   void* pCtx,
109249   int(*xCompare)(void*,int,const void*,int,const void*),
109250   void(*xDel)(void*)
109251 ){
109252   int rc;
109253   sqlite3_mutex_enter(db->mutex);
109254   assert( !db->mallocFailed );
109255   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
109256   rc = sqlite3ApiExit(db, rc);
109257   sqlite3_mutex_leave(db->mutex);
109258   return rc;
109259 }
109260
109261 #ifndef SQLITE_OMIT_UTF16
109262 /*
109263 ** Register a new collation sequence with the database handle db.
109264 */
109265 SQLITE_API int sqlite3_create_collation16(
109266   sqlite3* db, 
109267   const void *zName,
109268   int enc, 
109269   void* pCtx,
109270   int(*xCompare)(void*,int,const void*,int,const void*)
109271 ){
109272   int rc = SQLITE_OK;
109273   char *zName8;
109274   sqlite3_mutex_enter(db->mutex);
109275   assert( !db->mallocFailed );
109276   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
109277   if( zName8 ){
109278     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109279     sqlite3DbFree(db, zName8);
109280   }
109281   rc = sqlite3ApiExit(db, rc);
109282   sqlite3_mutex_leave(db->mutex);
109283   return rc;
109284 }
109285 #endif /* SQLITE_OMIT_UTF16 */
109286
109287 /*
109288 ** Register a collation sequence factory callback with the database handle
109289 ** db. Replace any previously installed collation sequence factory.
109290 */
109291 SQLITE_API int sqlite3_collation_needed(
109292   sqlite3 *db, 
109293   void *pCollNeededArg, 
109294   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
109295 ){
109296   sqlite3_mutex_enter(db->mutex);
109297   db->xCollNeeded = xCollNeeded;
109298   db->xCollNeeded16 = 0;
109299   db->pCollNeededArg = pCollNeededArg;
109300   sqlite3_mutex_leave(db->mutex);
109301   return SQLITE_OK;
109302 }
109303
109304 #ifndef SQLITE_OMIT_UTF16
109305 /*
109306 ** Register a collation sequence factory callback with the database handle
109307 ** db. Replace any previously installed collation sequence factory.
109308 */
109309 SQLITE_API int sqlite3_collation_needed16(
109310   sqlite3 *db, 
109311   void *pCollNeededArg, 
109312   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
109313 ){
109314   sqlite3_mutex_enter(db->mutex);
109315   db->xCollNeeded = 0;
109316   db->xCollNeeded16 = xCollNeeded16;
109317   db->pCollNeededArg = pCollNeededArg;
109318   sqlite3_mutex_leave(db->mutex);
109319   return SQLITE_OK;
109320 }
109321 #endif /* SQLITE_OMIT_UTF16 */
109322
109323 #ifndef SQLITE_OMIT_DEPRECATED
109324 /*
109325 ** This function is now an anachronism. It used to be used to recover from a
109326 ** malloc() failure, but SQLite now does this automatically.
109327 */
109328 SQLITE_API int sqlite3_global_recover(void){
109329   return SQLITE_OK;
109330 }
109331 #endif
109332
109333 /*
109334 ** Test to see whether or not the database connection is in autocommit
109335 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
109336 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
109337 ** by the next COMMIT or ROLLBACK.
109338 **
109339 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
109340 */
109341 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
109342   return db->autoCommit;
109343 }
109344
109345 /*
109346 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
109347 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
109348 ** constants.  They server two purposes:
109349 **
109350 **   1.  Serve as a convenient place to set a breakpoint in a debugger
109351 **       to detect when version error conditions occurs.
109352 **
109353 **   2.  Invoke sqlite3_log() to provide the source code location where
109354 **       a low-level error is first detected.
109355 */
109356 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
109357   testcase( sqlite3GlobalConfig.xLog!=0 );
109358   sqlite3_log(SQLITE_CORRUPT,
109359               "database corruption at line %d of [%.10s]",
109360               lineno, 20+sqlite3_sourceid());
109361   return SQLITE_CORRUPT;
109362 }
109363 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
109364   testcase( sqlite3GlobalConfig.xLog!=0 );
109365   sqlite3_log(SQLITE_MISUSE, 
109366               "misuse at line %d of [%.10s]",
109367               lineno, 20+sqlite3_sourceid());
109368   return SQLITE_MISUSE;
109369 }
109370 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
109371   testcase( sqlite3GlobalConfig.xLog!=0 );
109372   sqlite3_log(SQLITE_CANTOPEN, 
109373               "cannot open file at line %d of [%.10s]",
109374               lineno, 20+sqlite3_sourceid());
109375   return SQLITE_CANTOPEN;
109376 }
109377
109378
109379 #ifndef SQLITE_OMIT_DEPRECATED
109380 /*
109381 ** This is a convenience routine that makes sure that all thread-specific
109382 ** data for this thread has been deallocated.
109383 **
109384 ** SQLite no longer uses thread-specific data so this routine is now a
109385 ** no-op.  It is retained for historical compatibility.
109386 */
109387 SQLITE_API void sqlite3_thread_cleanup(void){
109388 }
109389 #endif
109390
109391 /*
109392 ** Return meta information about a specific column of a database table.
109393 ** See comment in sqlite3.h (sqlite.h.in) for details.
109394 */
109395 #ifdef SQLITE_ENABLE_COLUMN_METADATA
109396 SQLITE_API int sqlite3_table_column_metadata(
109397   sqlite3 *db,                /* Connection handle */
109398   const char *zDbName,        /* Database name or NULL */
109399   const char *zTableName,     /* Table name */
109400   const char *zColumnName,    /* Column name */
109401   char const **pzDataType,    /* OUTPUT: Declared data type */
109402   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
109403   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
109404   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
109405   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
109406 ){
109407   int rc;
109408   char *zErrMsg = 0;
109409   Table *pTab = 0;
109410   Column *pCol = 0;
109411   int iCol;
109412
109413   char const *zDataType = 0;
109414   char const *zCollSeq = 0;
109415   int notnull = 0;
109416   int primarykey = 0;
109417   int autoinc = 0;
109418
109419   /* Ensure the database schema has been loaded */
109420   sqlite3_mutex_enter(db->mutex);
109421   sqlite3BtreeEnterAll(db);
109422   rc = sqlite3Init(db, &zErrMsg);
109423   if( SQLITE_OK!=rc ){
109424     goto error_out;
109425   }
109426
109427   /* Locate the table in question */
109428   pTab = sqlite3FindTable(db, zTableName, zDbName);
109429   if( !pTab || pTab->pSelect ){
109430     pTab = 0;
109431     goto error_out;
109432   }
109433
109434   /* Find the column for which info is requested */
109435   if( sqlite3IsRowid(zColumnName) ){
109436     iCol = pTab->iPKey;
109437     if( iCol>=0 ){
109438       pCol = &pTab->aCol[iCol];
109439     }
109440   }else{
109441     for(iCol=0; iCol<pTab->nCol; iCol++){
109442       pCol = &pTab->aCol[iCol];
109443       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
109444         break;
109445       }
109446     }
109447     if( iCol==pTab->nCol ){
109448       pTab = 0;
109449       goto error_out;
109450     }
109451   }
109452
109453   /* The following block stores the meta information that will be returned
109454   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
109455   ** and autoinc. At this point there are two possibilities:
109456   ** 
109457   **     1. The specified column name was rowid", "oid" or "_rowid_" 
109458   **        and there is no explicitly declared IPK column. 
109459   **
109460   **     2. The table is not a view and the column name identified an 
109461   **        explicitly declared column. Copy meta information from *pCol.
109462   */ 
109463   if( pCol ){
109464     zDataType = pCol->zType;
109465     zCollSeq = pCol->zColl;
109466     notnull = pCol->notNull!=0;
109467     primarykey  = pCol->isPrimKey!=0;
109468     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
109469   }else{
109470     zDataType = "INTEGER";
109471     primarykey = 1;
109472   }
109473   if( !zCollSeq ){
109474     zCollSeq = "BINARY";
109475   }
109476
109477 error_out:
109478   sqlite3BtreeLeaveAll(db);
109479
109480   /* Whether the function call succeeded or failed, set the output parameters
109481   ** to whatever their local counterparts contain. If an error did occur,
109482   ** this has the effect of zeroing all output parameters.
109483   */
109484   if( pzDataType ) *pzDataType = zDataType;
109485   if( pzCollSeq ) *pzCollSeq = zCollSeq;
109486   if( pNotNull ) *pNotNull = notnull;
109487   if( pPrimaryKey ) *pPrimaryKey = primarykey;
109488   if( pAutoinc ) *pAutoinc = autoinc;
109489
109490   if( SQLITE_OK==rc && !pTab ){
109491     sqlite3DbFree(db, zErrMsg);
109492     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
109493         zColumnName);
109494     rc = SQLITE_ERROR;
109495   }
109496   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
109497   sqlite3DbFree(db, zErrMsg);
109498   rc = sqlite3ApiExit(db, rc);
109499   sqlite3_mutex_leave(db->mutex);
109500   return rc;
109501 }
109502 #endif
109503
109504 /*
109505 ** Sleep for a little while.  Return the amount of time slept.
109506 */
109507 SQLITE_API int sqlite3_sleep(int ms){
109508   sqlite3_vfs *pVfs;
109509   int rc;
109510   pVfs = sqlite3_vfs_find(0);
109511   if( pVfs==0 ) return 0;
109512
109513   /* This function works in milliseconds, but the underlying OsSleep() 
109514   ** API uses microseconds. Hence the 1000's.
109515   */
109516   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
109517   return rc;
109518 }
109519
109520 /*
109521 ** Enable or disable the extended result codes.
109522 */
109523 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
109524   sqlite3_mutex_enter(db->mutex);
109525   db->errMask = onoff ? 0xffffffff : 0xff;
109526   sqlite3_mutex_leave(db->mutex);
109527   return SQLITE_OK;
109528 }
109529
109530 /*
109531 ** Invoke the xFileControl method on a particular database.
109532 */
109533 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
109534   int rc = SQLITE_ERROR;
109535   int iDb;
109536   sqlite3_mutex_enter(db->mutex);
109537   if( zDbName==0 ){
109538     iDb = 0;
109539   }else{
109540     for(iDb=0; iDb<db->nDb; iDb++){
109541       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
109542     }
109543   }
109544   if( iDb<db->nDb ){
109545     Btree *pBtree = db->aDb[iDb].pBt;
109546     if( pBtree ){
109547       Pager *pPager;
109548       sqlite3_file *fd;
109549       sqlite3BtreeEnter(pBtree);
109550       pPager = sqlite3BtreePager(pBtree);
109551       assert( pPager!=0 );
109552       fd = sqlite3PagerFile(pPager);
109553       assert( fd!=0 );
109554       if( op==SQLITE_FCNTL_FILE_POINTER ){
109555         *(sqlite3_file**)pArg = fd;
109556         rc = SQLITE_OK;
109557       }else if( fd->pMethods ){
109558         rc = sqlite3OsFileControl(fd, op, pArg);
109559       }else{
109560         rc = SQLITE_NOTFOUND;
109561       }
109562       sqlite3BtreeLeave(pBtree);
109563     }
109564   }
109565   sqlite3_mutex_leave(db->mutex);
109566   return rc;   
109567 }
109568
109569 /*
109570 ** Interface to the testing logic.
109571 */
109572 SQLITE_API int sqlite3_test_control(int op, ...){
109573   int rc = 0;
109574 #ifndef SQLITE_OMIT_BUILTIN_TEST
109575   va_list ap;
109576   va_start(ap, op);
109577   switch( op ){
109578
109579     /*
109580     ** Save the current state of the PRNG.
109581     */
109582     case SQLITE_TESTCTRL_PRNG_SAVE: {
109583       sqlite3PrngSaveState();
109584       break;
109585     }
109586
109587     /*
109588     ** Restore the state of the PRNG to the last state saved using
109589     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
109590     ** this verb acts like PRNG_RESET.
109591     */
109592     case SQLITE_TESTCTRL_PRNG_RESTORE: {
109593       sqlite3PrngRestoreState();
109594       break;
109595     }
109596
109597     /*
109598     ** Reset the PRNG back to its uninitialized state.  The next call
109599     ** to sqlite3_randomness() will reseed the PRNG using a single call
109600     ** to the xRandomness method of the default VFS.
109601     */
109602     case SQLITE_TESTCTRL_PRNG_RESET: {
109603       sqlite3PrngResetState();
109604       break;
109605     }
109606
109607     /*
109608     **  sqlite3_test_control(BITVEC_TEST, size, program)
109609     **
109610     ** Run a test against a Bitvec object of size.  The program argument
109611     ** is an array of integers that defines the test.  Return -1 on a
109612     ** memory allocation error, 0 on success, or non-zero for an error.
109613     ** See the sqlite3BitvecBuiltinTest() for additional information.
109614     */
109615     case SQLITE_TESTCTRL_BITVEC_TEST: {
109616       int sz = va_arg(ap, int);
109617       int *aProg = va_arg(ap, int*);
109618       rc = sqlite3BitvecBuiltinTest(sz, aProg);
109619       break;
109620     }
109621
109622     /*
109623     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
109624     **
109625     ** Register hooks to call to indicate which malloc() failures 
109626     ** are benign.
109627     */
109628     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
109629       typedef void (*void_function)(void);
109630       void_function xBenignBegin;
109631       void_function xBenignEnd;
109632       xBenignBegin = va_arg(ap, void_function);
109633       xBenignEnd = va_arg(ap, void_function);
109634       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
109635       break;
109636     }
109637
109638     /*
109639     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
109640     **
109641     ** Set the PENDING byte to the value in the argument, if X>0.
109642     ** Make no changes if X==0.  Return the value of the pending byte
109643     ** as it existing before this routine was called.
109644     **
109645     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
109646     ** an incompatible database file format.  Changing the PENDING byte
109647     ** while any database connection is open results in undefined and
109648     ** dileterious behavior.
109649     */
109650     case SQLITE_TESTCTRL_PENDING_BYTE: {
109651       rc = PENDING_BYTE;
109652 #ifndef SQLITE_OMIT_WSD
109653       {
109654         unsigned int newVal = va_arg(ap, unsigned int);
109655         if( newVal ) sqlite3PendingByte = newVal;
109656       }
109657 #endif
109658       break;
109659     }
109660
109661     /*
109662     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
109663     **
109664     ** This action provides a run-time test to see whether or not
109665     ** assert() was enabled at compile-time.  If X is true and assert()
109666     ** is enabled, then the return value is true.  If X is true and
109667     ** assert() is disabled, then the return value is zero.  If X is
109668     ** false and assert() is enabled, then the assertion fires and the
109669     ** process aborts.  If X is false and assert() is disabled, then the
109670     ** return value is zero.
109671     */
109672     case SQLITE_TESTCTRL_ASSERT: {
109673       volatile int x = 0;
109674       assert( (x = va_arg(ap,int))!=0 );
109675       rc = x;
109676       break;
109677     }
109678
109679
109680     /*
109681     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
109682     **
109683     ** This action provides a run-time test to see how the ALWAYS and
109684     ** NEVER macros were defined at compile-time.
109685     **
109686     ** The return value is ALWAYS(X).  
109687     **
109688     ** The recommended test is X==2.  If the return value is 2, that means
109689     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
109690     ** default setting.  If the return value is 1, then ALWAYS() is either
109691     ** hard-coded to true or else it asserts if its argument is false.
109692     ** The first behavior (hard-coded to true) is the case if
109693     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
109694     ** behavior (assert if the argument to ALWAYS() is false) is the case if
109695     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
109696     **
109697     ** The run-time test procedure might look something like this:
109698     **
109699     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
109700     **      // ALWAYS() and NEVER() are no-op pass-through macros
109701     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
109702     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
109703     **    }else{
109704     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
109705     **    }
109706     */
109707     case SQLITE_TESTCTRL_ALWAYS: {
109708       int x = va_arg(ap,int);
109709       rc = ALWAYS(x);
109710       break;
109711     }
109712
109713     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
109714     **
109715     ** Set the nReserve size to N for the main database on the database
109716     ** connection db.
109717     */
109718     case SQLITE_TESTCTRL_RESERVE: {
109719       sqlite3 *db = va_arg(ap, sqlite3*);
109720       int x = va_arg(ap,int);
109721       sqlite3_mutex_enter(db->mutex);
109722       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
109723       sqlite3_mutex_leave(db->mutex);
109724       break;
109725     }
109726
109727     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
109728     **
109729     ** Enable or disable various optimizations for testing purposes.  The 
109730     ** argument N is a bitmask of optimizations to be disabled.  For normal
109731     ** operation N should be 0.  The idea is that a test program (like the
109732     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
109733     ** with various optimizations disabled to verify that the same answer
109734     ** is obtained in every case.
109735     */
109736     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
109737       sqlite3 *db = va_arg(ap, sqlite3*);
109738       int x = va_arg(ap,int);
109739       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
109740       break;
109741     }
109742
109743 #ifdef SQLITE_N_KEYWORD
109744     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
109745     **
109746     ** If zWord is a keyword recognized by the parser, then return the
109747     ** number of keywords.  Or if zWord is not a keyword, return 0.
109748     ** 
109749     ** This test feature is only available in the amalgamation since
109750     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
109751     ** is built using separate source files.
109752     */
109753     case SQLITE_TESTCTRL_ISKEYWORD: {
109754       const char *zWord = va_arg(ap, const char*);
109755       int n = sqlite3Strlen30(zWord);
109756       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
109757       break;
109758     }
109759 #endif 
109760
109761     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
109762     **
109763     ** Return the size of a pcache header in bytes.
109764     */
109765     case SQLITE_TESTCTRL_PGHDRSZ: {
109766       rc = sizeof(PgHdr);
109767       break;
109768     }
109769
109770     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
109771     **
109772     ** Pass pFree into sqlite3ScratchFree(). 
109773     ** If sz>0 then allocate a scratch buffer into pNew.  
109774     */
109775     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
109776       void *pFree, **ppNew;
109777       int sz;
109778       sz = va_arg(ap, int);
109779       ppNew = va_arg(ap, void**);
109780       pFree = va_arg(ap, void*);
109781       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
109782       sqlite3ScratchFree(pFree);
109783       break;
109784     }
109785
109786   }
109787   va_end(ap);
109788 #endif /* SQLITE_OMIT_BUILTIN_TEST */
109789   return rc;
109790 }
109791
109792 /************** End of main.c ************************************************/
109793 /************** Begin file notify.c ******************************************/
109794 /*
109795 ** 2009 March 3
109796 **
109797 ** The author disclaims copyright to this source code.  In place of
109798 ** a legal notice, here is a blessing:
109799 **
109800 **    May you do good and not evil.
109801 **    May you find forgiveness for yourself and forgive others.
109802 **    May you share freely, never taking more than you give.
109803 **
109804 *************************************************************************
109805 **
109806 ** This file contains the implementation of the sqlite3_unlock_notify()
109807 ** API method and its associated functionality.
109808 */
109809
109810 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
109811 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109812
109813 /*
109814 ** Public interfaces:
109815 **
109816 **   sqlite3ConnectionBlocked()
109817 **   sqlite3ConnectionUnlocked()
109818 **   sqlite3ConnectionClosed()
109819 **   sqlite3_unlock_notify()
109820 */
109821
109822 #define assertMutexHeld() \
109823   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
109824
109825 /*
109826 ** Head of a linked list of all sqlite3 objects created by this process
109827 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
109828 ** is not NULL. This variable may only accessed while the STATIC_MASTER
109829 ** mutex is held.
109830 */
109831 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
109832
109833 #ifndef NDEBUG
109834 /*
109835 ** This function is a complex assert() that verifies the following 
109836 ** properties of the blocked connections list:
109837 **
109838 **   1) Each entry in the list has a non-NULL value for either 
109839 **      pUnlockConnection or pBlockingConnection, or both.
109840 **
109841 **   2) All entries in the list that share a common value for 
109842 **      xUnlockNotify are grouped together.
109843 **
109844 **   3) If the argument db is not NULL, then none of the entries in the
109845 **      blocked connections list have pUnlockConnection or pBlockingConnection
109846 **      set to db. This is used when closing connection db.
109847 */
109848 static void checkListProperties(sqlite3 *db){
109849   sqlite3 *p;
109850   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
109851     int seen = 0;
109852     sqlite3 *p2;
109853
109854     /* Verify property (1) */
109855     assert( p->pUnlockConnection || p->pBlockingConnection );
109856
109857     /* Verify property (2) */
109858     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
109859       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
109860       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
109861       assert( db==0 || p->pUnlockConnection!=db );
109862       assert( db==0 || p->pBlockingConnection!=db );
109863     }
109864   }
109865 }
109866 #else
109867 # define checkListProperties(x)
109868 #endif
109869
109870 /*
109871 ** Remove connection db from the blocked connections list. If connection
109872 ** db is not currently a part of the list, this function is a no-op.
109873 */
109874 static void removeFromBlockedList(sqlite3 *db){
109875   sqlite3 **pp;
109876   assertMutexHeld();
109877   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
109878     if( *pp==db ){
109879       *pp = (*pp)->pNextBlocked;
109880       break;
109881     }
109882   }
109883 }
109884
109885 /*
109886 ** Add connection db to the blocked connections list. It is assumed
109887 ** that it is not already a part of the list.
109888 */
109889 static void addToBlockedList(sqlite3 *db){
109890   sqlite3 **pp;
109891   assertMutexHeld();
109892   for(
109893     pp=&sqlite3BlockedList; 
109894     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
109895     pp=&(*pp)->pNextBlocked
109896   );
109897   db->pNextBlocked = *pp;
109898   *pp = db;
109899 }
109900
109901 /*
109902 ** Obtain the STATIC_MASTER mutex.
109903 */
109904 static void enterMutex(void){
109905   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
109906   checkListProperties(0);
109907 }
109908
109909 /*
109910 ** Release the STATIC_MASTER mutex.
109911 */
109912 static void leaveMutex(void){
109913   assertMutexHeld();
109914   checkListProperties(0);
109915   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
109916 }
109917
109918 /*
109919 ** Register an unlock-notify callback.
109920 **
109921 ** This is called after connection "db" has attempted some operation
109922 ** but has received an SQLITE_LOCKED error because another connection
109923 ** (call it pOther) in the same process was busy using the same shared
109924 ** cache.  pOther is found by looking at db->pBlockingConnection.
109925 **
109926 ** If there is no blocking connection, the callback is invoked immediately,
109927 ** before this routine returns.
109928 **
109929 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
109930 ** a deadlock.
109931 **
109932 ** Otherwise, make arrangements to invoke xNotify when pOther drops
109933 ** its locks.
109934 **
109935 ** Each call to this routine overrides any prior callbacks registered
109936 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
109937 ** cancelled.
109938 */
109939 SQLITE_API int sqlite3_unlock_notify(
109940   sqlite3 *db,
109941   void (*xNotify)(void **, int),
109942   void *pArg
109943 ){
109944   int rc = SQLITE_OK;
109945
109946   sqlite3_mutex_enter(db->mutex);
109947   enterMutex();
109948
109949   if( xNotify==0 ){
109950     removeFromBlockedList(db);
109951     db->pBlockingConnection = 0;
109952     db->pUnlockConnection = 0;
109953     db->xUnlockNotify = 0;
109954     db->pUnlockArg = 0;
109955   }else if( 0==db->pBlockingConnection ){
109956     /* The blocking transaction has been concluded. Or there never was a 
109957     ** blocking transaction. In either case, invoke the notify callback
109958     ** immediately. 
109959     */
109960     xNotify(&pArg, 1);
109961   }else{
109962     sqlite3 *p;
109963
109964     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
109965     if( p ){
109966       rc = SQLITE_LOCKED;              /* Deadlock detected. */
109967     }else{
109968       db->pUnlockConnection = db->pBlockingConnection;
109969       db->xUnlockNotify = xNotify;
109970       db->pUnlockArg = pArg;
109971       removeFromBlockedList(db);
109972       addToBlockedList(db);
109973     }
109974   }
109975
109976   leaveMutex();
109977   assert( !db->mallocFailed );
109978   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
109979   sqlite3_mutex_leave(db->mutex);
109980   return rc;
109981 }
109982
109983 /*
109984 ** This function is called while stepping or preparing a statement 
109985 ** associated with connection db. The operation will return SQLITE_LOCKED
109986 ** to the user because it requires a lock that will not be available
109987 ** until connection pBlocker concludes its current transaction.
109988 */
109989 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
109990   enterMutex();
109991   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
109992     addToBlockedList(db);
109993   }
109994   db->pBlockingConnection = pBlocker;
109995   leaveMutex();
109996 }
109997
109998 /*
109999 ** This function is called when
110000 ** the transaction opened by database db has just finished. Locks held 
110001 ** by database connection db have been released.
110002 **
110003 ** This function loops through each entry in the blocked connections
110004 ** list and does the following:
110005 **
110006 **   1) If the sqlite3.pBlockingConnection member of a list entry is
110007 **      set to db, then set pBlockingConnection=0.
110008 **
110009 **   2) If the sqlite3.pUnlockConnection member of a list entry is
110010 **      set to db, then invoke the configured unlock-notify callback and
110011 **      set pUnlockConnection=0.
110012 **
110013 **   3) If the two steps above mean that pBlockingConnection==0 and
110014 **      pUnlockConnection==0, remove the entry from the blocked connections
110015 **      list.
110016 */
110017 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
110018   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
110019   int nArg = 0;                            /* Number of entries in aArg[] */
110020   sqlite3 **pp;                            /* Iterator variable */
110021   void **aArg;               /* Arguments to the unlock callback */
110022   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
110023   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
110024
110025   aArg = aStatic;
110026   enterMutex();         /* Enter STATIC_MASTER mutex */
110027
110028   /* This loop runs once for each entry in the blocked-connections list. */
110029   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
110030     sqlite3 *p = *pp;
110031
110032     /* Step 1. */
110033     if( p->pBlockingConnection==db ){
110034       p->pBlockingConnection = 0;
110035     }
110036
110037     /* Step 2. */
110038     if( p->pUnlockConnection==db ){
110039       assert( p->xUnlockNotify );
110040       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
110041         xUnlockNotify(aArg, nArg);
110042         nArg = 0;
110043       }
110044
110045       sqlite3BeginBenignMalloc();
110046       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
110047       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
110048       if( (!aDyn && nArg==(int)ArraySize(aStatic))
110049        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
110050       ){
110051         /* The aArg[] array needs to grow. */
110052         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
110053         if( pNew ){
110054           memcpy(pNew, aArg, nArg*sizeof(void *));
110055           sqlite3_free(aDyn);
110056           aDyn = aArg = pNew;
110057         }else{
110058           /* This occurs when the array of context pointers that need to
110059           ** be passed to the unlock-notify callback is larger than the
110060           ** aStatic[] array allocated on the stack and the attempt to 
110061           ** allocate a larger array from the heap has failed.
110062           **
110063           ** This is a difficult situation to handle. Returning an error
110064           ** code to the caller is insufficient, as even if an error code
110065           ** is returned the transaction on connection db will still be
110066           ** closed and the unlock-notify callbacks on blocked connections
110067           ** will go unissued. This might cause the application to wait
110068           ** indefinitely for an unlock-notify callback that will never 
110069           ** arrive.
110070           **
110071           ** Instead, invoke the unlock-notify callback with the context
110072           ** array already accumulated. We can then clear the array and
110073           ** begin accumulating any further context pointers without 
110074           ** requiring any dynamic allocation. This is sub-optimal because
110075           ** it means that instead of one callback with a large array of
110076           ** context pointers the application will receive two or more
110077           ** callbacks with smaller arrays of context pointers, which will
110078           ** reduce the applications ability to prioritize multiple 
110079           ** connections. But it is the best that can be done under the
110080           ** circumstances.
110081           */
110082           xUnlockNotify(aArg, nArg);
110083           nArg = 0;
110084         }
110085       }
110086       sqlite3EndBenignMalloc();
110087
110088       aArg[nArg++] = p->pUnlockArg;
110089       xUnlockNotify = p->xUnlockNotify;
110090       p->pUnlockConnection = 0;
110091       p->xUnlockNotify = 0;
110092       p->pUnlockArg = 0;
110093     }
110094
110095     /* Step 3. */
110096     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
110097       /* Remove connection p from the blocked connections list. */
110098       *pp = p->pNextBlocked;
110099       p->pNextBlocked = 0;
110100     }else{
110101       pp = &p->pNextBlocked;
110102     }
110103   }
110104
110105   if( nArg!=0 ){
110106     xUnlockNotify(aArg, nArg);
110107   }
110108   sqlite3_free(aDyn);
110109   leaveMutex();         /* Leave STATIC_MASTER mutex */
110110 }
110111
110112 /*
110113 ** This is called when the database connection passed as an argument is 
110114 ** being closed. The connection is removed from the blocked list.
110115 */
110116 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
110117   sqlite3ConnectionUnlocked(db);
110118   enterMutex();
110119   removeFromBlockedList(db);
110120   checkListProperties(db);
110121   leaveMutex();
110122 }
110123 #endif
110124
110125 /************** End of notify.c **********************************************/
110126 /************** Begin file fts3.c ********************************************/
110127 /*
110128 ** 2006 Oct 10
110129 **
110130 ** The author disclaims copyright to this source code.  In place of
110131 ** a legal notice, here is a blessing:
110132 **
110133 **    May you do good and not evil.
110134 **    May you find forgiveness for yourself and forgive others.
110135 **    May you share freely, never taking more than you give.
110136 **
110137 ******************************************************************************
110138 **
110139 ** This is an SQLite module implementing full-text search.
110140 */
110141
110142 /*
110143 ** The code in this file is only compiled if:
110144 **
110145 **     * The FTS3 module is being built as an extension
110146 **       (in which case SQLITE_CORE is not defined), or
110147 **
110148 **     * The FTS3 module is being built into the core of
110149 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110150 */
110151
110152 /* The full-text index is stored in a series of b+tree (-like)
110153 ** structures called segments which map terms to doclists.  The
110154 ** structures are like b+trees in layout, but are constructed from the
110155 ** bottom up in optimal fashion and are not updatable.  Since trees
110156 ** are built from the bottom up, things will be described from the
110157 ** bottom up.
110158 **
110159 **
110160 **** Varints ****
110161 ** The basic unit of encoding is a variable-length integer called a
110162 ** varint.  We encode variable-length integers in little-endian order
110163 ** using seven bits * per byte as follows:
110164 **
110165 ** KEY:
110166 **         A = 0xxxxxxx    7 bits of data and one flag bit
110167 **         B = 1xxxxxxx    7 bits of data and one flag bit
110168 **
110169 **  7 bits - A
110170 ** 14 bits - BA
110171 ** 21 bits - BBA
110172 ** and so on.
110173 **
110174 ** This is similar in concept to how sqlite encodes "varints" but
110175 ** the encoding is not the same.  SQLite varints are big-endian
110176 ** are are limited to 9 bytes in length whereas FTS3 varints are
110177 ** little-endian and can be up to 10 bytes in length (in theory).
110178 **
110179 ** Example encodings:
110180 **
110181 **     1:    0x01
110182 **   127:    0x7f
110183 **   128:    0x81 0x00
110184 **
110185 **
110186 **** Document lists ****
110187 ** A doclist (document list) holds a docid-sorted list of hits for a
110188 ** given term.  Doclists hold docids and associated token positions.
110189 ** A docid is the unique integer identifier for a single document.
110190 ** A position is the index of a word within the document.  The first 
110191 ** word of the document has a position of 0.
110192 **
110193 ** FTS3 used to optionally store character offsets using a compile-time
110194 ** option.  But that functionality is no longer supported.
110195 **
110196 ** A doclist is stored like this:
110197 **
110198 ** array {
110199 **   varint docid;
110200 **   array {                (position list for column 0)
110201 **     varint position;     (2 more than the delta from previous position)
110202 **   }
110203 **   array {
110204 **     varint POS_COLUMN;   (marks start of position list for new column)
110205 **     varint column;       (index of new column)
110206 **     array {
110207 **       varint position;   (2 more than the delta from previous position)
110208 **     }
110209 **   }
110210 **   varint POS_END;        (marks end of positions for this document.
110211 ** }
110212 **
110213 ** Here, array { X } means zero or more occurrences of X, adjacent in
110214 ** memory.  A "position" is an index of a token in the token stream
110215 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
110216 ** in the same logical place as the position element, and act as sentinals
110217 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
110218 ** The positions numbers are not stored literally but rather as two more
110219 ** than the difference from the prior position, or the just the position plus
110220 ** 2 for the first position.  Example:
110221 **
110222 **   label:       A B C D E  F  G H   I  J K
110223 **   value:     123 5 9 1 1 14 35 0 234 72 0
110224 **
110225 ** The 123 value is the first docid.  For column zero in this document
110226 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
110227 ** at D signals the start of a new column; the 1 at E indicates that the
110228 ** new column is column number 1.  There are two positions at 12 and 45
110229 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
110230 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
110231 ** terminates with the 0 at K.
110232 **
110233 ** A "position-list" is the list of positions for multiple columns for
110234 ** a single docid.  A "column-list" is the set of positions for a single
110235 ** column.  Hence, a position-list consists of one or more column-lists,
110236 ** a document record consists of a docid followed by a position-list and
110237 ** a doclist consists of one or more document records.
110238 **
110239 ** A bare doclist omits the position information, becoming an 
110240 ** array of varint-encoded docids.
110241 **
110242 **** Segment leaf nodes ****
110243 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
110244 ** nodes are written using LeafWriter, and read using LeafReader (to
110245 ** iterate through a single leaf node's data) and LeavesReader (to
110246 ** iterate through a segment's entire leaf layer).  Leaf nodes have
110247 ** the format:
110248 **
110249 ** varint iHeight;             (height from leaf level, always 0)
110250 ** varint nTerm;               (length of first term)
110251 ** char pTerm[nTerm];          (content of first term)
110252 ** varint nDoclist;            (length of term's associated doclist)
110253 ** char pDoclist[nDoclist];    (content of doclist)
110254 ** array {
110255 **                             (further terms are delta-encoded)
110256 **   varint nPrefix;           (length of prefix shared with previous term)
110257 **   varint nSuffix;           (length of unshared suffix)
110258 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
110259 **   varint nDoclist;          (length of term's associated doclist)
110260 **   char pDoclist[nDoclist];  (content of doclist)
110261 ** }
110262 **
110263 ** Here, array { X } means zero or more occurrences of X, adjacent in
110264 ** memory.
110265 **
110266 ** Leaf nodes are broken into blocks which are stored contiguously in
110267 ** the %_segments table in sorted order.  This means that when the end
110268 ** of a node is reached, the next term is in the node with the next
110269 ** greater node id.
110270 **
110271 ** New data is spilled to a new leaf node when the current node
110272 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
110273 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
110274 ** node (a leaf node with a single term and doclist).  The goal of
110275 ** these settings is to pack together groups of small doclists while
110276 ** making it efficient to directly access large doclists.  The
110277 ** assumption is that large doclists represent terms which are more
110278 ** likely to be query targets.
110279 **
110280 ** TODO(shess) It may be useful for blocking decisions to be more
110281 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
110282 ** node rather than splitting into 2k and .5k nodes.  My intuition is
110283 ** that this might extend through 2x or 4x the pagesize.
110284 **
110285 **
110286 **** Segment interior nodes ****
110287 ** Segment interior nodes store blockids for subtree nodes and terms
110288 ** to describe what data is stored by the each subtree.  Interior
110289 ** nodes are written using InteriorWriter, and read using
110290 ** InteriorReader.  InteriorWriters are created as needed when
110291 ** SegmentWriter creates new leaf nodes, or when an interior node
110292 ** itself grows too big and must be split.  The format of interior
110293 ** nodes:
110294 **
110295 ** varint iHeight;           (height from leaf level, always >0)
110296 ** varint iBlockid;          (block id of node's leftmost subtree)
110297 ** optional {
110298 **   varint nTerm;           (length of first term)
110299 **   char pTerm[nTerm];      (content of first term)
110300 **   array {
110301 **                                (further terms are delta-encoded)
110302 **     varint nPrefix;            (length of shared prefix with previous term)
110303 **     varint nSuffix;            (length of unshared suffix)
110304 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
110305 **   }
110306 ** }
110307 **
110308 ** Here, optional { X } means an optional element, while array { X }
110309 ** means zero or more occurrences of X, adjacent in memory.
110310 **
110311 ** An interior node encodes n terms separating n+1 subtrees.  The
110312 ** subtree blocks are contiguous, so only the first subtree's blockid
110313 ** is encoded.  The subtree at iBlockid will contain all terms less
110314 ** than the first term encoded (or all terms if no term is encoded).
110315 ** Otherwise, for terms greater than or equal to pTerm[i] but less
110316 ** than pTerm[i+1], the subtree for that term will be rooted at
110317 ** iBlockid+i.  Interior nodes only store enough term data to
110318 ** distinguish adjacent children (if the rightmost term of the left
110319 ** child is "something", and the leftmost term of the right child is
110320 ** "wicked", only "w" is stored).
110321 **
110322 ** New data is spilled to a new interior node at the same height when
110323 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
110324 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
110325 ** interior nodes and making the tree too skinny.  The interior nodes
110326 ** at a given height are naturally tracked by interior nodes at
110327 ** height+1, and so on.
110328 **
110329 **
110330 **** Segment directory ****
110331 ** The segment directory in table %_segdir stores meta-information for
110332 ** merging and deleting segments, and also the root node of the
110333 ** segment's tree.
110334 **
110335 ** The root node is the top node of the segment's tree after encoding
110336 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
110337 ** This could be either a leaf node or an interior node.  If the top
110338 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
110339 ** and a new root interior node is generated (which should always fit
110340 ** within ROOT_MAX because it only needs space for 2 varints, the
110341 ** height and the blockid of the previous root).
110342 **
110343 ** The meta-information in the segment directory is:
110344 **   level               - segment level (see below)
110345 **   idx                 - index within level
110346 **                       - (level,idx uniquely identify a segment)
110347 **   start_block         - first leaf node
110348 **   leaves_end_block    - last leaf node
110349 **   end_block           - last block (including interior nodes)
110350 **   root                - contents of root node
110351 **
110352 ** If the root node is a leaf node, then start_block,
110353 ** leaves_end_block, and end_block are all 0.
110354 **
110355 **
110356 **** Segment merging ****
110357 ** To amortize update costs, segments are grouped into levels and
110358 ** merged in batches.  Each increase in level represents exponentially
110359 ** more documents.
110360 **
110361 ** New documents (actually, document updates) are tokenized and
110362 ** written individually (using LeafWriter) to a level 0 segment, with
110363 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
110364 ** level 0 segments are merged into a single level 1 segment.  Level 1
110365 ** is populated like level 0, and eventually MERGE_COUNT level 1
110366 ** segments are merged to a single level 2 segment (representing
110367 ** MERGE_COUNT^2 updates), and so on.
110368 **
110369 ** A segment merge traverses all segments at a given level in
110370 ** parallel, performing a straightforward sorted merge.  Since segment
110371 ** leaf nodes are written in to the %_segments table in order, this
110372 ** merge traverses the underlying sqlite disk structures efficiently.
110373 ** After the merge, all segment blocks from the merged level are
110374 ** deleted.
110375 **
110376 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
110377 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
110378 ** very similar performance numbers to 16 on insertion, though they're
110379 ** a tiny bit slower (perhaps due to more overhead in merge-time
110380 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
110381 ** 16, 2 about 66% slower than 16.
110382 **
110383 ** At query time, high MERGE_COUNT increases the number of segments
110384 ** which need to be scanned and merged.  For instance, with 100k docs
110385 ** inserted:
110386 **
110387 **    MERGE_COUNT   segments
110388 **       16           25
110389 **        8           12
110390 **        4           10
110391 **        2            6
110392 **
110393 ** This appears to have only a moderate impact on queries for very
110394 ** frequent terms (which are somewhat dominated by segment merge
110395 ** costs), and infrequent and non-existent terms still seem to be fast
110396 ** even with many segments.
110397 **
110398 ** TODO(shess) That said, it would be nice to have a better query-side
110399 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
110400 ** optimizations to things like doclist merging will swing the sweet
110401 ** spot around.
110402 **
110403 **
110404 **
110405 **** Handling of deletions and updates ****
110406 ** Since we're using a segmented structure, with no docid-oriented
110407 ** index into the term index, we clearly cannot simply update the term
110408 ** index when a document is deleted or updated.  For deletions, we
110409 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
110410 ** we simply write the new doclist.  Segment merges overwrite older
110411 ** data for a particular docid with newer data, so deletes or updates
110412 ** will eventually overtake the earlier data and knock it out.  The
110413 ** query logic likewise merges doclists so that newer data knocks out
110414 ** older data.
110415 **
110416 ** TODO(shess) Provide a VACUUM type operation to clear out all
110417 ** deletions and duplications.  This would basically be a forced merge
110418 ** into a single segment.
110419 */
110420
110421 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110422
110423 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
110424 # define SQLITE_CORE 1
110425 #endif
110426
110427 /************** Include fts3Int.h in the middle of fts3.c ********************/
110428 /************** Begin file fts3Int.h *****************************************/
110429 /*
110430 ** 2009 Nov 12
110431 **
110432 ** The author disclaims copyright to this source code.  In place of
110433 ** a legal notice, here is a blessing:
110434 **
110435 **    May you do good and not evil.
110436 **    May you find forgiveness for yourself and forgive others.
110437 **    May you share freely, never taking more than you give.
110438 **
110439 ******************************************************************************
110440 **
110441 */
110442
110443 #ifndef _FTSINT_H
110444 #define _FTSINT_H
110445
110446 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
110447 # define NDEBUG 1
110448 #endif
110449
110450 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
110451 /************** Begin file fts3_tokenizer.h **********************************/
110452 /*
110453 ** 2006 July 10
110454 **
110455 ** The author disclaims copyright to this source code.
110456 **
110457 *************************************************************************
110458 ** Defines the interface to tokenizers used by fulltext-search.  There
110459 ** are three basic components:
110460 **
110461 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
110462 ** interface functions.  This is essentially the class structure for
110463 ** tokenizers.
110464 **
110465 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
110466 ** including customization information defined at creation time.
110467 **
110468 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
110469 ** tokens from a particular input.
110470 */
110471 #ifndef _FTS3_TOKENIZER_H_
110472 #define _FTS3_TOKENIZER_H_
110473
110474 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
110475 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
110476 ** we will need a way to register the API consistently.
110477 */
110478
110479 /*
110480 ** Structures used by the tokenizer interface. When a new tokenizer
110481 ** implementation is registered, the caller provides a pointer to
110482 ** an sqlite3_tokenizer_module containing pointers to the callback
110483 ** functions that make up an implementation.
110484 **
110485 ** When an fts3 table is created, it passes any arguments passed to
110486 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
110487 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
110488 ** implementation. The xCreate() function in turn returns an 
110489 ** sqlite3_tokenizer structure representing the specific tokenizer to
110490 ** be used for the fts3 table (customized by the tokenizer clause arguments).
110491 **
110492 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
110493 ** method is called. It returns an sqlite3_tokenizer_cursor object
110494 ** that may be used to tokenize a specific input buffer based on
110495 ** the tokenization rules supplied by a specific sqlite3_tokenizer
110496 ** object.
110497 */
110498 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
110499 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
110500 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
110501
110502 struct sqlite3_tokenizer_module {
110503
110504   /*
110505   ** Structure version. Should always be set to 0.
110506   */
110507   int iVersion;
110508
110509   /*
110510   ** Create a new tokenizer. The values in the argv[] array are the
110511   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
110512   ** TABLE statement that created the fts3 table. For example, if
110513   ** the following SQL is executed:
110514   **
110515   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
110516   **
110517   ** then argc is set to 2, and the argv[] array contains pointers
110518   ** to the strings "arg1" and "arg2".
110519   **
110520   ** This method should return either SQLITE_OK (0), or an SQLite error 
110521   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
110522   ** to point at the newly created tokenizer structure. The generic
110523   ** sqlite3_tokenizer.pModule variable should not be initialised by
110524   ** this callback. The caller will do so.
110525   */
110526   int (*xCreate)(
110527     int argc,                           /* Size of argv array */
110528     const char *const*argv,             /* Tokenizer argument strings */
110529     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
110530   );
110531
110532   /*
110533   ** Destroy an existing tokenizer. The fts3 module calls this method
110534   ** exactly once for each successful call to xCreate().
110535   */
110536   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
110537
110538   /*
110539   ** Create a tokenizer cursor to tokenize an input buffer. The caller
110540   ** is responsible for ensuring that the input buffer remains valid
110541   ** until the cursor is closed (using the xClose() method). 
110542   */
110543   int (*xOpen)(
110544     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
110545     const char *pInput, int nBytes,      /* Input buffer */
110546     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
110547   );
110548
110549   /*
110550   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
110551   ** method exactly once for each successful call to xOpen().
110552   */
110553   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
110554
110555   /*
110556   ** Retrieve the next token from the tokenizer cursor pCursor. This
110557   ** method should either return SQLITE_OK and set the values of the
110558   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
110559   ** the end of the buffer has been reached, or an SQLite error code.
110560   **
110561   ** *ppToken should be set to point at a buffer containing the 
110562   ** normalized version of the token (i.e. after any case-folding and/or
110563   ** stemming has been performed). *pnBytes should be set to the length
110564   ** of this buffer in bytes. The input text that generated the token is
110565   ** identified by the byte offsets returned in *piStartOffset and
110566   ** *piEndOffset. *piStartOffset should be set to the index of the first
110567   ** byte of the token in the input buffer. *piEndOffset should be set
110568   ** to the index of the first byte just past the end of the token in
110569   ** the input buffer.
110570   **
110571   ** The buffer *ppToken is set to point at is managed by the tokenizer
110572   ** implementation. It is only required to be valid until the next call
110573   ** to xNext() or xClose(). 
110574   */
110575   /* TODO(shess) current implementation requires pInput to be
110576   ** nul-terminated.  This should either be fixed, or pInput/nBytes
110577   ** should be converted to zInput.
110578   */
110579   int (*xNext)(
110580     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
110581     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
110582     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
110583     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
110584     int *piPosition      /* OUT: Number of tokens returned before this one */
110585   );
110586 };
110587
110588 struct sqlite3_tokenizer {
110589   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
110590   /* Tokenizer implementations will typically add additional fields */
110591 };
110592
110593 struct sqlite3_tokenizer_cursor {
110594   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
110595   /* Tokenizer implementations will typically add additional fields */
110596 };
110597
110598 int fts3_global_term_cnt(int iTerm, int iCol);
110599 int fts3_term_cnt(int iTerm, int iCol);
110600
110601
110602 #endif /* _FTS3_TOKENIZER_H_ */
110603
110604 /************** End of fts3_tokenizer.h **************************************/
110605 /************** Continuing where we left off in fts3Int.h ********************/
110606 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
110607 /************** Begin file fts3_hash.h ***************************************/
110608 /*
110609 ** 2001 September 22
110610 **
110611 ** The author disclaims copyright to this source code.  In place of
110612 ** a legal notice, here is a blessing:
110613 **
110614 **    May you do good and not evil.
110615 **    May you find forgiveness for yourself and forgive others.
110616 **    May you share freely, never taking more than you give.
110617 **
110618 *************************************************************************
110619 ** This is the header file for the generic hash-table implemenation
110620 ** used in SQLite.  We've modified it slightly to serve as a standalone
110621 ** hash table implementation for the full-text indexing module.
110622 **
110623 */
110624 #ifndef _FTS3_HASH_H_
110625 #define _FTS3_HASH_H_
110626
110627 /* Forward declarations of structures. */
110628 typedef struct Fts3Hash Fts3Hash;
110629 typedef struct Fts3HashElem Fts3HashElem;
110630
110631 /* A complete hash table is an instance of the following structure.
110632 ** The internals of this structure are intended to be opaque -- client
110633 ** code should not attempt to access or modify the fields of this structure
110634 ** directly.  Change this structure only by using the routines below.
110635 ** However, many of the "procedures" and "functions" for modifying and
110636 ** accessing this structure are really macros, so we can't really make
110637 ** this structure opaque.
110638 */
110639 struct Fts3Hash {
110640   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
110641   char copyKey;           /* True if copy of key made on insert */
110642   int count;              /* Number of entries in this table */
110643   Fts3HashElem *first;    /* The first element of the array */
110644   int htsize;             /* Number of buckets in the hash table */
110645   struct _fts3ht {        /* the hash table */
110646     int count;               /* Number of entries with this hash */
110647     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
110648   } *ht;
110649 };
110650
110651 /* Each element in the hash table is an instance of the following 
110652 ** structure.  All elements are stored on a single doubly-linked list.
110653 **
110654 ** Again, this structure is intended to be opaque, but it can't really
110655 ** be opaque because it is used by macros.
110656 */
110657 struct Fts3HashElem {
110658   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
110659   void *data;                /* Data associated with this element */
110660   void *pKey; int nKey;      /* Key associated with this element */
110661 };
110662
110663 /*
110664 ** There are 2 different modes of operation for a hash table:
110665 **
110666 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
110667 **                           (including the null-terminator, if any).  Case
110668 **                           is respected in comparisons.
110669 **
110670 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
110671 **                           memcmp() is used to compare keys.
110672 **
110673 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
110674 */
110675 #define FTS3_HASH_STRING    1
110676 #define FTS3_HASH_BINARY    2
110677
110678 /*
110679 ** Access routines.  To delete, insert a NULL pointer.
110680 */
110681 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
110682 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
110683 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
110684 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
110685 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
110686
110687 /*
110688 ** Shorthand for the functions above
110689 */
110690 #define fts3HashInit     sqlite3Fts3HashInit
110691 #define fts3HashInsert   sqlite3Fts3HashInsert
110692 #define fts3HashFind     sqlite3Fts3HashFind
110693 #define fts3HashClear    sqlite3Fts3HashClear
110694 #define fts3HashFindElem sqlite3Fts3HashFindElem
110695
110696 /*
110697 ** Macros for looping over all elements of a hash table.  The idiom is
110698 ** like this:
110699 **
110700 **   Fts3Hash h;
110701 **   Fts3HashElem *p;
110702 **   ...
110703 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
110704 **     SomeStructure *pData = fts3HashData(p);
110705 **     // do something with pData
110706 **   }
110707 */
110708 #define fts3HashFirst(H)  ((H)->first)
110709 #define fts3HashNext(E)   ((E)->next)
110710 #define fts3HashData(E)   ((E)->data)
110711 #define fts3HashKey(E)    ((E)->pKey)
110712 #define fts3HashKeysize(E) ((E)->nKey)
110713
110714 /*
110715 ** Number of entries in a hash table
110716 */
110717 #define fts3HashCount(H)  ((H)->count)
110718
110719 #endif /* _FTS3_HASH_H_ */
110720
110721 /************** End of fts3_hash.h *******************************************/
110722 /************** Continuing where we left off in fts3Int.h ********************/
110723
110724 /*
110725 ** This constant controls how often segments are merged. Once there are
110726 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
110727 ** segment of level N+1.
110728 */
110729 #define FTS3_MERGE_COUNT 16
110730
110731 /*
110732 ** This is the maximum amount of data (in bytes) to store in the 
110733 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
110734 ** populated as documents are inserted/updated/deleted in a transaction
110735 ** and used to create a new segment when the transaction is committed.
110736 ** However if this limit is reached midway through a transaction, a new 
110737 ** segment is created and the hash table cleared immediately.
110738 */
110739 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
110740
110741 /*
110742 ** Macro to return the number of elements in an array. SQLite has a
110743 ** similar macro called ArraySize(). Use a different name to avoid
110744 ** a collision when building an amalgamation with built-in FTS3.
110745 */
110746 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
110747
110748 /*
110749 ** Maximum length of a varint encoded integer. The varint format is different
110750 ** from that used by SQLite, so the maximum length is 10, not 9.
110751 */
110752 #define FTS3_VARINT_MAX 10
110753
110754 /*
110755 ** The testcase() macro is only used by the amalgamation.  If undefined,
110756 ** make it a no-op.
110757 */
110758 #ifndef testcase
110759 # define testcase(X)
110760 #endif
110761
110762 /*
110763 ** Terminator values for position-lists and column-lists.
110764 */
110765 #define POS_COLUMN  (1)     /* Column-list terminator */
110766 #define POS_END     (0)     /* Position-list terminator */ 
110767
110768 /*
110769 ** This section provides definitions to allow the
110770 ** FTS3 extension to be compiled outside of the 
110771 ** amalgamation.
110772 */
110773 #ifndef SQLITE_AMALGAMATION
110774 /*
110775 ** Macros indicating that conditional expressions are always true or
110776 ** false.
110777 */
110778 #ifdef SQLITE_COVERAGE_TEST
110779 # define ALWAYS(x) (1)
110780 # define NEVER(X)  (0)
110781 #else
110782 # define ALWAYS(x) (x)
110783 # define NEVER(X)  (x)
110784 #endif
110785
110786 /*
110787 ** Internal types used by SQLite.
110788 */
110789 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
110790 typedef short int i16;            /* 2-byte (or larger) signed integer */
110791 typedef unsigned int u32;         /* 4-byte unsigned integer */
110792 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
110793 /*
110794 ** Macro used to suppress compiler warnings for unused parameters.
110795 */
110796 #define UNUSED_PARAMETER(x) (void)(x)
110797 #endif
110798
110799 typedef struct Fts3Table Fts3Table;
110800 typedef struct Fts3Cursor Fts3Cursor;
110801 typedef struct Fts3Expr Fts3Expr;
110802 typedef struct Fts3Phrase Fts3Phrase;
110803 typedef struct Fts3PhraseToken Fts3PhraseToken;
110804
110805 typedef struct Fts3SegFilter Fts3SegFilter;
110806 typedef struct Fts3DeferredToken Fts3DeferredToken;
110807 typedef struct Fts3SegReader Fts3SegReader;
110808 typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
110809
110810 /*
110811 ** A connection to a fulltext index is an instance of the following
110812 ** structure. The xCreate and xConnect methods create an instance
110813 ** of this structure and xDestroy and xDisconnect free that instance.
110814 ** All other methods receive a pointer to the structure as one of their
110815 ** arguments.
110816 */
110817 struct Fts3Table {
110818   sqlite3_vtab base;              /* Base class used by SQLite core */
110819   sqlite3 *db;                    /* The database connection */
110820   const char *zDb;                /* logical database name */
110821   const char *zName;              /* virtual table name */
110822   int nColumn;                    /* number of named columns in virtual table */
110823   char **azColumn;                /* column names.  malloced */
110824   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
110825
110826   /* Precompiled statements used by the implementation. Each of these 
110827   ** statements is run and reset within a single virtual table API call. 
110828   */
110829   sqlite3_stmt *aStmt[24];
110830
110831   char *zReadExprlist;
110832   char *zWriteExprlist;
110833
110834   int nNodeSize;                  /* Soft limit for node size */
110835   u8 bHasStat;                    /* True if %_stat table exists */
110836   u8 bHasDocsize;                 /* True if %_docsize table exists */
110837   int nPgsz;                      /* Page size for host database */
110838   char *zSegmentsTbl;             /* Name of %_segments table */
110839   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
110840
110841   /* The following hash table is used to buffer pending index updates during
110842   ** transactions. Variable nPendingData estimates the memory size of the 
110843   ** pending data, including hash table overhead, but not malloc overhead. 
110844   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
110845   ** automatically. Variable iPrevDocid is the docid of the most recently
110846   ** inserted record.
110847   */
110848   int nMaxPendingData;
110849   int nPendingData;
110850   sqlite_int64 iPrevDocid;
110851   Fts3Hash pendingTerms;
110852 };
110853
110854 /*
110855 ** When the core wants to read from the virtual table, it creates a
110856 ** virtual table cursor (an instance of the following structure) using
110857 ** the xOpen method. Cursors are destroyed using the xClose method.
110858 */
110859 struct Fts3Cursor {
110860   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
110861   i16 eSearch;                    /* Search strategy (see below) */
110862   u8 isEof;                       /* True if at End Of Results */
110863   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
110864   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
110865   Fts3Expr *pExpr;                /* Parsed MATCH query string */
110866   int nPhrase;                    /* Number of matchable phrases in query */
110867   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
110868   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
110869   char *pNextId;                  /* Pointer into the body of aDoclist */
110870   char *aDoclist;                 /* List of docids for full-text queries */
110871   int nDoclist;                   /* Size of buffer at aDoclist */
110872   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
110873   int nRowAvg;                    /* Average size of database rows, in pages */
110874
110875   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
110876   u32 *aMatchinfo;                /* Information about most recent match */
110877   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
110878   char *zMatchinfo;               /* Matchinfo specification */
110879 };
110880
110881 #define FTS3_EVAL_FILTER    0
110882 #define FTS3_EVAL_NEXT      1
110883 #define FTS3_EVAL_MATCHINFO 2
110884
110885 /*
110886 ** The Fts3Cursor.eSearch member is always set to one of the following.
110887 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
110888 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
110889 ** of the column to be searched.  For example, in
110890 **
110891 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
110892 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
110893 ** 
110894 ** Because the LHS of the MATCH operator is 2nd column "b",
110895 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
110896 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
110897 ** indicating that all columns should be searched,
110898 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
110899 */
110900 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
110901 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
110902 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
110903
110904 /*
110905 ** A "phrase" is a sequence of one or more tokens that must match in
110906 ** sequence.  A single token is the base case and the most common case.
110907 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
110908 ** nToken will be the number of tokens in the string.
110909 **
110910 ** The nDocMatch and nMatch variables contain data that may be used by the
110911 ** matchinfo() function. They are populated when the full-text index is 
110912 ** queried for hits on the phrase. If one or more tokens in the phrase
110913 ** are deferred, the nDocMatch and nMatch variables are populated based
110914 ** on the assumption that the 
110915 */
110916 struct Fts3PhraseToken {
110917   char *z;                        /* Text of the token */
110918   int n;                          /* Number of bytes in buffer z */
110919   int isPrefix;                   /* True if token ends with a "*" character */
110920   int bFulltext;                  /* True if full-text index was used */
110921   Fts3SegReaderCursor *pSegcsr;   /* Segment-reader for this token */
110922   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
110923 };
110924
110925 struct Fts3Phrase {
110926   /* Variables populated by fts3_expr.c when parsing a MATCH expression */
110927   int nToken;                /* Number of tokens in the phrase */
110928   int iColumn;               /* Index of column this phrase must match */
110929   int isNot;                 /* Phrase prefixed by unary not (-) operator */
110930   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
110931 };
110932
110933 /*
110934 ** A tree of these objects forms the RHS of a MATCH operator.
110935 **
110936 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
110937 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
110938 ** containing the results of the NEAR or phrase query in FTS3 doclist
110939 ** format. As usual, the initial "Length" field found in doclists stored
110940 ** on disk is omitted from this buffer.
110941 **
110942 ** Variable pCurrent always points to the start of a docid field within
110943 ** aDoclist. Since the doclist is usually scanned in docid order, this can
110944 ** be used to accelerate seeking to the required docid within the doclist.
110945 */
110946 struct Fts3Expr {
110947   int eType;                 /* One of the FTSQUERY_XXX values defined below */
110948   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
110949   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
110950   Fts3Expr *pLeft;           /* Left operand */
110951   Fts3Expr *pRight;          /* Right operand */
110952   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
110953
110954   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
110955   char *aDoclist;            /* Buffer containing doclist */
110956   int nDoclist;              /* Size of aDoclist in bytes */
110957
110958   sqlite3_int64 iCurrent;
110959   char *pCurrent;
110960 };
110961
110962 /*
110963 ** Candidate values for Fts3Query.eType. Note that the order of the first
110964 ** four values is in order of precedence when parsing expressions. For 
110965 ** example, the following:
110966 **
110967 **   "a OR b AND c NOT d NEAR e"
110968 **
110969 ** is equivalent to:
110970 **
110971 **   "a OR (b AND (c NOT (d NEAR e)))"
110972 */
110973 #define FTSQUERY_NEAR   1
110974 #define FTSQUERY_NOT    2
110975 #define FTSQUERY_AND    3
110976 #define FTSQUERY_OR     4
110977 #define FTSQUERY_PHRASE 5
110978
110979
110980 /* fts3_write.c */
110981 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
110982 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
110983 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
110984 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
110985 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
110986   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
110987 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
110988 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
110989 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
110990 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
110991 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
110992 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
110993
110994 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
110995 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
110996
110997 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
110998 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
110999 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
111000 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
111001 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
111002 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
111003
111004 #define FTS3_SEGCURSOR_PENDING -1
111005 #define FTS3_SEGCURSOR_ALL     -2
111006
111007 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
111008 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
111009 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
111010 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
111011     Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
111012
111013 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
111014 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
111015 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
111016 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
111017 #define FTS3_SEGMENT_PREFIX        0x00000008
111018 #define FTS3_SEGMENT_SCAN          0x00000010
111019
111020 /* Type passed as 4th argument to SegmentReaderIterate() */
111021 struct Fts3SegFilter {
111022   const char *zTerm;
111023   int nTerm;
111024   int iCol;
111025   int flags;
111026 };
111027
111028 struct Fts3SegReaderCursor {
111029   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
111030   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
111031   int nSegment;                   /* Size of apSegment array */
111032   int nAdvance;                   /* How many seg-readers to advance */
111033   Fts3SegFilter *pFilter;         /* Pointer to filter object */
111034   char *aBuffer;                  /* Buffer to merge doclists in */
111035   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
111036
111037   /* Cost of running this iterator. Used by fts3.c only. */
111038   int nCost;
111039
111040   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
111041   char *zTerm;                    /* Pointer to term buffer */
111042   int nTerm;                      /* Size of zTerm in bytes */
111043   char *aDoclist;                 /* Pointer to doclist buffer */
111044   int nDoclist;                   /* Size of aDoclist[] in bytes */
111045 };
111046
111047 /* fts3.c */
111048 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
111049 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
111050 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
111051 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
111052 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
111053
111054 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
111055 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
111056 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
111057 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
111058
111059 /* fts3_tokenizer.c */
111060 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
111061 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
111062 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
111063     sqlite3_tokenizer **, char **
111064 );
111065 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
111066
111067 /* fts3_snippet.c */
111068 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
111069 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
111070   const char *, const char *, int, int
111071 );
111072 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
111073
111074 /* fts3_expr.c */
111075 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
111076   char **, int, int, const char *, int, Fts3Expr **
111077 );
111078 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
111079 #ifdef SQLITE_TEST
111080 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
111081 #endif
111082
111083 /* fts3_aux.c */
111084 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
111085
111086 #endif /* _FTSINT_H */
111087
111088 /************** End of fts3Int.h *********************************************/
111089 /************** Continuing where we left off in fts3.c ***********************/
111090
111091
111092 #ifndef SQLITE_CORE 
111093   SQLITE_EXTENSION_INIT1
111094 #endif
111095
111096 /* 
111097 ** Write a 64-bit variable-length integer to memory starting at p[0].
111098 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
111099 ** The number of bytes written is returned.
111100 */
111101 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
111102   unsigned char *q = (unsigned char *) p;
111103   sqlite_uint64 vu = v;
111104   do{
111105     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
111106     vu >>= 7;
111107   }while( vu!=0 );
111108   q[-1] &= 0x7f;  /* turn off high bit in final byte */
111109   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
111110   return (int) (q - (unsigned char *)p);
111111 }
111112
111113 /* 
111114 ** Read a 64-bit variable-length integer from memory starting at p[0].
111115 ** Return the number of bytes read, or 0 on error.
111116 ** The value is stored in *v.
111117 */
111118 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
111119   const unsigned char *q = (const unsigned char *) p;
111120   sqlite_uint64 x = 0, y = 1;
111121   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
111122     x += y * (*q++ & 0x7f);
111123     y <<= 7;
111124   }
111125   x += y * (*q++);
111126   *v = (sqlite_int64) x;
111127   return (int) (q - (unsigned char *)p);
111128 }
111129
111130 /*
111131 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
111132 ** 32-bit integer before it is returned.
111133 */
111134 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
111135  sqlite_int64 i;
111136  int ret = sqlite3Fts3GetVarint(p, &i);
111137  *pi = (int) i;
111138  return ret;
111139 }
111140
111141 /*
111142 ** Return the number of bytes required to encode v as a varint
111143 */
111144 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
111145   int i = 0;
111146   do{
111147     i++;
111148     v >>= 7;
111149   }while( v!=0 );
111150   return i;
111151 }
111152
111153 /*
111154 ** Convert an SQL-style quoted string into a normal string by removing
111155 ** the quote characters.  The conversion is done in-place.  If the
111156 ** input does not begin with a quote character, then this routine
111157 ** is a no-op.
111158 **
111159 ** Examples:
111160 **
111161 **     "abc"   becomes   abc
111162 **     'xyz'   becomes   xyz
111163 **     [pqr]   becomes   pqr
111164 **     `mno`   becomes   mno
111165 **
111166 */
111167 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
111168   char quote;                     /* Quote character (if any ) */
111169
111170   quote = z[0];
111171   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
111172     int iIn = 1;                  /* Index of next byte to read from input */
111173     int iOut = 0;                 /* Index of next byte to write to output */
111174
111175     /* If the first byte was a '[', then the close-quote character is a ']' */
111176     if( quote=='[' ) quote = ']';  
111177
111178     while( ALWAYS(z[iIn]) ){
111179       if( z[iIn]==quote ){
111180         if( z[iIn+1]!=quote ) break;
111181         z[iOut++] = quote;
111182         iIn += 2;
111183       }else{
111184         z[iOut++] = z[iIn++];
111185       }
111186     }
111187     z[iOut] = '\0';
111188   }
111189 }
111190
111191 /*
111192 ** Read a single varint from the doclist at *pp and advance *pp to point
111193 ** to the first byte past the end of the varint.  Add the value of the varint
111194 ** to *pVal.
111195 */
111196 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
111197   sqlite3_int64 iVal;
111198   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
111199   *pVal += iVal;
111200 }
111201
111202 /*
111203 ** As long as *pp has not reached its end (pEnd), then do the same
111204 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
111205 ** But if we have reached the end of the varint, just set *pp=0 and
111206 ** leave *pVal unchanged.
111207 */
111208 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
111209   if( *pp>=pEnd ){
111210     *pp = 0;
111211   }else{
111212     fts3GetDeltaVarint(pp, pVal);
111213   }
111214 }
111215
111216 /*
111217 ** The xDisconnect() virtual table method.
111218 */
111219 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
111220   Fts3Table *p = (Fts3Table *)pVtab;
111221   int i;
111222
111223   assert( p->nPendingData==0 );
111224   assert( p->pSegments==0 );
111225
111226   /* Free any prepared statements held */
111227   for(i=0; i<SizeofArray(p->aStmt); i++){
111228     sqlite3_finalize(p->aStmt[i]);
111229   }
111230   sqlite3_free(p->zSegmentsTbl);
111231   sqlite3_free(p->zReadExprlist);
111232   sqlite3_free(p->zWriteExprlist);
111233
111234   /* Invoke the tokenizer destructor to free the tokenizer. */
111235   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
111236
111237   sqlite3_free(p);
111238   return SQLITE_OK;
111239 }
111240
111241 /*
111242 ** Construct one or more SQL statements from the format string given
111243 ** and then evaluate those statements. The success code is written
111244 ** into *pRc.
111245 **
111246 ** If *pRc is initially non-zero then this routine is a no-op.
111247 */
111248 static void fts3DbExec(
111249   int *pRc,              /* Success code */
111250   sqlite3 *db,           /* Database in which to run SQL */
111251   const char *zFormat,   /* Format string for SQL */
111252   ...                    /* Arguments to the format string */
111253 ){
111254   va_list ap;
111255   char *zSql;
111256   if( *pRc ) return;
111257   va_start(ap, zFormat);
111258   zSql = sqlite3_vmprintf(zFormat, ap);
111259   va_end(ap);
111260   if( zSql==0 ){
111261     *pRc = SQLITE_NOMEM;
111262   }else{
111263     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
111264     sqlite3_free(zSql);
111265   }
111266 }
111267
111268 /*
111269 ** The xDestroy() virtual table method.
111270 */
111271 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
111272   int rc = SQLITE_OK;              /* Return code */
111273   Fts3Table *p = (Fts3Table *)pVtab;
111274   sqlite3 *db = p->db;
111275
111276   /* Drop the shadow tables */
111277   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
111278   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
111279   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
111280   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
111281   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
111282
111283   /* If everything has worked, invoke fts3DisconnectMethod() to free the
111284   ** memory associated with the Fts3Table structure and return SQLITE_OK.
111285   ** Otherwise, return an SQLite error code.
111286   */
111287   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
111288 }
111289
111290
111291 /*
111292 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
111293 ** passed as the first argument. This is done as part of the xConnect()
111294 ** and xCreate() methods.
111295 **
111296 ** If *pRc is non-zero when this function is called, it is a no-op. 
111297 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111298 ** before returning.
111299 */
111300 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
111301   if( *pRc==SQLITE_OK ){
111302     int i;                        /* Iterator variable */
111303     int rc;                       /* Return code */
111304     char *zSql;                   /* SQL statement passed to declare_vtab() */
111305     char *zCols;                  /* List of user defined columns */
111306
111307     /* Create a list of user columns for the virtual table */
111308     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
111309     for(i=1; zCols && i<p->nColumn; i++){
111310       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
111311     }
111312
111313     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
111314     zSql = sqlite3_mprintf(
111315         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
111316     );
111317     if( !zCols || !zSql ){
111318       rc = SQLITE_NOMEM;
111319     }else{
111320       rc = sqlite3_declare_vtab(p->db, zSql);
111321     }
111322
111323     sqlite3_free(zSql);
111324     sqlite3_free(zCols);
111325     *pRc = rc;
111326   }
111327 }
111328
111329 /*
111330 ** Create the backing store tables (%_content, %_segments and %_segdir)
111331 ** required by the FTS3 table passed as the only argument. This is done
111332 ** as part of the vtab xCreate() method.
111333 **
111334 ** If the p->bHasDocsize boolean is true (indicating that this is an
111335 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
111336 ** %_stat tables required by FTS4.
111337 */
111338 static int fts3CreateTables(Fts3Table *p){
111339   int rc = SQLITE_OK;             /* Return code */
111340   int i;                          /* Iterator variable */
111341   char *zContentCols;             /* Columns of %_content table */
111342   sqlite3 *db = p->db;            /* The database connection */
111343
111344   /* Create a list of user columns for the content table */
111345   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
111346   for(i=0; zContentCols && i<p->nColumn; i++){
111347     char *z = p->azColumn[i];
111348     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
111349   }
111350   if( zContentCols==0 ) rc = SQLITE_NOMEM;
111351
111352   /* Create the content table */
111353   fts3DbExec(&rc, db, 
111354      "CREATE TABLE %Q.'%q_content'(%s)",
111355      p->zDb, p->zName, zContentCols
111356   );
111357   sqlite3_free(zContentCols);
111358   /* Create other tables */
111359   fts3DbExec(&rc, db, 
111360       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
111361       p->zDb, p->zName
111362   );
111363   fts3DbExec(&rc, db, 
111364       "CREATE TABLE %Q.'%q_segdir'("
111365         "level INTEGER,"
111366         "idx INTEGER,"
111367         "start_block INTEGER,"
111368         "leaves_end_block INTEGER,"
111369         "end_block INTEGER,"
111370         "root BLOB,"
111371         "PRIMARY KEY(level, idx)"
111372       ");",
111373       p->zDb, p->zName
111374   );
111375   if( p->bHasDocsize ){
111376     fts3DbExec(&rc, db, 
111377         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
111378         p->zDb, p->zName
111379     );
111380   }
111381   if( p->bHasStat ){
111382     fts3DbExec(&rc, db, 
111383         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
111384         p->zDb, p->zName
111385     );
111386   }
111387   return rc;
111388 }
111389
111390 /*
111391 ** Store the current database page-size in bytes in p->nPgsz.
111392 **
111393 ** If *pRc is non-zero when this function is called, it is a no-op. 
111394 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
111395 ** before returning.
111396 */
111397 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
111398   if( *pRc==SQLITE_OK ){
111399     int rc;                       /* Return code */
111400     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
111401     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
111402   
111403     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
111404     if( !zSql ){
111405       rc = SQLITE_NOMEM;
111406     }else{
111407       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
111408       if( rc==SQLITE_OK ){
111409         sqlite3_step(pStmt);
111410         p->nPgsz = sqlite3_column_int(pStmt, 0);
111411         rc = sqlite3_finalize(pStmt);
111412       }
111413     }
111414     assert( p->nPgsz>0 || rc!=SQLITE_OK );
111415     sqlite3_free(zSql);
111416     *pRc = rc;
111417   }
111418 }
111419
111420 /*
111421 ** "Special" FTS4 arguments are column specifications of the following form:
111422 **
111423 **   <key> = <value>
111424 **
111425 ** There may not be whitespace surrounding the "=" character. The <value> 
111426 ** term may be quoted, but the <key> may not.
111427 */
111428 static int fts3IsSpecialColumn(
111429   const char *z, 
111430   int *pnKey,
111431   char **pzValue
111432 ){
111433   char *zValue;
111434   const char *zCsr = z;
111435
111436   while( *zCsr!='=' ){
111437     if( *zCsr=='\0' ) return 0;
111438     zCsr++;
111439   }
111440
111441   *pnKey = (int)(zCsr-z);
111442   zValue = sqlite3_mprintf("%s", &zCsr[1]);
111443   if( zValue ){
111444     sqlite3Fts3Dequote(zValue);
111445   }
111446   *pzValue = zValue;
111447   return 1;
111448 }
111449
111450 /*
111451 ** Append the output of a printf() style formatting to an existing string.
111452 */
111453 static void fts3Appendf(
111454   int *pRc,                       /* IN/OUT: Error code */
111455   char **pz,                      /* IN/OUT: Pointer to string buffer */
111456   const char *zFormat,            /* Printf format string to append */
111457   ...                             /* Arguments for printf format string */
111458 ){
111459   if( *pRc==SQLITE_OK ){
111460     va_list ap;
111461     char *z;
111462     va_start(ap, zFormat);
111463     z = sqlite3_vmprintf(zFormat, ap);
111464     if( z && *pz ){
111465       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
111466       sqlite3_free(z);
111467       z = z2;
111468     }
111469     if( z==0 ) *pRc = SQLITE_NOMEM;
111470     sqlite3_free(*pz);
111471     *pz = z;
111472   }
111473 }
111474
111475 /*
111476 ** Return a copy of input string zInput enclosed in double-quotes (") and
111477 ** with all double quote characters escaped. For example:
111478 **
111479 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
111480 **
111481 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
111482 ** is the callers responsibility to call sqlite3_free() to release this
111483 ** memory.
111484 */
111485 static char *fts3QuoteId(char const *zInput){
111486   int nRet;
111487   char *zRet;
111488   nRet = 2 + strlen(zInput)*2 + 1;
111489   zRet = sqlite3_malloc(nRet);
111490   if( zRet ){
111491     int i;
111492     char *z = zRet;
111493     *(z++) = '"';
111494     for(i=0; zInput[i]; i++){
111495       if( zInput[i]=='"' ) *(z++) = '"';
111496       *(z++) = zInput[i];
111497     }
111498     *(z++) = '"';
111499     *(z++) = '\0';
111500   }
111501   return zRet;
111502 }
111503
111504 /*
111505 ** Return a list of comma separated SQL expressions that could be used
111506 ** in a SELECT statement such as the following:
111507 **
111508 **     SELECT <list of expressions> FROM %_content AS x ...
111509 **
111510 ** to return the docid, followed by each column of text data in order
111511 ** from left to write. If parameter zFunc is not NULL, then instead of
111512 ** being returned directly each column of text data is passed to an SQL
111513 ** function named zFunc first. For example, if zFunc is "unzip" and the
111514 ** table has the three user-defined columns "a", "b", and "c", the following
111515 ** string is returned:
111516 **
111517 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
111518 **
111519 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111520 ** is the responsibility of the caller to eventually free it.
111521 **
111522 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111523 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111524 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111525 ** no error occurs, *pRc is left unmodified.
111526 */
111527 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
111528   char *zRet = 0;
111529   char *zFree = 0;
111530   char *zFunction;
111531   int i;
111532
111533   if( !zFunc ){
111534     zFunction = "";
111535   }else{
111536     zFree = zFunction = fts3QuoteId(zFunc);
111537   }
111538   fts3Appendf(pRc, &zRet, "docid");
111539   for(i=0; i<p->nColumn; i++){
111540     fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
111541   }
111542   sqlite3_free(zFree);
111543   return zRet;
111544 }
111545
111546 /*
111547 ** Return a list of N comma separated question marks, where N is the number
111548 ** of columns in the %_content table (one for the docid plus one for each
111549 ** user-defined text column).
111550 **
111551 ** If argument zFunc is not NULL, then all but the first question mark
111552 ** is preceded by zFunc and an open bracket, and followed by a closed
111553 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
111554 ** user-defined text columns, the following string is returned:
111555 **
111556 **     "?, zip(?), zip(?), zip(?)"
111557 **
111558 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
111559 ** is the responsibility of the caller to eventually free it.
111560 **
111561 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
111562 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
111563 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
111564 ** no error occurs, *pRc is left unmodified.
111565 */
111566 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
111567   char *zRet = 0;
111568   char *zFree = 0;
111569   char *zFunction;
111570   int i;
111571
111572   if( !zFunc ){
111573     zFunction = "";
111574   }else{
111575     zFree = zFunction = fts3QuoteId(zFunc);
111576   }
111577   fts3Appendf(pRc, &zRet, "?");
111578   for(i=0; i<p->nColumn; i++){
111579     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
111580   }
111581   sqlite3_free(zFree);
111582   return zRet;
111583 }
111584
111585 /*
111586 ** This function is the implementation of both the xConnect and xCreate
111587 ** methods of the FTS3 virtual table.
111588 **
111589 ** The argv[] array contains the following:
111590 **
111591 **   argv[0]   -> module name  ("fts3" or "fts4")
111592 **   argv[1]   -> database name
111593 **   argv[2]   -> table name
111594 **   argv[...] -> "column name" and other module argument fields.
111595 */
111596 static int fts3InitVtab(
111597   int isCreate,                   /* True for xCreate, false for xConnect */
111598   sqlite3 *db,                    /* The SQLite database connection */
111599   void *pAux,                     /* Hash table containing tokenizers */
111600   int argc,                       /* Number of elements in argv array */
111601   const char * const *argv,       /* xCreate/xConnect argument array */
111602   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
111603   char **pzErr                    /* Write any error message here */
111604 ){
111605   Fts3Hash *pHash = (Fts3Hash *)pAux;
111606   Fts3Table *p = 0;               /* Pointer to allocated vtab */
111607   int rc = SQLITE_OK;             /* Return code */
111608   int i;                          /* Iterator variable */
111609   int nByte;                      /* Size of allocation used for *p */
111610   int iCol;                       /* Column index */
111611   int nString = 0;                /* Bytes required to hold all column names */
111612   int nCol = 0;                   /* Number of columns in the FTS table */
111613   char *zCsr;                     /* Space for holding column names */
111614   int nDb;                        /* Bytes required to hold database name */
111615   int nName;                      /* Bytes required to hold table name */
111616   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
111617   int bNoDocsize = 0;             /* True to omit %_docsize table */
111618   const char **aCol;              /* Array of column names */
111619   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
111620
111621   char *zCompress = 0;
111622   char *zUncompress = 0;
111623
111624   assert( strlen(argv[0])==4 );
111625   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
111626        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
111627   );
111628
111629   nDb = (int)strlen(argv[1]) + 1;
111630   nName = (int)strlen(argv[2]) + 1;
111631
111632   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
111633   if( !aCol ) return SQLITE_NOMEM;
111634   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
111635
111636   /* Loop through all of the arguments passed by the user to the FTS3/4
111637   ** module (i.e. all the column names and special arguments). This loop
111638   ** does the following:
111639   **
111640   **   + Figures out the number of columns the FTSX table will have, and
111641   **     the number of bytes of space that must be allocated to store copies
111642   **     of the column names.
111643   **
111644   **   + If there is a tokenizer specification included in the arguments,
111645   **     initializes the tokenizer pTokenizer.
111646   */
111647   for(i=3; rc==SQLITE_OK && i<argc; i++){
111648     char const *z = argv[i];
111649     int nKey;
111650     char *zVal;
111651
111652     /* Check if this is a tokenizer specification */
111653     if( !pTokenizer 
111654      && strlen(z)>8
111655      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
111656      && 0==sqlite3Fts3IsIdChar(z[8])
111657     ){
111658       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
111659     }
111660
111661     /* Check if it is an FTS4 special argument. */
111662     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
111663       if( !zVal ){
111664         rc = SQLITE_NOMEM;
111665         goto fts3_init_out;
111666       }
111667       if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
111668         if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
111669           bNoDocsize = 1;
111670         }else{
111671           *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
111672           rc = SQLITE_ERROR;
111673         }
111674       }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
111675         zCompress = zVal;
111676         zVal = 0;
111677       }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
111678         zUncompress = zVal;
111679         zVal = 0;
111680       }else{
111681         *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
111682         rc = SQLITE_ERROR;
111683       }
111684       sqlite3_free(zVal);
111685     }
111686
111687     /* Otherwise, the argument is a column name. */
111688     else {
111689       nString += (int)(strlen(z) + 1);
111690       aCol[nCol++] = z;
111691     }
111692   }
111693   if( rc!=SQLITE_OK ) goto fts3_init_out;
111694
111695   if( nCol==0 ){
111696     assert( nString==0 );
111697     aCol[0] = "content";
111698     nString = 8;
111699     nCol = 1;
111700   }
111701
111702   if( pTokenizer==0 ){
111703     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
111704     if( rc!=SQLITE_OK ) goto fts3_init_out;
111705   }
111706   assert( pTokenizer );
111707
111708
111709   /* Allocate and populate the Fts3Table structure. */
111710   nByte = sizeof(Fts3Table) +              /* Fts3Table */
111711           nCol * sizeof(char *) +              /* azColumn */
111712           nName +                              /* zName */
111713           nDb +                                /* zDb */
111714           nString;                             /* Space for azColumn strings */
111715   p = (Fts3Table*)sqlite3_malloc(nByte);
111716   if( p==0 ){
111717     rc = SQLITE_NOMEM;
111718     goto fts3_init_out;
111719   }
111720   memset(p, 0, nByte);
111721   p->db = db;
111722   p->nColumn = nCol;
111723   p->nPendingData = 0;
111724   p->azColumn = (char **)&p[1];
111725   p->pTokenizer = pTokenizer;
111726   p->nNodeSize = 1000;
111727   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
111728   p->bHasDocsize = (isFts4 && bNoDocsize==0);
111729   p->bHasStat = isFts4;
111730   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
111731
111732   /* Fill in the zName and zDb fields of the vtab structure. */
111733   zCsr = (char *)&p->azColumn[nCol];
111734   p->zName = zCsr;
111735   memcpy(zCsr, argv[2], nName);
111736   zCsr += nName;
111737   p->zDb = zCsr;
111738   memcpy(zCsr, argv[1], nDb);
111739   zCsr += nDb;
111740
111741   /* Fill in the azColumn array */
111742   for(iCol=0; iCol<nCol; iCol++){
111743     char *z; 
111744     int n;
111745     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
111746     memcpy(zCsr, z, n);
111747     zCsr[n] = '\0';
111748     sqlite3Fts3Dequote(zCsr);
111749     p->azColumn[iCol] = zCsr;
111750     zCsr += n+1;
111751     assert( zCsr <= &((char *)p)[nByte] );
111752   }
111753
111754   if( (zCompress==0)!=(zUncompress==0) ){
111755     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
111756     rc = SQLITE_ERROR;
111757     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
111758   }
111759   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
111760   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
111761   if( rc!=SQLITE_OK ) goto fts3_init_out;
111762
111763   /* If this is an xCreate call, create the underlying tables in the 
111764   ** database. TODO: For xConnect(), it could verify that said tables exist.
111765   */
111766   if( isCreate ){
111767     rc = fts3CreateTables(p);
111768   }
111769
111770   /* Figure out the page-size for the database. This is required in order to
111771   ** estimate the cost of loading large doclists from the database (see 
111772   ** function sqlite3Fts3SegReaderCost() for details).
111773   */
111774   fts3DatabasePageSize(&rc, p);
111775
111776   /* Declare the table schema to SQLite. */
111777   fts3DeclareVtab(&rc, p);
111778
111779 fts3_init_out:
111780   sqlite3_free(zCompress);
111781   sqlite3_free(zUncompress);
111782   sqlite3_free((void *)aCol);
111783   if( rc!=SQLITE_OK ){
111784     if( p ){
111785       fts3DisconnectMethod((sqlite3_vtab *)p);
111786     }else if( pTokenizer ){
111787       pTokenizer->pModule->xDestroy(pTokenizer);
111788     }
111789   }else{
111790     *ppVTab = &p->base;
111791   }
111792   return rc;
111793 }
111794
111795 /*
111796 ** The xConnect() and xCreate() methods for the virtual table. All the
111797 ** work is done in function fts3InitVtab().
111798 */
111799 static int fts3ConnectMethod(
111800   sqlite3 *db,                    /* Database connection */
111801   void *pAux,                     /* Pointer to tokenizer hash table */
111802   int argc,                       /* Number of elements in argv array */
111803   const char * const *argv,       /* xCreate/xConnect argument array */
111804   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
111805   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
111806 ){
111807   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
111808 }
111809 static int fts3CreateMethod(
111810   sqlite3 *db,                    /* Database connection */
111811   void *pAux,                     /* Pointer to tokenizer hash table */
111812   int argc,                       /* Number of elements in argv array */
111813   const char * const *argv,       /* xCreate/xConnect argument array */
111814   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
111815   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
111816 ){
111817   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
111818 }
111819
111820 /* 
111821 ** Implementation of the xBestIndex method for FTS3 tables. There
111822 ** are three possible strategies, in order of preference:
111823 **
111824 **   1. Direct lookup by rowid or docid. 
111825 **   2. Full-text search using a MATCH operator on a non-docid column.
111826 **   3. Linear scan of %_content table.
111827 */
111828 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
111829   Fts3Table *p = (Fts3Table *)pVTab;
111830   int i;                          /* Iterator variable */
111831   int iCons = -1;                 /* Index of constraint to use */
111832
111833   /* By default use a full table scan. This is an expensive option,
111834   ** so search through the constraints to see if a more efficient 
111835   ** strategy is possible.
111836   */
111837   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
111838   pInfo->estimatedCost = 500000;
111839   for(i=0; i<pInfo->nConstraint; i++){
111840     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
111841     if( pCons->usable==0 ) continue;
111842
111843     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
111844     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
111845      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
111846     ){
111847       pInfo->idxNum = FTS3_DOCID_SEARCH;
111848       pInfo->estimatedCost = 1.0;
111849       iCons = i;
111850     }
111851
111852     /* A MATCH constraint. Use a full-text search.
111853     **
111854     ** If there is more than one MATCH constraint available, use the first
111855     ** one encountered. If there is both a MATCH constraint and a direct
111856     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
111857     ** though the rowid/docid lookup is faster than a MATCH query, selecting
111858     ** it would lead to an "unable to use function MATCH in the requested 
111859     ** context" error.
111860     */
111861     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
111862      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
111863     ){
111864       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
111865       pInfo->estimatedCost = 2.0;
111866       iCons = i;
111867       break;
111868     }
111869   }
111870
111871   if( iCons>=0 ){
111872     pInfo->aConstraintUsage[iCons].argvIndex = 1;
111873     pInfo->aConstraintUsage[iCons].omit = 1;
111874   } 
111875   return SQLITE_OK;
111876 }
111877
111878 /*
111879 ** Implementation of xOpen method.
111880 */
111881 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
111882   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
111883
111884   UNUSED_PARAMETER(pVTab);
111885
111886   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
111887   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
111888   ** if the allocation fails, return SQLITE_NOMEM.
111889   */
111890   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
111891   if( !pCsr ){
111892     return SQLITE_NOMEM;
111893   }
111894   memset(pCsr, 0, sizeof(Fts3Cursor));
111895   return SQLITE_OK;
111896 }
111897
111898 /*
111899 ** Close the cursor.  For additional information see the documentation
111900 ** on the xClose method of the virtual table interface.
111901 */
111902 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
111903   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111904   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
111905   sqlite3_finalize(pCsr->pStmt);
111906   sqlite3Fts3ExprFree(pCsr->pExpr);
111907   sqlite3Fts3FreeDeferredTokens(pCsr);
111908   sqlite3_free(pCsr->aDoclist);
111909   sqlite3_free(pCsr->aMatchinfo);
111910   sqlite3_free(pCsr);
111911   return SQLITE_OK;
111912 }
111913
111914 /*
111915 ** Position the pCsr->pStmt statement so that it is on the row
111916 ** of the %_content table that contains the last match.  Return
111917 ** SQLITE_OK on success.  
111918 */
111919 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
111920   if( pCsr->isRequireSeek ){
111921     pCsr->isRequireSeek = 0;
111922     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
111923     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
111924       return SQLITE_OK;
111925     }else{
111926       int rc = sqlite3_reset(pCsr->pStmt);
111927       if( rc==SQLITE_OK ){
111928         /* If no row was found and no error has occured, then the %_content
111929         ** table is missing a row that is present in the full-text index.
111930         ** The data structures are corrupt.
111931         */
111932         rc = SQLITE_CORRUPT;
111933       }
111934       pCsr->isEof = 1;
111935       if( pContext ){
111936         sqlite3_result_error_code(pContext, rc);
111937       }
111938       return rc;
111939     }
111940   }else{
111941     return SQLITE_OK;
111942   }
111943 }
111944
111945 /*
111946 ** This function is used to process a single interior node when searching
111947 ** a b-tree for a term or term prefix. The node data is passed to this 
111948 ** function via the zNode/nNode parameters. The term to search for is
111949 ** passed in zTerm/nTerm.
111950 **
111951 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
111952 ** of the child node that heads the sub-tree that may contain the term.
111953 **
111954 ** If piLast is not NULL, then *piLast is set to the right-most child node
111955 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
111956 ** a prefix.
111957 **
111958 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
111959 */
111960 static int fts3ScanInteriorNode(
111961   const char *zTerm,              /* Term to select leaves for */
111962   int nTerm,                      /* Size of term zTerm in bytes */
111963   const char *zNode,              /* Buffer containing segment interior node */
111964   int nNode,                      /* Size of buffer at zNode */
111965   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
111966   sqlite3_int64 *piLast           /* OUT: Selected child node */
111967 ){
111968   int rc = SQLITE_OK;             /* Return code */
111969   const char *zCsr = zNode;       /* Cursor to iterate through node */
111970   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
111971   char *zBuffer = 0;              /* Buffer to load terms into */
111972   int nAlloc = 0;                 /* Size of allocated buffer */
111973   int isFirstTerm = 1;            /* True when processing first term on page */
111974   sqlite3_int64 iChild;           /* Block id of child node to descend to */
111975
111976   /* Skip over the 'height' varint that occurs at the start of every 
111977   ** interior node. Then load the blockid of the left-child of the b-tree
111978   ** node into variable iChild.  
111979   **
111980   ** Even if the data structure on disk is corrupted, this (reading two
111981   ** varints from the buffer) does not risk an overread. If zNode is a
111982   ** root node, then the buffer comes from a SELECT statement. SQLite does
111983   ** not make this guarantee explicitly, but in practice there are always
111984   ** either more than 20 bytes of allocated space following the nNode bytes of
111985   ** contents, or two zero bytes. Or, if the node is read from the %_segments
111986   ** table, then there are always 20 bytes of zeroed padding following the
111987   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
111988   */
111989   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
111990   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
111991   if( zCsr>zEnd ){
111992     return SQLITE_CORRUPT;
111993   }
111994   
111995   while( zCsr<zEnd && (piFirst || piLast) ){
111996     int cmp;                      /* memcmp() result */
111997     int nSuffix;                  /* Size of term suffix */
111998     int nPrefix = 0;              /* Size of term prefix */
111999     int nBuffer;                  /* Total term size */
112000   
112001     /* Load the next term on the node into zBuffer. Use realloc() to expand
112002     ** the size of zBuffer if required.  */
112003     if( !isFirstTerm ){
112004       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
112005     }
112006     isFirstTerm = 0;
112007     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
112008     
112009     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
112010       rc = SQLITE_CORRUPT;
112011       goto finish_scan;
112012     }
112013     if( nPrefix+nSuffix>nAlloc ){
112014       char *zNew;
112015       nAlloc = (nPrefix+nSuffix) * 2;
112016       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
112017       if( !zNew ){
112018         rc = SQLITE_NOMEM;
112019         goto finish_scan;
112020       }
112021       zBuffer = zNew;
112022     }
112023     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
112024     nBuffer = nPrefix + nSuffix;
112025     zCsr += nSuffix;
112026
112027     /* Compare the term we are searching for with the term just loaded from
112028     ** the interior node. If the specified term is greater than or equal
112029     ** to the term from the interior node, then all terms on the sub-tree 
112030     ** headed by node iChild are smaller than zTerm. No need to search 
112031     ** iChild.
112032     **
112033     ** If the interior node term is larger than the specified term, then
112034     ** the tree headed by iChild may contain the specified term.
112035     */
112036     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
112037     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
112038       *piFirst = iChild;
112039       piFirst = 0;
112040     }
112041
112042     if( piLast && cmp<0 ){
112043       *piLast = iChild;
112044       piLast = 0;
112045     }
112046
112047     iChild++;
112048   };
112049
112050   if( piFirst ) *piFirst = iChild;
112051   if( piLast ) *piLast = iChild;
112052
112053  finish_scan:
112054   sqlite3_free(zBuffer);
112055   return rc;
112056 }
112057
112058
112059 /*
112060 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
112061 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
112062 ** contains a term. This function searches the sub-tree headed by the zNode
112063 ** node for the range of leaf nodes that may contain the specified term
112064 ** or terms for which the specified term is a prefix.
112065 **
112066 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
112067 ** left-most leaf node in the tree that may contain the specified term.
112068 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
112069 ** right-most leaf node that may contain a term for which the specified
112070 ** term is a prefix.
112071 **
112072 ** It is possible that the range of returned leaf nodes does not contain 
112073 ** the specified term or any terms for which it is a prefix. However, if the 
112074 ** segment does contain any such terms, they are stored within the identified
112075 ** range. Because this function only inspects interior segment nodes (and
112076 ** never loads leaf nodes into memory), it is not possible to be sure.
112077 **
112078 ** If an error occurs, an error code other than SQLITE_OK is returned.
112079 */ 
112080 static int fts3SelectLeaf(
112081   Fts3Table *p,                   /* Virtual table handle */
112082   const char *zTerm,              /* Term to select leaves for */
112083   int nTerm,                      /* Size of term zTerm in bytes */
112084   const char *zNode,              /* Buffer containing segment interior node */
112085   int nNode,                      /* Size of buffer at zNode */
112086   sqlite3_int64 *piLeaf,          /* Selected leaf node */
112087   sqlite3_int64 *piLeaf2          /* Selected leaf node */
112088 ){
112089   int rc;                         /* Return code */
112090   int iHeight;                    /* Height of this node in tree */
112091
112092   assert( piLeaf || piLeaf2 );
112093
112094   sqlite3Fts3GetVarint32(zNode, &iHeight);
112095   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
112096   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
112097
112098   if( rc==SQLITE_OK && iHeight>1 ){
112099     char *zBlob = 0;              /* Blob read from %_segments table */
112100     int nBlob;                    /* Size of zBlob in bytes */
112101
112102     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
112103       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
112104       if( rc==SQLITE_OK ){
112105         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
112106       }
112107       sqlite3_free(zBlob);
112108       piLeaf = 0;
112109       zBlob = 0;
112110     }
112111
112112     if( rc==SQLITE_OK ){
112113       rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
112114     }
112115     if( rc==SQLITE_OK ){
112116       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
112117     }
112118     sqlite3_free(zBlob);
112119   }
112120
112121   return rc;
112122 }
112123
112124 /*
112125 ** This function is used to create delta-encoded serialized lists of FTS3 
112126 ** varints. Each call to this function appends a single varint to a list.
112127 */
112128 static void fts3PutDeltaVarint(
112129   char **pp,                      /* IN/OUT: Output pointer */
112130   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
112131   sqlite3_int64 iVal              /* Write this value to the list */
112132 ){
112133   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
112134   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
112135   *piPrev = iVal;
112136 }
112137
112138 /*
112139 ** When this function is called, *ppPoslist is assumed to point to the 
112140 ** start of a position-list. After it returns, *ppPoslist points to the
112141 ** first byte after the position-list.
112142 **
112143 ** A position list is list of positions (delta encoded) and columns for 
112144 ** a single document record of a doclist.  So, in other words, this
112145 ** routine advances *ppPoslist so that it points to the next docid in
112146 ** the doclist, or to the first byte past the end of the doclist.
112147 **
112148 ** If pp is not NULL, then the contents of the position list are copied
112149 ** to *pp. *pp is set to point to the first byte past the last byte copied
112150 ** before this function returns.
112151 */
112152 static void fts3PoslistCopy(char **pp, char **ppPoslist){
112153   char *pEnd = *ppPoslist;
112154   char c = 0;
112155
112156   /* The end of a position list is marked by a zero encoded as an FTS3 
112157   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
112158   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
112159   ** of some other, multi-byte, value.
112160   **
112161   ** The following while-loop moves pEnd to point to the first byte that is not 
112162   ** immediately preceded by a byte with the 0x80 bit set. Then increments
112163   ** pEnd once more so that it points to the byte immediately following the
112164   ** last byte in the position-list.
112165   */
112166   while( *pEnd | c ){
112167     c = *pEnd++ & 0x80;
112168     testcase( c!=0 && (*pEnd)==0 );
112169   }
112170   pEnd++;  /* Advance past the POS_END terminator byte */
112171
112172   if( pp ){
112173     int n = (int)(pEnd - *ppPoslist);
112174     char *p = *pp;
112175     memcpy(p, *ppPoslist, n);
112176     p += n;
112177     *pp = p;
112178   }
112179   *ppPoslist = pEnd;
112180 }
112181
112182 /*
112183 ** When this function is called, *ppPoslist is assumed to point to the 
112184 ** start of a column-list. After it returns, *ppPoslist points to the
112185 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
112186 **
112187 ** A column-list is list of delta-encoded positions for a single column
112188 ** within a single document within a doclist.
112189 **
112190 ** The column-list is terminated either by a POS_COLUMN varint (1) or
112191 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
112192 ** the POS_COLUMN or POS_END that terminates the column-list.
112193 **
112194 ** If pp is not NULL, then the contents of the column-list are copied
112195 ** to *pp. *pp is set to point to the first byte past the last byte copied
112196 ** before this function returns.  The POS_COLUMN or POS_END terminator
112197 ** is not copied into *pp.
112198 */
112199 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
112200   char *pEnd = *ppPoslist;
112201   char c = 0;
112202
112203   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
112204   ** not part of a multi-byte varint.
112205   */
112206   while( 0xFE & (*pEnd | c) ){
112207     c = *pEnd++ & 0x80;
112208     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
112209   }
112210   if( pp ){
112211     int n = (int)(pEnd - *ppPoslist);
112212     char *p = *pp;
112213     memcpy(p, *ppPoslist, n);
112214     p += n;
112215     *pp = p;
112216   }
112217   *ppPoslist = pEnd;
112218 }
112219
112220 /*
112221 ** Value used to signify the end of an position-list. This is safe because
112222 ** it is not possible to have a document with 2^31 terms.
112223 */
112224 #define POSITION_LIST_END 0x7fffffff
112225
112226 /*
112227 ** This function is used to help parse position-lists. When this function is
112228 ** called, *pp may point to the start of the next varint in the position-list
112229 ** being parsed, or it may point to 1 byte past the end of the position-list
112230 ** (in which case **pp will be a terminator bytes POS_END (0) or
112231 ** (1)).
112232 **
112233 ** If *pp points past the end of the current position-list, set *pi to 
112234 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
112235 ** increment the current value of *pi by the value read, and set *pp to
112236 ** point to the next value before returning.
112237 **
112238 ** Before calling this routine *pi must be initialized to the value of
112239 ** the previous position, or zero if we are reading the first position
112240 ** in the position-list.  Because positions are delta-encoded, the value
112241 ** of the previous position is needed in order to compute the value of
112242 ** the next position.
112243 */
112244 static void fts3ReadNextPos(
112245   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
112246   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
112247 ){
112248   if( (**pp)&0xFE ){
112249     fts3GetDeltaVarint(pp, pi);
112250     *pi -= 2;
112251   }else{
112252     *pi = POSITION_LIST_END;
112253   }
112254 }
112255
112256 /*
112257 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
112258 ** the value of iCol encoded as a varint to *pp.   This will start a new
112259 ** column list.
112260 **
112261 ** Set *pp to point to the byte just after the last byte written before 
112262 ** returning (do not modify it if iCol==0). Return the total number of bytes
112263 ** written (0 if iCol==0).
112264 */
112265 static int fts3PutColNumber(char **pp, int iCol){
112266   int n = 0;                      /* Number of bytes written */
112267   if( iCol ){
112268     char *p = *pp;                /* Output pointer */
112269     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
112270     *p = 0x01;
112271     *pp = &p[n];
112272   }
112273   return n;
112274 }
112275
112276 /*
112277 ** Compute the union of two position lists.  The output written
112278 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
112279 ** order and with any duplicates removed.  All pointers are
112280 ** updated appropriately.   The caller is responsible for insuring
112281 ** that there is enough space in *pp to hold the complete output.
112282 */
112283 static void fts3PoslistMerge(
112284   char **pp,                      /* Output buffer */
112285   char **pp1,                     /* Left input list */
112286   char **pp2                      /* Right input list */
112287 ){
112288   char *p = *pp;
112289   char *p1 = *pp1;
112290   char *p2 = *pp2;
112291
112292   while( *p1 || *p2 ){
112293     int iCol1;         /* The current column index in pp1 */
112294     int iCol2;         /* The current column index in pp2 */
112295
112296     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
112297     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
112298     else iCol1 = 0;
112299
112300     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
112301     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
112302     else iCol2 = 0;
112303
112304     if( iCol1==iCol2 ){
112305       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
112306       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
112307       sqlite3_int64 iPrev = 0;
112308       int n = fts3PutColNumber(&p, iCol1);
112309       p1 += n;
112310       p2 += n;
112311
112312       /* At this point, both p1 and p2 point to the start of column-lists
112313       ** for the same column (the column with index iCol1 and iCol2).
112314       ** A column-list is a list of non-negative delta-encoded varints, each 
112315       ** incremented by 2 before being stored. Each list is terminated by a
112316       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
112317       ** and writes the results to buffer p. p is left pointing to the byte
112318       ** after the list written. No terminator (POS_END or POS_COLUMN) is
112319       ** written to the output.
112320       */
112321       fts3GetDeltaVarint(&p1, &i1);
112322       fts3GetDeltaVarint(&p2, &i2);
112323       do {
112324         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
112325         iPrev -= 2;
112326         if( i1==i2 ){
112327           fts3ReadNextPos(&p1, &i1);
112328           fts3ReadNextPos(&p2, &i2);
112329         }else if( i1<i2 ){
112330           fts3ReadNextPos(&p1, &i1);
112331         }else{
112332           fts3ReadNextPos(&p2, &i2);
112333         }
112334       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
112335     }else if( iCol1<iCol2 ){
112336       p1 += fts3PutColNumber(&p, iCol1);
112337       fts3ColumnlistCopy(&p, &p1);
112338     }else{
112339       p2 += fts3PutColNumber(&p, iCol2);
112340       fts3ColumnlistCopy(&p, &p2);
112341     }
112342   }
112343
112344   *p++ = POS_END;
112345   *pp = p;
112346   *pp1 = p1 + 1;
112347   *pp2 = p2 + 1;
112348 }
112349
112350 /*
112351 ** nToken==1 searches for adjacent positions.
112352 **
112353 ** This function is used to merge two position lists into one. When it is
112354 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
112355 ** the part of a doclist that follows each document id. For example, if a row
112356 ** contains:
112357 **
112358 **     'a b c'|'x y z'|'a b b a'
112359 **
112360 ** Then the position list for this row for token 'b' would consist of:
112361 **
112362 **     0x02 0x01 0x02 0x03 0x03 0x00
112363 **
112364 ** When this function returns, both *pp1 and *pp2 are left pointing to the
112365 ** byte following the 0x00 terminator of their respective position lists.
112366 **
112367 ** If isSaveLeft is 0, an entry is added to the output position list for 
112368 ** each position in *pp2 for which there exists one or more positions in
112369 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
112370 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
112371 ** slots before it.
112372 */
112373 static int fts3PoslistPhraseMerge(
112374   char **pp,                      /* IN/OUT: Preallocated output buffer */
112375   int nToken,                     /* Maximum difference in token positions */
112376   int isSaveLeft,                 /* Save the left position */
112377   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
112378   char **pp1,                     /* IN/OUT: Left input list */
112379   char **pp2                      /* IN/OUT: Right input list */
112380 ){
112381   char *p = (pp ? *pp : 0);
112382   char *p1 = *pp1;
112383   char *p2 = *pp2;
112384   int iCol1 = 0;
112385   int iCol2 = 0;
112386
112387   /* Never set both isSaveLeft and isExact for the same invocation. */
112388   assert( isSaveLeft==0 || isExact==0 );
112389
112390   assert( *p1!=0 && *p2!=0 );
112391   if( *p1==POS_COLUMN ){ 
112392     p1++;
112393     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112394   }
112395   if( *p2==POS_COLUMN ){ 
112396     p2++;
112397     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112398   }
112399
112400   while( 1 ){
112401     if( iCol1==iCol2 ){
112402       char *pSave = p;
112403       sqlite3_int64 iPrev = 0;
112404       sqlite3_int64 iPos1 = 0;
112405       sqlite3_int64 iPos2 = 0;
112406
112407       if( pp && iCol1 ){
112408         *p++ = POS_COLUMN;
112409         p += sqlite3Fts3PutVarint(p, iCol1);
112410       }
112411
112412       assert( *p1!=POS_END && *p1!=POS_COLUMN );
112413       assert( *p2!=POS_END && *p2!=POS_COLUMN );
112414       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112415       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112416
112417       while( 1 ){
112418         if( iPos2==iPos1+nToken 
112419          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
112420         ){
112421           sqlite3_int64 iSave;
112422           if( !pp ){
112423             fts3PoslistCopy(0, &p2);
112424             fts3PoslistCopy(0, &p1);
112425             *pp1 = p1;
112426             *pp2 = p2;
112427             return 1;
112428           }
112429           iSave = isSaveLeft ? iPos1 : iPos2;
112430           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
112431           pSave = 0;
112432         }
112433         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
112434           if( (*p2&0xFE)==0 ) break;
112435           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
112436         }else{
112437           if( (*p1&0xFE)==0 ) break;
112438           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
112439         }
112440       }
112441
112442       if( pSave ){
112443         assert( pp && p );
112444         p = pSave;
112445       }
112446
112447       fts3ColumnlistCopy(0, &p1);
112448       fts3ColumnlistCopy(0, &p2);
112449       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
112450       if( 0==*p1 || 0==*p2 ) break;
112451
112452       p1++;
112453       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112454       p2++;
112455       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112456     }
112457
112458     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
112459     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
112460     ** end of the position list, or the 0x01 that precedes the next 
112461     ** column-number in the position list. 
112462     */
112463     else if( iCol1<iCol2 ){
112464       fts3ColumnlistCopy(0, &p1);
112465       if( 0==*p1 ) break;
112466       p1++;
112467       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
112468     }else{
112469       fts3ColumnlistCopy(0, &p2);
112470       if( 0==*p2 ) break;
112471       p2++;
112472       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
112473     }
112474   }
112475
112476   fts3PoslistCopy(0, &p2);
112477   fts3PoslistCopy(0, &p1);
112478   *pp1 = p1;
112479   *pp2 = p2;
112480   if( !pp || *pp==p ){
112481     return 0;
112482   }
112483   *p++ = 0x00;
112484   *pp = p;
112485   return 1;
112486 }
112487
112488 /*
112489 ** Merge two position-lists as required by the NEAR operator.
112490 */
112491 static int fts3PoslistNearMerge(
112492   char **pp,                      /* Output buffer */
112493   char *aTmp,                     /* Temporary buffer space */
112494   int nRight,                     /* Maximum difference in token positions */
112495   int nLeft,                      /* Maximum difference in token positions */
112496   char **pp1,                     /* IN/OUT: Left input list */
112497   char **pp2                      /* IN/OUT: Right input list */
112498 ){
112499   char *p1 = *pp1;
112500   char *p2 = *pp2;
112501
112502   if( !pp ){
112503     if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
112504     *pp1 = p1;
112505     *pp2 = p2;
112506     return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
112507   }else{
112508     char *pTmp1 = aTmp;
112509     char *pTmp2;
112510     char *aTmp2;
112511     int res = 1;
112512
112513     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
112514     aTmp2 = pTmp2 = pTmp1;
112515     *pp1 = p1;
112516     *pp2 = p2;
112517     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
112518     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
112519       fts3PoslistMerge(pp, &aTmp, &aTmp2);
112520     }else if( pTmp1!=aTmp ){
112521       fts3PoslistCopy(pp, &aTmp);
112522     }else if( pTmp2!=aTmp2 ){
112523       fts3PoslistCopy(pp, &aTmp2);
112524     }else{
112525       res = 0;
112526     }
112527
112528     return res;
112529   }
112530 }
112531
112532 /*
112533 ** Values that may be used as the first parameter to fts3DoclistMerge().
112534 */
112535 #define MERGE_NOT        2        /* D + D -> D */
112536 #define MERGE_AND        3        /* D + D -> D */
112537 #define MERGE_OR         4        /* D + D -> D */
112538 #define MERGE_POS_OR     5        /* P + P -> P */
112539 #define MERGE_PHRASE     6        /* P + P -> D */
112540 #define MERGE_POS_PHRASE 7        /* P + P -> P */
112541 #define MERGE_NEAR       8        /* P + P -> D */
112542 #define MERGE_POS_NEAR   9        /* P + P -> P */
112543
112544 /*
112545 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
112546 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
112547 ** which is guaranteed to be large enough to hold the results. The number
112548 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
112549 **
112550 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
112551 ** occurs while allocating a temporary buffer as part of the merge operation,
112552 ** SQLITE_NOMEM is returned.
112553 */
112554 static int fts3DoclistMerge(
112555   int mergetype,                  /* One of the MERGE_XXX constants */
112556   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112557   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
112558   char *aBuffer,                  /* Pre-allocated output buffer */
112559   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
112560   char *a1,                       /* Buffer containing first doclist */
112561   int n1,                         /* Size of buffer a1 */
112562   char *a2,                       /* Buffer containing second doclist */
112563   int n2,                         /* Size of buffer a2 */
112564   int *pnDoc                      /* OUT: Number of docids in output */
112565 ){
112566   sqlite3_int64 i1 = 0;
112567   sqlite3_int64 i2 = 0;
112568   sqlite3_int64 iPrev = 0;
112569
112570   char *p = aBuffer;
112571   char *p1 = a1;
112572   char *p2 = a2;
112573   char *pEnd1 = &a1[n1];
112574   char *pEnd2 = &a2[n2];
112575   int nDoc = 0;
112576
112577   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
112578        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
112579        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
112580        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
112581   );
112582
112583   if( !aBuffer ){
112584     *pnBuffer = 0;
112585     return SQLITE_NOMEM;
112586   }
112587
112588   /* Read the first docid from each doclist */
112589   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112590   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112591
112592   switch( mergetype ){
112593     case MERGE_OR:
112594     case MERGE_POS_OR:
112595       while( p1 || p2 ){
112596         if( p2 && p1 && i1==i2 ){
112597           fts3PutDeltaVarint(&p, &iPrev, i1);
112598           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
112599           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112600           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112601         }else if( !p2 || (p1 && i1<i2) ){
112602           fts3PutDeltaVarint(&p, &iPrev, i1);
112603           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
112604           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112605         }else{
112606           fts3PutDeltaVarint(&p, &iPrev, i2);
112607           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
112608           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112609         }
112610       }
112611       break;
112612
112613     case MERGE_AND:
112614       while( p1 && p2 ){
112615         if( i1==i2 ){
112616           fts3PutDeltaVarint(&p, &iPrev, i1);
112617           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112618           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112619           nDoc++;
112620         }else if( i1<i2 ){
112621           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112622         }else{
112623           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112624         }
112625       }
112626       break;
112627
112628     case MERGE_NOT:
112629       while( p1 ){
112630         if( p2 && i1==i2 ){
112631           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112632           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112633         }else if( !p2 || i1<i2 ){
112634           fts3PutDeltaVarint(&p, &iPrev, i1);
112635           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112636         }else{
112637           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112638         }
112639       }
112640       break;
112641
112642     case MERGE_POS_PHRASE:
112643     case MERGE_PHRASE: {
112644       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
112645       while( p1 && p2 ){
112646         if( i1==i2 ){
112647           char *pSave = p;
112648           sqlite3_int64 iPrevSave = iPrev;
112649           fts3PutDeltaVarint(&p, &iPrev, i1);
112650           if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
112651             p = pSave;
112652             iPrev = iPrevSave;
112653           }else{
112654             nDoc++;
112655           }
112656           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112657           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112658         }else if( i1<i2 ){
112659           fts3PoslistCopy(0, &p1);
112660           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112661         }else{
112662           fts3PoslistCopy(0, &p2);
112663           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112664         }
112665       }
112666       break;
112667     }
112668
112669     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
112670       char *aTmp = 0;
112671       char **ppPos = 0;
112672
112673       if( mergetype==MERGE_POS_NEAR ){
112674         ppPos = &p;
112675         aTmp = sqlite3_malloc(2*(n1+n2+1));
112676         if( !aTmp ){
112677           return SQLITE_NOMEM;
112678         }
112679       }
112680
112681       while( p1 && p2 ){
112682         if( i1==i2 ){
112683           char *pSave = p;
112684           sqlite3_int64 iPrevSave = iPrev;
112685           fts3PutDeltaVarint(&p, &iPrev, i1);
112686
112687           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
112688             iPrev = iPrevSave;
112689             p = pSave;
112690           }
112691
112692           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112693           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112694         }else if( i1<i2 ){
112695           fts3PoslistCopy(0, &p1);
112696           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
112697         }else{
112698           fts3PoslistCopy(0, &p2);
112699           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
112700         }
112701       }
112702       sqlite3_free(aTmp);
112703       break;
112704     }
112705   }
112706
112707   if( pnDoc ) *pnDoc = nDoc;
112708   *pnBuffer = (int)(p-aBuffer);
112709   return SQLITE_OK;
112710 }
112711
112712 /* 
112713 ** A pointer to an instance of this structure is used as the context 
112714 ** argument to sqlite3Fts3SegReaderIterate()
112715 */
112716 typedef struct TermSelect TermSelect;
112717 struct TermSelect {
112718   int isReqPos;
112719   char *aaOutput[16];             /* Malloc'd output buffer */
112720   int anOutput[16];               /* Size of output in bytes */
112721 };
112722
112723 /*
112724 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
112725 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
112726 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
112727 **
112728 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
112729 ** the responsibility of the caller to free any doclists left in the
112730 ** TermSelect.aaOutput[] array.
112731 */
112732 static int fts3TermSelectMerge(TermSelect *pTS){
112733   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
112734   char *aOut = 0;
112735   int nOut = 0;
112736   int i;
112737
112738   /* Loop through the doclists in the aaOutput[] array. Merge them all
112739   ** into a single doclist.
112740   */
112741   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
112742     if( pTS->aaOutput[i] ){
112743       if( !aOut ){
112744         aOut = pTS->aaOutput[i];
112745         nOut = pTS->anOutput[i];
112746         pTS->aaOutput[i] = 0;
112747       }else{
112748         int nNew = nOut + pTS->anOutput[i];
112749         char *aNew = sqlite3_malloc(nNew);
112750         if( !aNew ){
112751           sqlite3_free(aOut);
112752           return SQLITE_NOMEM;
112753         }
112754         fts3DoclistMerge(mergetype, 0, 0,
112755             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
112756         );
112757         sqlite3_free(pTS->aaOutput[i]);
112758         sqlite3_free(aOut);
112759         pTS->aaOutput[i] = 0;
112760         aOut = aNew;
112761         nOut = nNew;
112762       }
112763     }
112764   }
112765
112766   pTS->aaOutput[0] = aOut;
112767   pTS->anOutput[0] = nOut;
112768   return SQLITE_OK;
112769 }
112770
112771 /*
112772 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
112773 ** querying the full-text index for a doclist associated with a term or
112774 ** term-prefix.
112775 */
112776 static int fts3TermSelectCb(
112777   Fts3Table *p,                   /* Virtual table object */
112778   void *pContext,                 /* Pointer to TermSelect structure */
112779   char *zTerm,
112780   int nTerm,
112781   char *aDoclist,
112782   int nDoclist
112783 ){
112784   TermSelect *pTS = (TermSelect *)pContext;
112785
112786   UNUSED_PARAMETER(p);
112787   UNUSED_PARAMETER(zTerm);
112788   UNUSED_PARAMETER(nTerm);
112789
112790   if( pTS->aaOutput[0]==0 ){
112791     /* If this is the first term selected, copy the doclist to the output
112792     ** buffer using memcpy(). TODO: Add a way to transfer control of the
112793     ** aDoclist buffer from the caller so as to avoid the memcpy().
112794     */
112795     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
112796     pTS->anOutput[0] = nDoclist;
112797     if( pTS->aaOutput[0] ){
112798       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
112799     }else{
112800       return SQLITE_NOMEM;
112801     }
112802   }else{
112803     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
112804     char *aMerge = aDoclist;
112805     int nMerge = nDoclist;
112806     int iOut;
112807
112808     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
112809       char *aNew;
112810       int nNew;
112811       if( pTS->aaOutput[iOut]==0 ){
112812         assert( iOut>0 );
112813         pTS->aaOutput[iOut] = aMerge;
112814         pTS->anOutput[iOut] = nMerge;
112815         break;
112816       }
112817
112818       nNew = nMerge + pTS->anOutput[iOut];
112819       aNew = sqlite3_malloc(nNew);
112820       if( !aNew ){
112821         if( aMerge!=aDoclist ){
112822           sqlite3_free(aMerge);
112823         }
112824         return SQLITE_NOMEM;
112825       }
112826       fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew, 
112827           pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
112828       );
112829
112830       if( iOut>0 ) sqlite3_free(aMerge);
112831       sqlite3_free(pTS->aaOutput[iOut]);
112832       pTS->aaOutput[iOut] = 0;
112833
112834       aMerge = aNew;
112835       nMerge = nNew;
112836       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
112837         pTS->aaOutput[iOut] = aMerge;
112838         pTS->anOutput[iOut] = nMerge;
112839       }
112840     }
112841   }
112842   return SQLITE_OK;
112843 }
112844
112845 static int fts3DeferredTermSelect(
112846   Fts3DeferredToken *pToken,      /* Phrase token */
112847   int isTermPos,                  /* True to include positions */
112848   int *pnOut,                     /* OUT: Size of list */
112849   char **ppOut                    /* OUT: Body of list */
112850 ){
112851   char *aSource;
112852   int nSource;
112853
112854   aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
112855   if( !aSource ){
112856     *pnOut = 0;
112857     *ppOut = 0;
112858   }else if( isTermPos ){
112859     *ppOut = sqlite3_malloc(nSource);
112860     if( !*ppOut ) return SQLITE_NOMEM;
112861     memcpy(*ppOut, aSource, nSource);
112862     *pnOut = nSource;
112863   }else{
112864     sqlite3_int64 docid;
112865     *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
112866     *ppOut = sqlite3_malloc(*pnOut);
112867     if( !*ppOut ) return SQLITE_NOMEM;
112868     sqlite3Fts3PutVarint(*ppOut, docid);
112869   }
112870
112871   return SQLITE_OK;
112872 }
112873
112874 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
112875   Fts3Table *p,                   /* FTS3 table handle */
112876   int iLevel,                     /* Level of segments to scan */
112877   const char *zTerm,              /* Term to query for */
112878   int nTerm,                      /* Size of zTerm in bytes */
112879   int isPrefix,                   /* True for a prefix search */
112880   int isScan,                     /* True to scan from zTerm to EOF */
112881   Fts3SegReaderCursor *pCsr       /* Cursor object to populate */
112882 ){
112883   int rc = SQLITE_OK;
112884   int rc2;
112885   int iAge = 0;
112886   sqlite3_stmt *pStmt = 0;
112887   Fts3SegReader *pPending = 0;
112888
112889   assert( iLevel==FTS3_SEGCURSOR_ALL 
112890       ||  iLevel==FTS3_SEGCURSOR_PENDING 
112891       ||  iLevel>=0
112892   );
112893   assert( FTS3_SEGCURSOR_PENDING<0 );
112894   assert( FTS3_SEGCURSOR_ALL<0 );
112895   assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
112896   assert( isPrefix==0 || isScan==0 );
112897
112898
112899   memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
112900
112901   /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
112902   assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
112903   if( iLevel<0 && isScan==0 ){
112904     rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
112905     if( rc==SQLITE_OK && pPending ){
112906       int nByte = (sizeof(Fts3SegReader *) * 16);
112907       pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
112908       if( pCsr->apSegment==0 ){
112909         rc = SQLITE_NOMEM;
112910       }else{
112911         pCsr->apSegment[0] = pPending;
112912         pCsr->nSegment = 1;
112913         pPending = 0;
112914       }
112915     }
112916   }
112917
112918   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
112919     if( rc==SQLITE_OK ){
112920       rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
112921     }
112922     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
112923
112924       /* Read the values returned by the SELECT into local variables. */
112925       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
112926       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
112927       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
112928       int nRoot = sqlite3_column_bytes(pStmt, 4);
112929       char const *zRoot = sqlite3_column_blob(pStmt, 4);
112930
112931       /* If nSegment is a multiple of 16 the array needs to be extended. */
112932       if( (pCsr->nSegment%16)==0 ){
112933         Fts3SegReader **apNew;
112934         int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
112935         apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
112936         if( !apNew ){
112937           rc = SQLITE_NOMEM;
112938           goto finished;
112939         }
112940         pCsr->apSegment = apNew;
112941       }
112942
112943       /* If zTerm is not NULL, and this segment is not stored entirely on its
112944       ** root node, the range of leaves scanned can be reduced. Do this. */
112945       if( iStartBlock && zTerm ){
112946         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
112947         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
112948         if( rc!=SQLITE_OK ) goto finished;
112949         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
112950       }
112951  
112952       rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
112953           iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
112954       );
112955       if( rc!=SQLITE_OK ) goto finished;
112956       pCsr->nSegment++;
112957       iAge++;
112958     }
112959   }
112960
112961  finished:
112962   rc2 = sqlite3_reset(pStmt);
112963   if( rc==SQLITE_DONE ) rc = rc2;
112964   sqlite3Fts3SegReaderFree(pPending);
112965
112966   return rc;
112967 }
112968
112969
112970 static int fts3TermSegReaderCursor(
112971   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
112972   const char *zTerm,              /* Term to query for */
112973   int nTerm,                      /* Size of zTerm in bytes */
112974   int isPrefix,                   /* True for a prefix search */
112975   Fts3SegReaderCursor **ppSegcsr  /* OUT: Allocated seg-reader cursor */
112976 ){
112977   Fts3SegReaderCursor *pSegcsr;   /* Object to allocate and return */
112978   int rc = SQLITE_NOMEM;          /* Return code */
112979
112980   pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
112981   if( pSegcsr ){
112982     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
112983     int i;
112984     int nCost = 0;
112985     rc = sqlite3Fts3SegReaderCursor(
112986         p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
112987   
112988     for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
112989       rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
112990     }
112991     pSegcsr->nCost = nCost;
112992   }
112993
112994   *ppSegcsr = pSegcsr;
112995   return rc;
112996 }
112997
112998 static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
112999   sqlite3Fts3SegReaderFinish(pSegcsr);
113000   sqlite3_free(pSegcsr);
113001 }
113002
113003 /*
113004 ** This function retreives the doclist for the specified term (or term
113005 ** prefix) from the database. 
113006 **
113007 ** The returned doclist may be in one of two formats, depending on the 
113008 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
113009 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
113010 ** is non-zero, then the returned list is in the same format as is stored 
113011 ** in the database without the found length specifier at the start of on-disk
113012 ** doclists.
113013 */
113014 static int fts3TermSelect(
113015   Fts3Table *p,                   /* Virtual table handle */
113016   Fts3PhraseToken *pTok,          /* Token to query for */
113017   int iColumn,                    /* Column to query (or -ve for all columns) */
113018   int isReqPos,                   /* True to include position lists in output */
113019   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
113020   char **ppOut                    /* OUT: Malloced result buffer */
113021 ){
113022   int rc;                         /* Return code */
113023   Fts3SegReaderCursor *pSegcsr;   /* Seg-reader cursor for this term */
113024   TermSelect tsc;                 /* Context object for fts3TermSelectCb() */
113025   Fts3SegFilter filter;           /* Segment term filter configuration */
113026
113027   pSegcsr = pTok->pSegcsr;
113028   memset(&tsc, 0, sizeof(TermSelect));
113029   tsc.isReqPos = isReqPos;
113030
113031   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
113032         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
113033         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
113034         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
113035   filter.iCol = iColumn;
113036   filter.zTerm = pTok->z;
113037   filter.nTerm = pTok->n;
113038
113039   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
113040   while( SQLITE_OK==rc
113041       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
113042   ){
113043     rc = fts3TermSelectCb(p, (void *)&tsc, 
113044         pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
113045     );
113046   }
113047
113048   if( rc==SQLITE_OK ){
113049     rc = fts3TermSelectMerge(&tsc);
113050   }
113051   if( rc==SQLITE_OK ){
113052     *ppOut = tsc.aaOutput[0];
113053     *pnOut = tsc.anOutput[0];
113054   }else{
113055     int i;
113056     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
113057       sqlite3_free(tsc.aaOutput[i]);
113058     }
113059   }
113060
113061   fts3SegReaderCursorFree(pSegcsr);
113062   pTok->pSegcsr = 0;
113063   return rc;
113064 }
113065
113066 /*
113067 ** This function counts the total number of docids in the doclist stored
113068 ** in buffer aList[], size nList bytes.
113069 **
113070 ** If the isPoslist argument is true, then it is assumed that the doclist
113071 ** contains a position-list following each docid. Otherwise, it is assumed
113072 ** that the doclist is simply a list of docids stored as delta encoded 
113073 ** varints.
113074 */
113075 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
113076   int nDoc = 0;                   /* Return value */
113077   if( aList ){
113078     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
113079     char *p = aList;              /* Cursor */
113080     if( !isPoslist ){
113081       /* The number of docids in the list is the same as the number of 
113082       ** varints. In FTS3 a varint consists of a single byte with the 0x80 
113083       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
113084       ** count the varints in the buffer, just count the number of bytes
113085       ** with the 0x80 bit clear.  */
113086       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
113087     }else{
113088       while( p<aEnd ){
113089         nDoc++;
113090         while( (*p++)&0x80 );     /* Skip docid varint */
113091         fts3PoslistCopy(0, &p);   /* Skip over position list */
113092       }
113093     }
113094   }
113095
113096   return nDoc;
113097 }
113098
113099 /*
113100 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
113101 */
113102 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
113103   int rc = SQLITE_OK;
113104   if( pExpr ){
113105     rc = fts3DeferExpression(pCsr, pExpr->pLeft);
113106     if( rc==SQLITE_OK ){
113107       rc = fts3DeferExpression(pCsr, pExpr->pRight);
113108     }
113109     if( pExpr->eType==FTSQUERY_PHRASE ){
113110       int iCol = pExpr->pPhrase->iColumn;
113111       int i;
113112       for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
113113         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
113114         if( pToken->pDeferred==0 ){
113115           rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
113116         }
113117       }
113118     }
113119   }
113120   return rc;
113121 }
113122
113123 /*
113124 ** This function removes the position information from a doclist. When
113125 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
113126 ** position information. This function removes the position information so
113127 ** that aList contains only docids, and adjusts *pnList to reflect the new
113128 ** (possibly reduced) size of the doclist.
113129 */
113130 static void fts3DoclistStripPositions(
113131   char *aList,                    /* IN/OUT: Buffer containing doclist */
113132   int *pnList                     /* IN/OUT: Size of doclist in bytes */
113133 ){
113134   if( aList ){
113135     char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
113136     char *p = aList;              /* Input cursor */
113137     char *pOut = aList;           /* Output cursor */
113138   
113139     while( p<aEnd ){
113140       sqlite3_int64 delta;
113141       p += sqlite3Fts3GetVarint(p, &delta);
113142       fts3PoslistCopy(0, &p);
113143       pOut += sqlite3Fts3PutVarint(pOut, delta);
113144     }
113145
113146     *pnList = (int)(pOut - aList);
113147   }
113148 }
113149
113150 /* 
113151 ** Return a DocList corresponding to the phrase *pPhrase.
113152 **
113153 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
113154 ** then no tokens in the phrase were looked up in the full-text index. This
113155 ** is only possible when this function is called from within xFilter(). The
113156 ** caller should assume that all documents match the phrase. The actual
113157 ** filtering will take place in xNext().
113158 */
113159 static int fts3PhraseSelect(
113160   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
113161   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
113162   int isReqPos,                   /* True if output should contain positions */
113163   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
113164   int *pnOut                      /* OUT: Size of buffer at *paOut */
113165 ){
113166   char *pOut = 0;
113167   int nOut = 0;
113168   int rc = SQLITE_OK;
113169   int ii;
113170   int iCol = pPhrase->iColumn;
113171   int isTermPos = (pPhrase->nToken>1 || isReqPos);
113172   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
113173   int isFirst = 1;
113174
113175   int iPrevTok = 0;
113176   int nDoc = 0;
113177
113178   /* If this is an xFilter() evaluation, create a segment-reader for each
113179   ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
113180   ** evaluation, only create segment-readers if there are no Fts3DeferredToken
113181   ** objects attached to the phrase-tokens.
113182   */
113183   for(ii=0; ii<pPhrase->nToken; ii++){
113184     Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113185     if( pTok->pSegcsr==0 ){
113186       if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
113187        || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0) 
113188        || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext) 
113189       ){
113190         rc = fts3TermSegReaderCursor(
113191             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113192         );
113193         if( rc!=SQLITE_OK ) return rc;
113194       }
113195     }
113196   }
113197
113198   for(ii=0; ii<pPhrase->nToken; ii++){
113199     Fts3PhraseToken *pTok;        /* Token to find doclist for */
113200     int iTok = 0;                 /* The token being queried this iteration */
113201     char *pList = 0;              /* Pointer to token doclist */
113202     int nList = 0;                /* Size of buffer at pList */
113203
113204     /* Select a token to process. If this is an xFilter() call, then tokens 
113205     ** are processed in order from least to most costly. Otherwise, tokens 
113206     ** are processed in the order in which they occur in the phrase.
113207     */
113208     if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
113209       assert( isReqPos );
113210       iTok = ii;
113211       pTok = &pPhrase->aToken[iTok];
113212       if( pTok->bFulltext==0 ) continue;
113213     }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
113214       iTok = ii;
113215       pTok = &pPhrase->aToken[iTok];
113216     }else{
113217       int nMinCost = 0x7FFFFFFF;
113218       int jj;
113219
113220       /* Find the remaining token with the lowest cost. */
113221       for(jj=0; jj<pPhrase->nToken; jj++){
113222         Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
113223         if( pSegcsr && pSegcsr->nCost<nMinCost ){
113224           iTok = jj;
113225           nMinCost = pSegcsr->nCost;
113226         }
113227       }
113228       pTok = &pPhrase->aToken[iTok];
113229
113230       /* This branch is taken if it is determined that loading the doclist
113231       ** for the next token would require more IO than loading all documents
113232       ** currently identified by doclist pOut/nOut. No further doclists will
113233       ** be loaded from the full-text index for this phrase.
113234       */
113235       if( nMinCost>nDoc && ii>0 ){
113236         rc = fts3DeferExpression(pCsr, pCsr->pExpr);
113237         break;
113238       }
113239     }
113240
113241     if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
113242       rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
113243     }else{
113244       if( pTok->pSegcsr ){
113245         rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
113246       }
113247       pTok->bFulltext = 1;
113248     }
113249     assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
113250     if( rc!=SQLITE_OK ) break;
113251
113252     if( isFirst ){
113253       pOut = pList;
113254       nOut = nList;
113255       if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
113256         nDoc = fts3DoclistCountDocids(1, pOut, nOut);
113257       }
113258       isFirst = 0;
113259       iPrevTok = iTok;
113260     }else{
113261       /* Merge the new term list and the current output. */
113262       char *aLeft, *aRight;
113263       int nLeft, nRight;
113264       int nDist;
113265       int mt;
113266
113267       /* If this is the final token of the phrase, and positions were not
113268       ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
113269       ** This drops the position information from the output list.
113270       */
113271       mt = MERGE_POS_PHRASE;
113272       if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
113273
113274       assert( iPrevTok!=iTok );
113275       if( iPrevTok<iTok ){
113276         aLeft = pOut;
113277         nLeft = nOut;
113278         aRight = pList;
113279         nRight = nList;
113280         nDist = iTok-iPrevTok;
113281         iPrevTok = iTok;
113282       }else{
113283         aRight = pOut;
113284         nRight = nOut;
113285         aLeft = pList;
113286         nLeft = nList;
113287         nDist = iPrevTok-iTok;
113288       }
113289       pOut = aRight;
113290       fts3DoclistMerge(
113291           mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
113292       );
113293       sqlite3_free(aLeft);
113294     }
113295     assert( nOut==0 || pOut!=0 );
113296   }
113297
113298   if( rc==SQLITE_OK ){
113299     if( ii!=pPhrase->nToken ){
113300       assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
113301       fts3DoclistStripPositions(pOut, &nOut);
113302     }
113303     *paOut = pOut;
113304     *pnOut = nOut;
113305   }else{
113306     sqlite3_free(pOut);
113307   }
113308   return rc;
113309 }
113310
113311 /*
113312 ** This function merges two doclists according to the requirements of a
113313 ** NEAR operator.
113314 **
113315 ** Both input doclists must include position information. The output doclist 
113316 ** includes position information if the first argument to this function
113317 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
113318 */
113319 static int fts3NearMerge(
113320   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
113321   int nNear,                      /* Parameter to NEAR operator */
113322   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
113323   char *aLeft,                    /* Doclist for LHS (incl. positions) */
113324   int nLeft,                      /* Size of LHS doclist in bytes */
113325   int nTokenRight,                /* As nTokenLeft */
113326   char *aRight,                   /* As aLeft */
113327   int nRight,                     /* As nRight */
113328   char **paOut,                   /* OUT: Results of merge (malloced) */
113329   int *pnOut                      /* OUT: Sized of output buffer */
113330 ){
113331   char *aOut;                     /* Buffer to write output doclist to */
113332   int rc;                         /* Return code */
113333
113334   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
113335
113336   aOut = sqlite3_malloc(nLeft+nRight+1);
113337   if( aOut==0 ){
113338     rc = SQLITE_NOMEM;
113339   }else{
113340     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
113341       aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
113342     );
113343     if( rc!=SQLITE_OK ){
113344       sqlite3_free(aOut);
113345       aOut = 0;
113346     }
113347   }
113348
113349   *paOut = aOut;
113350   return rc;
113351 }
113352
113353 /*
113354 ** This function is used as part of the processing for the snippet() and
113355 ** offsets() functions.
113356 **
113357 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
113358 ** have their respective doclists (including position information) loaded
113359 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
113360 ** each doclist that are not within nNear tokens of a corresponding entry
113361 ** in the other doclist.
113362 */
113363 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
113364   int rc;                         /* Return code */
113365
113366   assert( pLeft->eType==FTSQUERY_PHRASE );
113367   assert( pRight->eType==FTSQUERY_PHRASE );
113368   assert( pLeft->isLoaded && pRight->isLoaded );
113369
113370   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
113371     sqlite3_free(pLeft->aDoclist);
113372     sqlite3_free(pRight->aDoclist);
113373     pRight->aDoclist = 0;
113374     pLeft->aDoclist = 0;
113375     rc = SQLITE_OK;
113376   }else{
113377     char *aOut;                   /* Buffer in which to assemble new doclist */
113378     int nOut;                     /* Size of buffer aOut in bytes */
113379
113380     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
113381         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113382         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113383         &aOut, &nOut
113384     );
113385     if( rc!=SQLITE_OK ) return rc;
113386     sqlite3_free(pRight->aDoclist);
113387     pRight->aDoclist = aOut;
113388     pRight->nDoclist = nOut;
113389
113390     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
113391         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
113392         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
113393         &aOut, &nOut
113394     );
113395     sqlite3_free(pLeft->aDoclist);
113396     pLeft->aDoclist = aOut;
113397     pLeft->nDoclist = nOut;
113398   }
113399   return rc;
113400 }
113401
113402
113403 /*
113404 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr. 
113405 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
113406 ** variables of each token structure.
113407 */
113408 static int fts3ExprAllocateSegReaders(
113409   Fts3Cursor *pCsr,               /* FTS3 table */
113410   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
113411   int *pnExpr                     /* OUT: Number of AND'd expressions */
113412 ){
113413   int rc = SQLITE_OK;             /* Return code */
113414
113415   assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
113416   if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
113417     (*pnExpr)++;
113418     pnExpr = 0;
113419   }
113420
113421   if( pExpr->eType==FTSQUERY_PHRASE ){
113422     Fts3Phrase *pPhrase = pExpr->pPhrase;
113423     int ii;
113424
113425     for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
113426       Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
113427       if( pTok->pSegcsr==0 ){
113428         rc = fts3TermSegReaderCursor(
113429             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
113430         );
113431       }
113432     }
113433   }else{ 
113434     rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
113435     if( rc==SQLITE_OK ){
113436       rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
113437     }
113438   }
113439   return rc;
113440 }
113441
113442 /*
113443 ** Free the Fts3SegReaderArray objects associated with each token in the
113444 ** expression pExpr. In other words, this function frees the resources
113445 ** allocated by fts3ExprAllocateSegReaders().
113446 */
113447 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
113448   if( pExpr ){
113449     Fts3Phrase *pPhrase = pExpr->pPhrase;
113450     if( pPhrase ){
113451       int kk;
113452       for(kk=0; kk<pPhrase->nToken; kk++){
113453         fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
113454         pPhrase->aToken[kk].pSegcsr = 0;
113455       }
113456     }
113457     fts3ExprFreeSegReaders(pExpr->pLeft);
113458     fts3ExprFreeSegReaders(pExpr->pRight);
113459   }
113460 }
113461
113462 /*
113463 ** Return the sum of the costs of all tokens in the expression pExpr. This
113464 ** function must be called after Fts3SegReaderArrays have been allocated
113465 ** for all tokens using fts3ExprAllocateSegReaders().
113466 */
113467 static int fts3ExprCost(Fts3Expr *pExpr){
113468   int nCost;                      /* Return value */
113469   if( pExpr->eType==FTSQUERY_PHRASE ){
113470     Fts3Phrase *pPhrase = pExpr->pPhrase;
113471     int ii;
113472     nCost = 0;
113473     for(ii=0; ii<pPhrase->nToken; ii++){
113474       Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
113475       if( pSegcsr ) nCost += pSegcsr->nCost;
113476     }
113477   }else{
113478     nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
113479   }
113480   return nCost;
113481 }
113482
113483 /*
113484 ** The following is a helper function (and type) for fts3EvalExpr(). It
113485 ** must be called after Fts3SegReaders have been allocated for every token
113486 ** in the expression. See the context it is called from in fts3EvalExpr()
113487 ** for further explanation.
113488 */
113489 typedef struct ExprAndCost ExprAndCost;
113490 struct ExprAndCost {
113491   Fts3Expr *pExpr;
113492   int nCost;
113493 };
113494 static void fts3ExprAssignCosts(
113495   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
113496   ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
113497 ){
113498   if( pExpr->eType==FTSQUERY_AND ){
113499     fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
113500     fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
113501   }else{
113502     (*ppExprCost)->pExpr = pExpr;
113503     (*ppExprCost)->nCost = fts3ExprCost(pExpr);
113504     (*ppExprCost)++;
113505   }
113506 }
113507
113508 /*
113509 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
113510 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
113511 ** the space needed to store the output. The caller is responsible for
113512 ** freeing the space when it has finished.
113513 **
113514 ** This function is called in two distinct contexts:
113515 **
113516 **   * From within the virtual table xFilter() method. In this case, the
113517 **     output doclist contains entries for all rows in the table, based on
113518 **     data read from the full-text index.
113519 **
113520 **     In this case, if the query expression contains one or more tokens that 
113521 **     are very common, then the returned doclist may contain a superset of 
113522 **     the documents that actually match the expression.
113523 **
113524 **   * From within the virtual table xNext() method. This call is only made
113525 **     if the call from within xFilter() found that there were very common 
113526 **     tokens in the query expression and did return a superset of the 
113527 **     matching documents. In this case the returned doclist contains only
113528 **     entries that correspond to the current row of the table. Instead of
113529 **     reading the data for each token from the full-text index, the data is
113530 **     already available in-memory in the Fts3PhraseToken.pDeferred structures.
113531 **     See fts3EvalDeferred() for how it gets there.
113532 **
113533 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
113534 ** required) Fts3Cursor.doDeferred==1.
113535 **
113536 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
113537 ** as part of a SELECT on an FTS3 table, this function is called on each
113538 ** individual phrase expression in the query. If there were very common tokens
113539 ** found in the xFilter() call, then this function is called once for phrase
113540 ** for each row visited, and the returned doclist contains entries for the
113541 ** current row only. Otherwise, if there were no very common tokens, then this
113542 ** function is called once only for each phrase in the query and the returned
113543 ** doclist contains entries for all rows of the table.
113544 **
113545 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
113546 ** result of a snippet(), offsets() or matchinfo() invocation.
113547 */
113548 static int fts3EvalExpr(
113549   Fts3Cursor *p,                  /* Virtual table cursor handle */
113550   Fts3Expr *pExpr,                /* Parsed fts3 expression */
113551   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
113552   int *pnOut,                     /* OUT: Size of buffer at *paOut */
113553   int isReqPos                    /* Require positions in output buffer */
113554 ){
113555   int rc = SQLITE_OK;             /* Return code */
113556
113557   /* Zero the output parameters. */
113558   *paOut = 0;
113559   *pnOut = 0;
113560
113561   if( pExpr ){
113562     assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR     
113563          || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
113564          || pExpr->eType==FTSQUERY_PHRASE
113565     );
113566     assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
113567
113568     if( pExpr->eType==FTSQUERY_PHRASE ){
113569       rc = fts3PhraseSelect(p, pExpr->pPhrase,
113570           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
113571           paOut, pnOut
113572       );
113573       fts3ExprFreeSegReaders(pExpr);
113574     }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
113575       ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
113576       int nExpr = 0;              /* Size of aExpr[] */
113577       char *aRet = 0;             /* Doclist to return to caller */
113578       int nRet = 0;               /* Length of aRet[] in bytes */
113579       int nDoc = 0x7FFFFFFF;
113580
113581       assert( !isReqPos );
113582
113583       rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
113584       if( rc==SQLITE_OK ){
113585         assert( nExpr>1 );
113586         aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
113587         if( !aExpr ) rc = SQLITE_NOMEM;
113588       }
113589       if( rc==SQLITE_OK ){
113590         int ii;                   /* Used to iterate through expressions */
113591
113592         fts3ExprAssignCosts(pExpr, &aExpr);
113593         aExpr -= nExpr;
113594         for(ii=0; ii<nExpr; ii++){
113595           char *aNew;
113596           int nNew;
113597           int jj;
113598           ExprAndCost *pBest = 0;
113599   
113600           for(jj=0; jj<nExpr; jj++){
113601             ExprAndCost *pCand = &aExpr[jj];
113602             if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
113603               pBest = pCand;
113604             }
113605           }
113606   
113607           if( pBest->nCost>nDoc ){
113608             rc = fts3DeferExpression(p, p->pExpr);
113609             break;
113610           }else{
113611             rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
113612             if( rc!=SQLITE_OK ) break;
113613             pBest->pExpr = 0;
113614             if( ii==0 ){
113615               aRet = aNew;
113616               nRet = nNew;
113617               nDoc = fts3DoclistCountDocids(0, aRet, nRet);
113618             }else{
113619               fts3DoclistMerge(
113620                   MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
113621               );
113622               sqlite3_free(aNew);
113623             }
113624           }
113625         }
113626       }
113627
113628       if( rc==SQLITE_OK ){
113629         *paOut = aRet;
113630         *pnOut = nRet;
113631       }else{
113632         assert( *paOut==0 );
113633         sqlite3_free(aRet);
113634       }
113635       sqlite3_free(aExpr);
113636       fts3ExprFreeSegReaders(pExpr);
113637
113638     }else{
113639       char *aLeft;
113640       char *aRight;
113641       int nLeft;
113642       int nRight;
113643
113644       assert( pExpr->eType==FTSQUERY_NEAR 
113645            || pExpr->eType==FTSQUERY_OR
113646            || pExpr->eType==FTSQUERY_NOT
113647            || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
113648       );
113649
113650       if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
113651        && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
113652       ){
113653         switch( pExpr->eType ){
113654           case FTSQUERY_NEAR: {
113655             Fts3Expr *pLeft;
113656             Fts3Expr *pRight;
113657             int mergetype = MERGE_NEAR;
113658             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
113659               mergetype = MERGE_POS_NEAR;
113660             }
113661             pLeft = pExpr->pLeft;
113662             while( pLeft->eType==FTSQUERY_NEAR ){ 
113663               pLeft=pLeft->pRight;
113664             }
113665             pRight = pExpr->pRight;
113666             assert( pRight->eType==FTSQUERY_PHRASE );
113667             assert( pLeft->eType==FTSQUERY_PHRASE );
113668
113669             rc = fts3NearMerge(mergetype, pExpr->nNear, 
113670                 pLeft->pPhrase->nToken, aLeft, nLeft,
113671                 pRight->pPhrase->nToken, aRight, nRight,
113672                 paOut, pnOut
113673             );
113674             sqlite3_free(aLeft);
113675             break;
113676           }
113677
113678           case FTSQUERY_OR: {
113679             /* Allocate a buffer for the output. The maximum size is the
113680             ** sum of the sizes of the two input buffers. The +1 term is
113681             ** so that a buffer of zero bytes is never allocated - this can
113682             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
113683             */
113684             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
113685             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
113686                 aLeft, nLeft, aRight, nRight, 0
113687             );
113688             *paOut = aBuffer;
113689             sqlite3_free(aLeft);
113690             break;
113691           }
113692
113693           default: {
113694             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
113695             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
113696                 aLeft, nLeft, aRight, nRight, 0
113697             );
113698             *paOut = aLeft;
113699             break;
113700           }
113701         }
113702       }
113703       sqlite3_free(aRight);
113704     }
113705   }
113706
113707   assert( rc==SQLITE_OK || *paOut==0 );
113708   return rc;
113709 }
113710
113711 /*
113712 ** This function is called from within xNext() for each row visited by
113713 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
113714 ** was able to determine the exact set of matching rows, this function sets
113715 ** *pbRes to true and returns SQLITE_IO immediately.
113716 **
113717 ** Otherwise, if evaluating the query expression within xFilter() returned a
113718 ** superset of the matching documents instead of an exact set (this happens
113719 ** when the query includes very common tokens and it is deemed too expensive to
113720 ** load their doclists from disk), this function tests if the current row
113721 ** really does match the FTS3 query.
113722 **
113723 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
113724 ** is returned and *pbRes is set to true if the current row matches the
113725 ** FTS3 query (and should be included in the results returned to SQLite), or
113726 ** false otherwise.
113727 */
113728 static int fts3EvalDeferred(
113729   Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
113730   int *pbRes                      /* OUT: Set to true if row is a match */
113731 ){
113732   int rc = SQLITE_OK;
113733   if( pCsr->pDeferred==0 ){
113734     *pbRes = 1;
113735   }else{
113736     rc = fts3CursorSeek(0, pCsr);
113737     if( rc==SQLITE_OK ){
113738       sqlite3Fts3FreeDeferredDoclists(pCsr);
113739       rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
113740     }
113741     if( rc==SQLITE_OK ){
113742       char *a = 0;
113743       int n = 0;
113744       rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
113745       assert( n>=0 );
113746       *pbRes = (n>0);
113747       sqlite3_free(a);
113748     }
113749   }
113750   return rc;
113751 }
113752
113753 /*
113754 ** Advance the cursor to the next row in the %_content table that
113755 ** matches the search criteria.  For a MATCH search, this will be
113756 ** the next row that matches. For a full-table scan, this will be
113757 ** simply the next row in the %_content table.  For a docid lookup,
113758 ** this routine simply sets the EOF flag.
113759 **
113760 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
113761 ** even if we reach end-of-file.  The fts3EofMethod() will be called
113762 ** subsequently to determine whether or not an EOF was hit.
113763 */
113764 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
113765   int res;
113766   int rc = SQLITE_OK;             /* Return code */
113767   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
113768
113769   pCsr->eEvalmode = FTS3_EVAL_NEXT;
113770   do {
113771     if( pCsr->aDoclist==0 ){
113772       if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
113773         pCsr->isEof = 1;
113774         rc = sqlite3_reset(pCsr->pStmt);
113775         break;
113776       }
113777       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
113778     }else{
113779       if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
113780         pCsr->isEof = 1;
113781         break;
113782       }
113783       sqlite3_reset(pCsr->pStmt);
113784       fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
113785       pCsr->isRequireSeek = 1;
113786       pCsr->isMatchinfoNeeded = 1;
113787     }
113788   }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
113789
113790   return rc;
113791 }
113792
113793 /*
113794 ** This is the xFilter interface for the virtual table.  See
113795 ** the virtual table xFilter method documentation for additional
113796 ** information.
113797 **
113798 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
113799 ** the %_content table.
113800 **
113801 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
113802 ** in the %_content table.
113803 **
113804 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
113805 ** column on the left-hand side of the MATCH operator is column
113806 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
113807 ** side of the MATCH operator.
113808 */
113809 static int fts3FilterMethod(
113810   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
113811   int idxNum,                     /* Strategy index */
113812   const char *idxStr,             /* Unused */
113813   int nVal,                       /* Number of elements in apVal */
113814   sqlite3_value **apVal           /* Arguments for the indexing scheme */
113815 ){
113816   const char *azSql[] = {
113817     "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
113818     "SELECT %s FROM %Q.'%q_content' AS x ",                /* full-scan */
113819   };
113820   int rc;                         /* Return code */
113821   char *zSql;                     /* SQL statement used to access %_content */
113822   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
113823   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
113824
113825   UNUSED_PARAMETER(idxStr);
113826   UNUSED_PARAMETER(nVal);
113827
113828   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
113829   assert( nVal==0 || nVal==1 );
113830   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
113831   assert( p->pSegments==0 );
113832
113833   /* In case the cursor has been used before, clear it now. */
113834   sqlite3_finalize(pCsr->pStmt);
113835   sqlite3_free(pCsr->aDoclist);
113836   sqlite3Fts3ExprFree(pCsr->pExpr);
113837   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
113838
113839   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
113840     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
113841     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
113842
113843     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
113844       return SQLITE_NOMEM;
113845     }
113846
113847     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
113848         iCol, zQuery, -1, &pCsr->pExpr
113849     );
113850     if( rc!=SQLITE_OK ){
113851       if( rc==SQLITE_ERROR ){
113852         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
113853                                           zQuery);
113854       }
113855       return rc;
113856     }
113857
113858     rc = sqlite3Fts3ReadLock(p);
113859     if( rc!=SQLITE_OK ) return rc;
113860
113861     rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
113862     sqlite3Fts3SegmentsClose(p);
113863     if( rc!=SQLITE_OK ) return rc;
113864     pCsr->pNextId = pCsr->aDoclist;
113865     pCsr->iPrevId = 0;
113866   }
113867
113868   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
113869   ** statement loops through all rows of the %_content table. For a
113870   ** full-text query or docid lookup, the statement retrieves a single
113871   ** row by docid.
113872   */
113873   zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
113874   zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
113875   if( !zSql ){
113876     rc = SQLITE_NOMEM;
113877   }else{
113878     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
113879     sqlite3_free(zSql);
113880   }
113881   if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
113882     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
113883   }
113884   pCsr->eSearch = (i16)idxNum;
113885
113886   if( rc!=SQLITE_OK ) return rc;
113887   return fts3NextMethod(pCursor);
113888 }
113889
113890 /* 
113891 ** This is the xEof method of the virtual table. SQLite calls this 
113892 ** routine to find out if it has reached the end of a result set.
113893 */
113894 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
113895   return ((Fts3Cursor *)pCursor)->isEof;
113896 }
113897
113898 /* 
113899 ** This is the xRowid method. The SQLite core calls this routine to
113900 ** retrieve the rowid for the current row of the result set. fts3
113901 ** exposes %_content.docid as the rowid for the virtual table. The
113902 ** rowid should be written to *pRowid.
113903 */
113904 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
113905   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
113906   if( pCsr->aDoclist ){
113907     *pRowid = pCsr->iPrevId;
113908   }else{
113909     /* This branch runs if the query is implemented using a full-table scan
113910     ** (not using the full-text index). In this case grab the rowid from the
113911     ** SELECT statement.
113912     */
113913     assert( pCsr->isRequireSeek==0 );
113914     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
113915   }
113916   return SQLITE_OK;
113917 }
113918
113919 /* 
113920 ** This is the xColumn method, called by SQLite to request a value from
113921 ** the row that the supplied cursor currently points to.
113922 */
113923 static int fts3ColumnMethod(
113924   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
113925   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
113926   int iCol                        /* Index of column to read value from */
113927 ){
113928   int rc;                         /* Return Code */
113929   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
113930   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
113931
113932   /* The column value supplied by SQLite must be in range. */
113933   assert( iCol>=0 && iCol<=p->nColumn+1 );
113934
113935   if( iCol==p->nColumn+1 ){
113936     /* This call is a request for the "docid" column. Since "docid" is an 
113937     ** alias for "rowid", use the xRowid() method to obtain the value.
113938     */
113939     sqlite3_int64 iRowid;
113940     rc = fts3RowidMethod(pCursor, &iRowid);
113941     sqlite3_result_int64(pContext, iRowid);
113942   }else if( iCol==p->nColumn ){
113943     /* The extra column whose name is the same as the table.
113944     ** Return a blob which is a pointer to the cursor.
113945     */
113946     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
113947     rc = SQLITE_OK;
113948   }else{
113949     rc = fts3CursorSeek(0, pCsr);
113950     if( rc==SQLITE_OK ){
113951       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
113952     }
113953   }
113954   return rc;
113955 }
113956
113957 /* 
113958 ** This function is the implementation of the xUpdate callback used by 
113959 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
113960 ** inserted, updated or deleted.
113961 */
113962 static int fts3UpdateMethod(
113963   sqlite3_vtab *pVtab,            /* Virtual table handle */
113964   int nArg,                       /* Size of argument array */
113965   sqlite3_value **apVal,          /* Array of arguments */
113966   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
113967 ){
113968   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
113969 }
113970
113971 /*
113972 ** Implementation of xSync() method. Flush the contents of the pending-terms
113973 ** hash-table to the database.
113974 */
113975 static int fts3SyncMethod(sqlite3_vtab *pVtab){
113976   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
113977   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
113978   return rc;
113979 }
113980
113981 /*
113982 ** Implementation of xBegin() method. This is a no-op.
113983 */
113984 static int fts3BeginMethod(sqlite3_vtab *pVtab){
113985   UNUSED_PARAMETER(pVtab);
113986   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
113987   return SQLITE_OK;
113988 }
113989
113990 /*
113991 ** Implementation of xCommit() method. This is a no-op. The contents of
113992 ** the pending-terms hash-table have already been flushed into the database
113993 ** by fts3SyncMethod().
113994 */
113995 static int fts3CommitMethod(sqlite3_vtab *pVtab){
113996   UNUSED_PARAMETER(pVtab);
113997   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
113998   return SQLITE_OK;
113999 }
114000
114001 /*
114002 ** Implementation of xRollback(). Discard the contents of the pending-terms
114003 ** hash-table. Any changes made to the database are reverted by SQLite.
114004 */
114005 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
114006   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
114007   return SQLITE_OK;
114008 }
114009
114010 /*
114011 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
114012 ** The loaded doclist contains positions as well as the document ids.
114013 ** This is used by the matchinfo(), snippet() and offsets() auxillary
114014 ** functions.
114015 */
114016 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
114017   int rc;
114018   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114019   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114020   rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
114021   return rc;
114022 }
114023
114024 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
114025   Fts3Cursor *pCsr, 
114026   Fts3Expr *pExpr,
114027   char **paDoclist,
114028   int *pnDoclist
114029 ){
114030   int rc;
114031   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
114032   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
114033   pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
114034   rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
114035   pCsr->eEvalmode = FTS3_EVAL_NEXT;
114036   return rc;
114037 }
114038
114039 /*
114040 ** After ExprLoadDoclist() (see above) has been called, this function is
114041 ** used to iterate/search through the position lists that make up the doclist
114042 ** stored in pExpr->aDoclist.
114043 */
114044 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
114045   Fts3Expr *pExpr,                /* Access this expressions doclist */
114046   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
114047   int iCol                        /* Column of requested pos-list */
114048 ){
114049   assert( pExpr->isLoaded );
114050   if( pExpr->aDoclist ){
114051     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114052     char *pCsr;
114053
114054     if( pExpr->pCurrent==0 ){
114055       pExpr->pCurrent = pExpr->aDoclist;
114056       pExpr->iCurrent = 0;
114057       pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
114058     }
114059     pCsr = pExpr->pCurrent;
114060     assert( pCsr );
114061
114062     while( pCsr<pEnd ){
114063       if( pExpr->iCurrent<iDocid ){
114064         fts3PoslistCopy(0, &pCsr);
114065         if( pCsr<pEnd ){
114066           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
114067         }
114068         pExpr->pCurrent = pCsr;
114069       }else{
114070         if( pExpr->iCurrent==iDocid ){
114071           int iThis = 0;
114072           if( iCol<0 ){
114073             /* If iCol is negative, return a pointer to the start of the
114074             ** position-list (instead of a pointer to the start of a list
114075             ** of offsets associated with a specific column).
114076             */
114077             return pCsr;
114078           }
114079           while( iThis<iCol ){
114080             fts3ColumnlistCopy(0, &pCsr);
114081             if( *pCsr==0x00 ) return 0;
114082             pCsr++;
114083             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
114084           }
114085           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
114086         }
114087         return 0;
114088       }
114089     }
114090   }
114091
114092   return 0;
114093 }
114094
114095 /*
114096 ** Helper function used by the implementation of the overloaded snippet(),
114097 ** offsets() and optimize() SQL functions.
114098 **
114099 ** If the value passed as the third argument is a blob of size
114100 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
114101 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
114102 ** message is written to context pContext and SQLITE_ERROR returned. The
114103 ** string passed via zFunc is used as part of the error message.
114104 */
114105 static int fts3FunctionArg(
114106   sqlite3_context *pContext,      /* SQL function call context */
114107   const char *zFunc,              /* Function name */
114108   sqlite3_value *pVal,            /* argv[0] passed to function */
114109   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
114110 ){
114111   Fts3Cursor *pRet;
114112   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
114113    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
114114   ){
114115     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
114116     sqlite3_result_error(pContext, zErr, -1);
114117     sqlite3_free(zErr);
114118     return SQLITE_ERROR;
114119   }
114120   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
114121   *ppCsr = pRet;
114122   return SQLITE_OK;
114123 }
114124
114125 /*
114126 ** Implementation of the snippet() function for FTS3
114127 */
114128 static void fts3SnippetFunc(
114129   sqlite3_context *pContext,      /* SQLite function call context */
114130   int nVal,                       /* Size of apVal[] array */
114131   sqlite3_value **apVal           /* Array of arguments */
114132 ){
114133   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114134   const char *zStart = "<b>";
114135   const char *zEnd = "</b>";
114136   const char *zEllipsis = "<b>...</b>";
114137   int iCol = -1;
114138   int nToken = 15;                /* Default number of tokens in snippet */
114139
114140   /* There must be at least one argument passed to this function (otherwise
114141   ** the non-overloaded version would have been called instead of this one).
114142   */
114143   assert( nVal>=1 );
114144
114145   if( nVal>6 ){
114146     sqlite3_result_error(pContext, 
114147         "wrong number of arguments to function snippet()", -1);
114148     return;
114149   }
114150   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
114151
114152   switch( nVal ){
114153     case 6: nToken = sqlite3_value_int(apVal[5]);
114154     case 5: iCol = sqlite3_value_int(apVal[4]);
114155     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
114156     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
114157     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
114158   }
114159   if( !zEllipsis || !zEnd || !zStart ){
114160     sqlite3_result_error_nomem(pContext);
114161   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114162     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
114163   }
114164 }
114165
114166 /*
114167 ** Implementation of the offsets() function for FTS3
114168 */
114169 static void fts3OffsetsFunc(
114170   sqlite3_context *pContext,      /* SQLite function call context */
114171   int nVal,                       /* Size of argument array */
114172   sqlite3_value **apVal           /* Array of arguments */
114173 ){
114174   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114175
114176   UNUSED_PARAMETER(nVal);
114177
114178   assert( nVal==1 );
114179   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
114180   assert( pCsr );
114181   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114182     sqlite3Fts3Offsets(pContext, pCsr);
114183   }
114184 }
114185
114186 /* 
114187 ** Implementation of the special optimize() function for FTS3. This 
114188 ** function merges all segments in the database to a single segment.
114189 ** Example usage is:
114190 **
114191 **   SELECT optimize(t) FROM t LIMIT 1;
114192 **
114193 ** where 't' is the name of an FTS3 table.
114194 */
114195 static void fts3OptimizeFunc(
114196   sqlite3_context *pContext,      /* SQLite function call context */
114197   int nVal,                       /* Size of argument array */
114198   sqlite3_value **apVal           /* Array of arguments */
114199 ){
114200   int rc;                         /* Return code */
114201   Fts3Table *p;                   /* Virtual table handle */
114202   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
114203
114204   UNUSED_PARAMETER(nVal);
114205
114206   assert( nVal==1 );
114207   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
114208   p = (Fts3Table *)pCursor->base.pVtab;
114209   assert( p );
114210
114211   rc = sqlite3Fts3Optimize(p);
114212
114213   switch( rc ){
114214     case SQLITE_OK:
114215       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
114216       break;
114217     case SQLITE_DONE:
114218       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
114219       break;
114220     default:
114221       sqlite3_result_error_code(pContext, rc);
114222       break;
114223   }
114224 }
114225
114226 /*
114227 ** Implementation of the matchinfo() function for FTS3
114228 */
114229 static void fts3MatchinfoFunc(
114230   sqlite3_context *pContext,      /* SQLite function call context */
114231   int nVal,                       /* Size of argument array */
114232   sqlite3_value **apVal           /* Array of arguments */
114233 ){
114234   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114235   assert( nVal==1 || nVal==2 );
114236   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
114237     const char *zArg = 0;
114238     if( nVal>1 ){
114239       zArg = (const char *)sqlite3_value_text(apVal[1]);
114240     }
114241     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
114242   }
114243 }
114244
114245 /*
114246 ** This routine implements the xFindFunction method for the FTS3
114247 ** virtual table.
114248 */
114249 static int fts3FindFunctionMethod(
114250   sqlite3_vtab *pVtab,            /* Virtual table handle */
114251   int nArg,                       /* Number of SQL function arguments */
114252   const char *zName,              /* Name of SQL function */
114253   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
114254   void **ppArg                    /* Unused */
114255 ){
114256   struct Overloaded {
114257     const char *zName;
114258     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
114259   } aOverload[] = {
114260     { "snippet", fts3SnippetFunc },
114261     { "offsets", fts3OffsetsFunc },
114262     { "optimize", fts3OptimizeFunc },
114263     { "matchinfo", fts3MatchinfoFunc },
114264   };
114265   int i;                          /* Iterator variable */
114266
114267   UNUSED_PARAMETER(pVtab);
114268   UNUSED_PARAMETER(nArg);
114269   UNUSED_PARAMETER(ppArg);
114270
114271   for(i=0; i<SizeofArray(aOverload); i++){
114272     if( strcmp(zName, aOverload[i].zName)==0 ){
114273       *pxFunc = aOverload[i].xFunc;
114274       return 1;
114275     }
114276   }
114277
114278   /* No function of the specified name was found. Return 0. */
114279   return 0;
114280 }
114281
114282 /*
114283 ** Implementation of FTS3 xRename method. Rename an fts3 table.
114284 */
114285 static int fts3RenameMethod(
114286   sqlite3_vtab *pVtab,            /* Virtual table handle */
114287   const char *zName               /* New name of table */
114288 ){
114289   Fts3Table *p = (Fts3Table *)pVtab;
114290   sqlite3 *db = p->db;            /* Database connection */
114291   int rc;                         /* Return Code */
114292
114293   rc = sqlite3Fts3PendingTermsFlush(p);
114294   if( rc!=SQLITE_OK ){
114295     return rc;
114296   }
114297
114298   fts3DbExec(&rc, db,
114299     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
114300     p->zDb, p->zName, zName
114301   );
114302   if( p->bHasDocsize ){
114303     fts3DbExec(&rc, db,
114304       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
114305       p->zDb, p->zName, zName
114306     );
114307   }
114308   if( p->bHasStat ){
114309     fts3DbExec(&rc, db,
114310       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
114311       p->zDb, p->zName, zName
114312     );
114313   }
114314   fts3DbExec(&rc, db,
114315     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
114316     p->zDb, p->zName, zName
114317   );
114318   fts3DbExec(&rc, db,
114319     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
114320     p->zDb, p->zName, zName
114321   );
114322   return rc;
114323 }
114324
114325 static const sqlite3_module fts3Module = {
114326   /* iVersion      */ 0,
114327   /* xCreate       */ fts3CreateMethod,
114328   /* xConnect      */ fts3ConnectMethod,
114329   /* xBestIndex    */ fts3BestIndexMethod,
114330   /* xDisconnect   */ fts3DisconnectMethod,
114331   /* xDestroy      */ fts3DestroyMethod,
114332   /* xOpen         */ fts3OpenMethod,
114333   /* xClose        */ fts3CloseMethod,
114334   /* xFilter       */ fts3FilterMethod,
114335   /* xNext         */ fts3NextMethod,
114336   /* xEof          */ fts3EofMethod,
114337   /* xColumn       */ fts3ColumnMethod,
114338   /* xRowid        */ fts3RowidMethod,
114339   /* xUpdate       */ fts3UpdateMethod,
114340   /* xBegin        */ fts3BeginMethod,
114341   /* xSync         */ fts3SyncMethod,
114342   /* xCommit       */ fts3CommitMethod,
114343   /* xRollback     */ fts3RollbackMethod,
114344   /* xFindFunction */ fts3FindFunctionMethod,
114345   /* xRename */       fts3RenameMethod,
114346 };
114347
114348 /*
114349 ** This function is registered as the module destructor (called when an
114350 ** FTS3 enabled database connection is closed). It frees the memory
114351 ** allocated for the tokenizer hash table.
114352 */
114353 static void hashDestroy(void *p){
114354   Fts3Hash *pHash = (Fts3Hash *)p;
114355   sqlite3Fts3HashClear(pHash);
114356   sqlite3_free(pHash);
114357 }
114358
114359 /*
114360 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
114361 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
114362 ** respectively. The following three forward declarations are for functions
114363 ** declared in these files used to retrieve the respective implementations.
114364 **
114365 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
114366 ** to by the argument to point to the "simple" tokenizer implementation.
114367 ** And so on.
114368 */
114369 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114370 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114371 #ifdef SQLITE_ENABLE_ICU
114372 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114373 #endif
114374
114375 /*
114376 ** Initialise the fts3 extension. If this extension is built as part
114377 ** of the sqlite library, then this function is called directly by
114378 ** SQLite. If fts3 is built as a dynamically loadable extension, this
114379 ** function is called by the sqlite3_extension_init() entry point.
114380 */
114381 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
114382   int rc = SQLITE_OK;
114383   Fts3Hash *pHash = 0;
114384   const sqlite3_tokenizer_module *pSimple = 0;
114385   const sqlite3_tokenizer_module *pPorter = 0;
114386
114387 #ifdef SQLITE_ENABLE_ICU
114388   const sqlite3_tokenizer_module *pIcu = 0;
114389   sqlite3Fts3IcuTokenizerModule(&pIcu);
114390 #endif
114391
114392   rc = sqlite3Fts3InitAux(db);
114393   if( rc!=SQLITE_OK ) return rc;
114394
114395   sqlite3Fts3SimpleTokenizerModule(&pSimple);
114396   sqlite3Fts3PorterTokenizerModule(&pPorter);
114397
114398   /* Allocate and initialise the hash-table used to store tokenizers. */
114399   pHash = sqlite3_malloc(sizeof(Fts3Hash));
114400   if( !pHash ){
114401     rc = SQLITE_NOMEM;
114402   }else{
114403     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
114404   }
114405
114406   /* Load the built-in tokenizers into the hash table */
114407   if( rc==SQLITE_OK ){
114408     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
114409      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
114410 #ifdef SQLITE_ENABLE_ICU
114411      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
114412 #endif
114413     ){
114414       rc = SQLITE_NOMEM;
114415     }
114416   }
114417
114418 #ifdef SQLITE_TEST
114419   if( rc==SQLITE_OK ){
114420     rc = sqlite3Fts3ExprInitTestInterface(db);
114421   }
114422 #endif
114423
114424   /* Create the virtual table wrapper around the hash-table and overload 
114425   ** the two scalar functions. If this is successful, register the
114426   ** module with sqlite.
114427   */
114428   if( SQLITE_OK==rc 
114429    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
114430    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
114431    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
114432    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
114433    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
114434    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
114435   ){
114436     rc = sqlite3_create_module_v2(
114437         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
114438     );
114439     if( rc==SQLITE_OK ){
114440       rc = sqlite3_create_module_v2(
114441           db, "fts4", &fts3Module, (void *)pHash, 0
114442       );
114443     }
114444     return rc;
114445   }
114446
114447   /* An error has occurred. Delete the hash table and return the error code. */
114448   assert( rc!=SQLITE_OK );
114449   if( pHash ){
114450     sqlite3Fts3HashClear(pHash);
114451     sqlite3_free(pHash);
114452   }
114453   return rc;
114454 }
114455
114456 #if !SQLITE_CORE
114457 SQLITE_API int sqlite3_extension_init(
114458   sqlite3 *db, 
114459   char **pzErrMsg,
114460   const sqlite3_api_routines *pApi
114461 ){
114462   SQLITE_EXTENSION_INIT2(pApi)
114463   return sqlite3Fts3Init(db);
114464 }
114465 #endif
114466
114467 #endif
114468
114469 /************** End of fts3.c ************************************************/
114470 /************** Begin file fts3_aux.c ****************************************/
114471 /*
114472 ** 2011 Jan 27
114473 **
114474 ** The author disclaims copyright to this source code.  In place of
114475 ** a legal notice, here is a blessing:
114476 **
114477 **    May you do good and not evil.
114478 **    May you find forgiveness for yourself and forgive others.
114479 **    May you share freely, never taking more than you give.
114480 **
114481 ******************************************************************************
114482 **
114483 */
114484
114485 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114486
114487
114488 typedef struct Fts3auxTable Fts3auxTable;
114489 typedef struct Fts3auxCursor Fts3auxCursor;
114490
114491 struct Fts3auxTable {
114492   sqlite3_vtab base;              /* Base class used by SQLite core */
114493   Fts3Table *pFts3Tab;
114494 };
114495
114496 struct Fts3auxCursor {
114497   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
114498   Fts3SegReaderCursor csr;        /* Must be right after "base" */
114499   Fts3SegFilter filter;
114500   char *zStop;
114501   int nStop;                      /* Byte-length of string zStop */
114502   int isEof;                      /* True if cursor is at EOF */
114503   sqlite3_int64 iRowid;           /* Current rowid */
114504
114505   int iCol;                       /* Current value of 'col' column */
114506   int nStat;                      /* Size of aStat[] array */
114507   struct Fts3auxColstats {
114508     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
114509     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
114510   } *aStat;
114511 };
114512
114513 /*
114514 ** Schema of the terms table.
114515 */
114516 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
114517
114518 /*
114519 ** This function does all the work for both the xConnect and xCreate methods.
114520 ** These tables have no persistent representation of their own, so xConnect
114521 ** and xCreate are identical operations.
114522 */
114523 static int fts3auxConnectMethod(
114524   sqlite3 *db,                    /* Database connection */
114525   void *pUnused,                  /* Unused */
114526   int argc,                       /* Number of elements in argv array */
114527   const char * const *argv,       /* xCreate/xConnect argument array */
114528   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
114529   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
114530 ){
114531   char const *zDb;                /* Name of database (e.g. "main") */
114532   char const *zFts3;              /* Name of fts3 table */
114533   int nDb;                        /* Result of strlen(zDb) */
114534   int nFts3;                      /* Result of strlen(zFts3) */
114535   int nByte;                      /* Bytes of space to allocate here */
114536   int rc;                         /* value returned by declare_vtab() */
114537   Fts3auxTable *p;                /* Virtual table object to return */
114538
114539   UNUSED_PARAMETER(pUnused);
114540
114541   /* The user should specify a single argument - the name of an fts3 table. */
114542   if( argc!=4 ){
114543     *pzErr = sqlite3_mprintf(
114544         "wrong number of arguments to fts4aux constructor"
114545     );
114546     return SQLITE_ERROR;
114547   }
114548
114549   zDb = argv[1]; 
114550   nDb = strlen(zDb);
114551   zFts3 = argv[3];
114552   nFts3 = strlen(zFts3);
114553
114554   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
114555   if( rc!=SQLITE_OK ) return rc;
114556
114557   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
114558   p = (Fts3auxTable *)sqlite3_malloc(nByte);
114559   if( !p ) return SQLITE_NOMEM;
114560   memset(p, 0, nByte);
114561
114562   p->pFts3Tab = (Fts3Table *)&p[1];
114563   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
114564   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
114565   p->pFts3Tab->db = db;
114566
114567   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
114568   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
114569   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
114570
114571   *ppVtab = (sqlite3_vtab *)p;
114572   return SQLITE_OK;
114573 }
114574
114575 /*
114576 ** This function does the work for both the xDisconnect and xDestroy methods.
114577 ** These tables have no persistent representation of their own, so xDisconnect
114578 ** and xDestroy are identical operations.
114579 */
114580 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
114581   Fts3auxTable *p = (Fts3auxTable *)pVtab;
114582   Fts3Table *pFts3 = p->pFts3Tab;
114583   int i;
114584
114585   /* Free any prepared statements held */
114586   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
114587     sqlite3_finalize(pFts3->aStmt[i]);
114588   }
114589   sqlite3_free(pFts3->zSegmentsTbl);
114590   sqlite3_free(p);
114591   return SQLITE_OK;
114592 }
114593
114594 #define FTS4AUX_EQ_CONSTRAINT 1
114595 #define FTS4AUX_GE_CONSTRAINT 2
114596 #define FTS4AUX_LE_CONSTRAINT 4
114597
114598 /*
114599 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
114600 */
114601 static int fts3auxBestIndexMethod(
114602   sqlite3_vtab *pVTab, 
114603   sqlite3_index_info *pInfo
114604 ){
114605   int i;
114606   int iEq = -1;
114607   int iGe = -1;
114608   int iLe = -1;
114609
114610   UNUSED_PARAMETER(pVTab);
114611
114612   /* This vtab delivers always results in "ORDER BY term ASC" order. */
114613   if( pInfo->nOrderBy==1 
114614    && pInfo->aOrderBy[0].iColumn==0 
114615    && pInfo->aOrderBy[0].desc==0
114616   ){
114617     pInfo->orderByConsumed = 1;
114618   }
114619
114620   /* Search for equality and range constraints on the "term" column. */
114621   for(i=0; i<pInfo->nConstraint; i++){
114622     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
114623       int op = pInfo->aConstraint[i].op;
114624       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
114625       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
114626       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
114627       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
114628       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
114629     }
114630   }
114631
114632   if( iEq>=0 ){
114633     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
114634     pInfo->aConstraintUsage[iEq].argvIndex = 1;
114635     pInfo->estimatedCost = 5;
114636   }else{
114637     pInfo->idxNum = 0;
114638     pInfo->estimatedCost = 20000;
114639     if( iGe>=0 ){
114640       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
114641       pInfo->aConstraintUsage[iGe].argvIndex = 1;
114642       pInfo->estimatedCost /= 2;
114643     }
114644     if( iLe>=0 ){
114645       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
114646       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
114647       pInfo->estimatedCost /= 2;
114648     }
114649   }
114650
114651   return SQLITE_OK;
114652 }
114653
114654 /*
114655 ** xOpen - Open a cursor.
114656 */
114657 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
114658   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
114659
114660   UNUSED_PARAMETER(pVTab);
114661
114662   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
114663   if( !pCsr ) return SQLITE_NOMEM;
114664   memset(pCsr, 0, sizeof(Fts3auxCursor));
114665
114666   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
114667   return SQLITE_OK;
114668 }
114669
114670 /*
114671 ** xClose - Close a cursor.
114672 */
114673 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
114674   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114675   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114676
114677   sqlite3Fts3SegmentsClose(pFts3);
114678   sqlite3Fts3SegReaderFinish(&pCsr->csr);
114679   sqlite3_free((void *)pCsr->filter.zTerm);
114680   sqlite3_free(pCsr->zStop);
114681   sqlite3_free(pCsr->aStat);
114682   sqlite3_free(pCsr);
114683   return SQLITE_OK;
114684 }
114685
114686 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
114687   if( nSize>pCsr->nStat ){
114688     struct Fts3auxColstats *aNew;
114689     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
114690         sizeof(struct Fts3auxColstats) * nSize
114691     );
114692     if( aNew==0 ) return SQLITE_NOMEM;
114693     memset(&aNew[pCsr->nStat], 0, 
114694         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
114695     );
114696     pCsr->aStat = aNew;
114697     pCsr->nStat = nSize;
114698   }
114699   return SQLITE_OK;
114700 }
114701
114702 /*
114703 ** xNext - Advance the cursor to the next row, if any.
114704 */
114705 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
114706   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114707   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114708   int rc;
114709
114710   /* Increment our pretend rowid value. */
114711   pCsr->iRowid++;
114712
114713   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
114714     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
114715   }
114716
114717   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
114718   if( rc==SQLITE_ROW ){
114719     int i = 0;
114720     int nDoclist = pCsr->csr.nDoclist;
114721     char *aDoclist = pCsr->csr.aDoclist;
114722     int iCol;
114723
114724     int eState = 0;
114725
114726     if( pCsr->zStop ){
114727       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
114728       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
114729       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
114730         pCsr->isEof = 1;
114731         return SQLITE_OK;
114732       }
114733     }
114734
114735     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
114736     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
114737     iCol = 0;
114738
114739     while( i<nDoclist ){
114740       sqlite3_int64 v = 0;
114741
114742       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
114743       switch( eState ){
114744         /* State 0. In this state the integer just read was a docid. */
114745         case 0:
114746           pCsr->aStat[0].nDoc++;
114747           eState = 1;
114748           iCol = 0;
114749           break;
114750
114751         /* State 1. In this state we are expecting either a 1, indicating
114752         ** that the following integer will be a column number, or the
114753         ** start of a position list for column 0.  
114754         ** 
114755         ** The only difference between state 1 and state 2 is that if the
114756         ** integer encountered in state 1 is not 0 or 1, then we need to
114757         ** increment the column 0 "nDoc" count for this term.
114758         */
114759         case 1:
114760           assert( iCol==0 );
114761           if( v>1 ){
114762             pCsr->aStat[1].nDoc++;
114763           }
114764           eState = 2;
114765           /* fall through */
114766
114767         case 2:
114768           if( v==0 ){       /* 0x00. Next integer will be a docid. */
114769             eState = 0;
114770           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
114771             eState = 3;
114772           }else{            /* 2 or greater. A position. */
114773             pCsr->aStat[iCol+1].nOcc++;
114774             pCsr->aStat[0].nOcc++;
114775           }
114776           break;
114777
114778         /* State 3. The integer just read is a column number. */
114779         default: assert( eState==3 );
114780           iCol = (int)v;
114781           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
114782           pCsr->aStat[iCol+1].nDoc++;
114783           eState = 2;
114784           break;
114785       }
114786     }
114787
114788     pCsr->iCol = 0;
114789     rc = SQLITE_OK;
114790   }else{
114791     pCsr->isEof = 1;
114792   }
114793   return rc;
114794 }
114795
114796 /*
114797 ** xFilter - Initialize a cursor to point at the start of its data.
114798 */
114799 static int fts3auxFilterMethod(
114800   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
114801   int idxNum,                     /* Strategy index */
114802   const char *idxStr,             /* Unused */
114803   int nVal,                       /* Number of elements in apVal */
114804   sqlite3_value **apVal           /* Arguments for the indexing scheme */
114805 ){
114806   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114807   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
114808   int rc;
114809   int isScan;
114810
114811   UNUSED_PARAMETER(nVal);
114812
114813   assert( idxStr==0 );
114814   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
114815        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
114816        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
114817   );
114818   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
114819
114820   /* In case this cursor is being reused, close and zero it. */
114821   testcase(pCsr->filter.zTerm);
114822   sqlite3Fts3SegReaderFinish(&pCsr->csr);
114823   sqlite3_free((void *)pCsr->filter.zTerm);
114824   sqlite3_free(pCsr->aStat);
114825   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
114826
114827   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
114828   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
114829
114830   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
114831     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
114832     if( zStr ){
114833       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
114834       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
114835       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
114836     }
114837   }
114838   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
114839     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
114840     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
114841     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
114842     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
114843   }
114844
114845   rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
114846       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
114847   );
114848   if( rc==SQLITE_OK ){
114849     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
114850   }
114851
114852   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
114853   return rc;
114854 }
114855
114856 /*
114857 ** xEof - Return true if the cursor is at EOF, or false otherwise.
114858 */
114859 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
114860   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114861   return pCsr->isEof;
114862 }
114863
114864 /*
114865 ** xColumn - Return a column value.
114866 */
114867 static int fts3auxColumnMethod(
114868   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
114869   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
114870   int iCol                        /* Index of column to read value from */
114871 ){
114872   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
114873
114874   assert( p->isEof==0 );
114875   if( iCol==0 ){        /* Column "term" */
114876     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
114877   }else if( iCol==1 ){  /* Column "col" */
114878     if( p->iCol ){
114879       sqlite3_result_int(pContext, p->iCol-1);
114880     }else{
114881       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
114882     }
114883   }else if( iCol==2 ){  /* Column "documents" */
114884     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
114885   }else{                /* Column "occurrences" */
114886     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
114887   }
114888
114889   return SQLITE_OK;
114890 }
114891
114892 /*
114893 ** xRowid - Return the current rowid for the cursor.
114894 */
114895 static int fts3auxRowidMethod(
114896   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
114897   sqlite_int64 *pRowid            /* OUT: Rowid value */
114898 ){
114899   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
114900   *pRowid = pCsr->iRowid;
114901   return SQLITE_OK;
114902 }
114903
114904 /*
114905 ** Register the fts3aux module with database connection db. Return SQLITE_OK
114906 ** if successful or an error code if sqlite3_create_module() fails.
114907 */
114908 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
114909   static const sqlite3_module fts3aux_module = {
114910      0,                           /* iVersion      */
114911      fts3auxConnectMethod,        /* xCreate       */
114912      fts3auxConnectMethod,        /* xConnect      */
114913      fts3auxBestIndexMethod,      /* xBestIndex    */
114914      fts3auxDisconnectMethod,     /* xDisconnect   */
114915      fts3auxDisconnectMethod,     /* xDestroy      */
114916      fts3auxOpenMethod,           /* xOpen         */
114917      fts3auxCloseMethod,          /* xClose        */
114918      fts3auxFilterMethod,         /* xFilter       */
114919      fts3auxNextMethod,           /* xNext         */
114920      fts3auxEofMethod,            /* xEof          */
114921      fts3auxColumnMethod,         /* xColumn       */
114922      fts3auxRowidMethod,          /* xRowid        */
114923      0,                           /* xUpdate       */
114924      0,                           /* xBegin        */
114925      0,                           /* xSync         */
114926      0,                           /* xCommit       */
114927      0,                           /* xRollback     */
114928      0,                           /* xFindFunction */
114929      0                            /* xRename       */
114930   };
114931   int rc;                         /* Return code */
114932
114933   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
114934   return rc;
114935 }
114936
114937 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114938
114939 /************** End of fts3_aux.c ********************************************/
114940 /************** Begin file fts3_expr.c ***************************************/
114941 /*
114942 ** 2008 Nov 28
114943 **
114944 ** The author disclaims copyright to this source code.  In place of
114945 ** a legal notice, here is a blessing:
114946 **
114947 **    May you do good and not evil.
114948 **    May you find forgiveness for yourself and forgive others.
114949 **    May you share freely, never taking more than you give.
114950 **
114951 ******************************************************************************
114952 **
114953 ** This module contains code that implements a parser for fts3 query strings
114954 ** (the right-hand argument to the MATCH operator). Because the supported 
114955 ** syntax is relatively simple, the whole tokenizer/parser system is
114956 ** hand-coded. 
114957 */
114958 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114959
114960 /*
114961 ** By default, this module parses the legacy syntax that has been 
114962 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
114963 ** is defined, then it uses the new syntax. The differences between
114964 ** the new and the old syntaxes are:
114965 **
114966 **  a) The new syntax supports parenthesis. The old does not.
114967 **
114968 **  b) The new syntax supports the AND and NOT operators. The old does not.
114969 **
114970 **  c) The old syntax supports the "-" token qualifier. This is not 
114971 **     supported by the new syntax (it is replaced by the NOT operator).
114972 **
114973 **  d) When using the old syntax, the OR operator has a greater precedence
114974 **     than an implicit AND. When using the new, both implicity and explicit
114975 **     AND operators have a higher precedence than OR.
114976 **
114977 ** If compiled with SQLITE_TEST defined, then this module exports the
114978 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
114979 ** to zero causes the module to use the old syntax. If it is set to 
114980 ** non-zero the new syntax is activated. This is so both syntaxes can
114981 ** be tested using a single build of testfixture.
114982 **
114983 ** The following describes the syntax supported by the fts3 MATCH
114984 ** operator in a similar format to that used by the lemon parser
114985 ** generator. This module does not use actually lemon, it uses a
114986 ** custom parser.
114987 **
114988 **   query ::= andexpr (OR andexpr)*.
114989 **
114990 **   andexpr ::= notexpr (AND? notexpr)*.
114991 **
114992 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
114993 **   notexpr ::= LP query RP.
114994 **
114995 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
114996 **
114997 **   distance_opt ::= .
114998 **   distance_opt ::= / INTEGER.
114999 **
115000 **   phrase ::= TOKEN.
115001 **   phrase ::= COLUMN:TOKEN.
115002 **   phrase ::= "TOKEN TOKEN TOKEN...".
115003 */
115004
115005 #ifdef SQLITE_TEST
115006 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
115007 #else
115008 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
115009 #  define sqlite3_fts3_enable_parentheses 1
115010 # else
115011 #  define sqlite3_fts3_enable_parentheses 0
115012 # endif
115013 #endif
115014
115015 /*
115016 ** Default span for NEAR operators.
115017 */
115018 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
115019
115020
115021 typedef struct ParseContext ParseContext;
115022 struct ParseContext {
115023   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
115024   const char **azCol;                 /* Array of column names for fts3 table */
115025   int nCol;                           /* Number of entries in azCol[] */
115026   int iDefaultCol;                    /* Default column to query */
115027   sqlite3_context *pCtx;              /* Write error message here */
115028   int nNest;                          /* Number of nested brackets */
115029 };
115030
115031 /*
115032 ** This function is equivalent to the standard isspace() function. 
115033 **
115034 ** The standard isspace() can be awkward to use safely, because although it
115035 ** is defined to accept an argument of type int, its behaviour when passed
115036 ** an integer that falls outside of the range of the unsigned char type
115037 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
115038 ** is defined to accept an argument of type char, and always returns 0 for
115039 ** any values that fall outside of the range of the unsigned char type (i.e.
115040 ** negative values).
115041 */
115042 static int fts3isspace(char c){
115043   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
115044 }
115045
115046 /*
115047 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
115048 ** zero the memory before returning a pointer to it. If unsuccessful, 
115049 ** return NULL.
115050 */
115051 static void *fts3MallocZero(int nByte){
115052   void *pRet = sqlite3_malloc(nByte);
115053   if( pRet ) memset(pRet, 0, nByte);
115054   return pRet;
115055 }
115056
115057
115058 /*
115059 ** Extract the next token from buffer z (length n) using the tokenizer
115060 ** and other information (column names etc.) in pParse. Create an Fts3Expr
115061 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
115062 ** single token and set *ppExpr to point to it. If the end of the buffer is
115063 ** reached before a token is found, set *ppExpr to zero. It is the
115064 ** responsibility of the caller to eventually deallocate the allocated 
115065 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
115066 **
115067 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
115068 ** fails.
115069 */
115070 static int getNextToken(
115071   ParseContext *pParse,                   /* fts3 query parse context */
115072   int iCol,                               /* Value for Fts3Phrase.iColumn */
115073   const char *z, int n,                   /* Input string */
115074   Fts3Expr **ppExpr,                      /* OUT: expression */
115075   int *pnConsumed                         /* OUT: Number of bytes consumed */
115076 ){
115077   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115078   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115079   int rc;
115080   sqlite3_tokenizer_cursor *pCursor;
115081   Fts3Expr *pRet = 0;
115082   int nConsumed = 0;
115083
115084   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
115085   if( rc==SQLITE_OK ){
115086     const char *zToken;
115087     int nToken, iStart, iEnd, iPosition;
115088     int nByte;                               /* total space to allocate */
115089
115090     pCursor->pTokenizer = pTokenizer;
115091     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
115092
115093     if( rc==SQLITE_OK ){
115094       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
115095       pRet = (Fts3Expr *)fts3MallocZero(nByte);
115096       if( !pRet ){
115097         rc = SQLITE_NOMEM;
115098       }else{
115099         pRet->eType = FTSQUERY_PHRASE;
115100         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
115101         pRet->pPhrase->nToken = 1;
115102         pRet->pPhrase->iColumn = iCol;
115103         pRet->pPhrase->aToken[0].n = nToken;
115104         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
115105         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
115106
115107         if( iEnd<n && z[iEnd]=='*' ){
115108           pRet->pPhrase->aToken[0].isPrefix = 1;
115109           iEnd++;
115110         }
115111         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
115112           pRet->pPhrase->isNot = 1;
115113         }
115114       }
115115       nConsumed = iEnd;
115116     }
115117
115118     pModule->xClose(pCursor);
115119   }
115120   
115121   *pnConsumed = nConsumed;
115122   *ppExpr = pRet;
115123   return rc;
115124 }
115125
115126
115127 /*
115128 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
115129 ** then free the old allocation.
115130 */
115131 static void *fts3ReallocOrFree(void *pOrig, int nNew){
115132   void *pRet = sqlite3_realloc(pOrig, nNew);
115133   if( !pRet ){
115134     sqlite3_free(pOrig);
115135   }
115136   return pRet;
115137 }
115138
115139 /*
115140 ** Buffer zInput, length nInput, contains the contents of a quoted string
115141 ** that appeared as part of an fts3 query expression. Neither quote character
115142 ** is included in the buffer. This function attempts to tokenize the entire
115143 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
115144 ** containing the results.
115145 **
115146 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
115147 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
115148 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
115149 ** to 0.
115150 */
115151 static int getNextString(
115152   ParseContext *pParse,                   /* fts3 query parse context */
115153   const char *zInput, int nInput,         /* Input string */
115154   Fts3Expr **ppExpr                       /* OUT: expression */
115155 ){
115156   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
115157   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115158   int rc;
115159   Fts3Expr *p = 0;
115160   sqlite3_tokenizer_cursor *pCursor = 0;
115161   char *zTemp = 0;
115162   int nTemp = 0;
115163
115164   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
115165   if( rc==SQLITE_OK ){
115166     int ii;
115167     pCursor->pTokenizer = pTokenizer;
115168     for(ii=0; rc==SQLITE_OK; ii++){
115169       const char *zToken;
115170       int nToken, iBegin, iEnd, iPos;
115171       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
115172       if( rc==SQLITE_OK ){
115173         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115174         p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
115175         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
115176         if( !p || !zTemp ){
115177           goto no_mem;
115178         }
115179         if( ii==0 ){
115180           memset(p, 0, nByte);
115181           p->pPhrase = (Fts3Phrase *)&p[1];
115182         }
115183         p->pPhrase = (Fts3Phrase *)&p[1];
115184         memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
115185         p->pPhrase->nToken = ii+1;
115186         p->pPhrase->aToken[ii].n = nToken;
115187         memcpy(&zTemp[nTemp], zToken, nToken);
115188         nTemp += nToken;
115189         if( iEnd<nInput && zInput[iEnd]=='*' ){
115190           p->pPhrase->aToken[ii].isPrefix = 1;
115191         }else{
115192           p->pPhrase->aToken[ii].isPrefix = 0;
115193         }
115194       }
115195     }
115196
115197     pModule->xClose(pCursor);
115198     pCursor = 0;
115199   }
115200
115201   if( rc==SQLITE_DONE ){
115202     int jj;
115203     char *zNew = NULL;
115204     int nNew = 0;
115205     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
115206     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
115207     p = fts3ReallocOrFree(p, nByte + nTemp);
115208     if( !p ){
115209       goto no_mem;
115210     }
115211     if( zTemp ){
115212       zNew = &(((char *)p)[nByte]);
115213       memcpy(zNew, zTemp, nTemp);
115214     }else{
115215       memset(p, 0, nByte+nTemp);
115216     }
115217     p->pPhrase = (Fts3Phrase *)&p[1];
115218     for(jj=0; jj<p->pPhrase->nToken; jj++){
115219       p->pPhrase->aToken[jj].z = &zNew[nNew];
115220       nNew += p->pPhrase->aToken[jj].n;
115221     }
115222     sqlite3_free(zTemp);
115223     p->eType = FTSQUERY_PHRASE;
115224     p->pPhrase->iColumn = pParse->iDefaultCol;
115225     rc = SQLITE_OK;
115226   }
115227
115228   *ppExpr = p;
115229   return rc;
115230 no_mem:
115231
115232   if( pCursor ){
115233     pModule->xClose(pCursor);
115234   }
115235   sqlite3_free(zTemp);
115236   sqlite3_free(p);
115237   *ppExpr = 0;
115238   return SQLITE_NOMEM;
115239 }
115240
115241 /*
115242 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
115243 ** call fts3ExprParse(). So this forward declaration is required.
115244 */
115245 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
115246
115247 /*
115248 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
115249 ** structure, or set to 0 if the end of the input buffer is reached.
115250 **
115251 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
115252 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
115253 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
115254 */
115255 static int getNextNode(
115256   ParseContext *pParse,                   /* fts3 query parse context */
115257   const char *z, int n,                   /* Input string */
115258   Fts3Expr **ppExpr,                      /* OUT: expression */
115259   int *pnConsumed                         /* OUT: Number of bytes consumed */
115260 ){
115261   static const struct Fts3Keyword {
115262     char *z;                              /* Keyword text */
115263     unsigned char n;                      /* Length of the keyword */
115264     unsigned char parenOnly;              /* Only valid in paren mode */
115265     unsigned char eType;                  /* Keyword code */
115266   } aKeyword[] = {
115267     { "OR" ,  2, 0, FTSQUERY_OR   },
115268     { "AND",  3, 1, FTSQUERY_AND  },
115269     { "NOT",  3, 1, FTSQUERY_NOT  },
115270     { "NEAR", 4, 0, FTSQUERY_NEAR }
115271   };
115272   int ii;
115273   int iCol;
115274   int iColLen;
115275   int rc;
115276   Fts3Expr *pRet = 0;
115277
115278   const char *zInput = z;
115279   int nInput = n;
115280
115281   /* Skip over any whitespace before checking for a keyword, an open or
115282   ** close bracket, or a quoted string. 
115283   */
115284   while( nInput>0 && fts3isspace(*zInput) ){
115285     nInput--;
115286     zInput++;
115287   }
115288   if( nInput==0 ){
115289     return SQLITE_DONE;
115290   }
115291
115292   /* See if we are dealing with a keyword. */
115293   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
115294     const struct Fts3Keyword *pKey = &aKeyword[ii];
115295
115296     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
115297       continue;
115298     }
115299
115300     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
115301       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
115302       int nKey = pKey->n;
115303       char cNext;
115304
115305       /* If this is a "NEAR" keyword, check for an explicit nearness. */
115306       if( pKey->eType==FTSQUERY_NEAR ){
115307         assert( nKey==4 );
115308         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
115309           nNear = 0;
115310           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
115311             nNear = nNear * 10 + (zInput[nKey] - '0');
115312           }
115313         }
115314       }
115315
115316       /* At this point this is probably a keyword. But for that to be true,
115317       ** the next byte must contain either whitespace, an open or close
115318       ** parenthesis, a quote character, or EOF. 
115319       */
115320       cNext = zInput[nKey];
115321       if( fts3isspace(cNext) 
115322        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
115323       ){
115324         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
115325         if( !pRet ){
115326           return SQLITE_NOMEM;
115327         }
115328         pRet->eType = pKey->eType;
115329         pRet->nNear = nNear;
115330         *ppExpr = pRet;
115331         *pnConsumed = (int)((zInput - z) + nKey);
115332         return SQLITE_OK;
115333       }
115334
115335       /* Turns out that wasn't a keyword after all. This happens if the
115336       ** user has supplied a token such as "ORacle". Continue.
115337       */
115338     }
115339   }
115340
115341   /* Check for an open bracket. */
115342   if( sqlite3_fts3_enable_parentheses ){
115343     if( *zInput=='(' ){
115344       int nConsumed;
115345       pParse->nNest++;
115346       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
115347       if( rc==SQLITE_OK && !*ppExpr ){
115348         rc = SQLITE_DONE;
115349       }
115350       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
115351       return rc;
115352     }
115353   
115354     /* Check for a close bracket. */
115355     if( *zInput==')' ){
115356       pParse->nNest--;
115357       *pnConsumed = (int)((zInput - z) + 1);
115358       return SQLITE_DONE;
115359     }
115360   }
115361
115362   /* See if we are dealing with a quoted phrase. If this is the case, then
115363   ** search for the closing quote and pass the whole string to getNextString()
115364   ** for processing. This is easy to do, as fts3 has no syntax for escaping
115365   ** a quote character embedded in a string.
115366   */
115367   if( *zInput=='"' ){
115368     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
115369     *pnConsumed = (int)((zInput - z) + ii + 1);
115370     if( ii==nInput ){
115371       return SQLITE_ERROR;
115372     }
115373     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
115374   }
115375
115376
115377   /* If control flows to this point, this must be a regular token, or 
115378   ** the end of the input. Read a regular token using the sqlite3_tokenizer
115379   ** interface. Before doing so, figure out if there is an explicit
115380   ** column specifier for the token. 
115381   **
115382   ** TODO: Strangely, it is not possible to associate a column specifier
115383   ** with a quoted phrase, only with a single token. Not sure if this was
115384   ** an implementation artifact or an intentional decision when fts3 was
115385   ** first implemented. Whichever it was, this module duplicates the 
115386   ** limitation.
115387   */
115388   iCol = pParse->iDefaultCol;
115389   iColLen = 0;
115390   for(ii=0; ii<pParse->nCol; ii++){
115391     const char *zStr = pParse->azCol[ii];
115392     int nStr = (int)strlen(zStr);
115393     if( nInput>nStr && zInput[nStr]==':' 
115394      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
115395     ){
115396       iCol = ii;
115397       iColLen = (int)((zInput - z) + nStr + 1);
115398       break;
115399     }
115400   }
115401   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
115402   *pnConsumed += iColLen;
115403   return rc;
115404 }
115405
115406 /*
115407 ** The argument is an Fts3Expr structure for a binary operator (any type
115408 ** except an FTSQUERY_PHRASE). Return an integer value representing the
115409 ** precedence of the operator. Lower values have a higher precedence (i.e.
115410 ** group more tightly). For example, in the C language, the == operator
115411 ** groups more tightly than ||, and would therefore have a higher precedence.
115412 **
115413 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
115414 ** is defined), the order of the operators in precedence from highest to
115415 ** lowest is:
115416 **
115417 **   NEAR
115418 **   NOT
115419 **   AND (including implicit ANDs)
115420 **   OR
115421 **
115422 ** Note that when using the old query syntax, the OR operator has a higher
115423 ** precedence than the AND operator.
115424 */
115425 static int opPrecedence(Fts3Expr *p){
115426   assert( p->eType!=FTSQUERY_PHRASE );
115427   if( sqlite3_fts3_enable_parentheses ){
115428     return p->eType;
115429   }else if( p->eType==FTSQUERY_NEAR ){
115430     return 1;
115431   }else if( p->eType==FTSQUERY_OR ){
115432     return 2;
115433   }
115434   assert( p->eType==FTSQUERY_AND );
115435   return 3;
115436 }
115437
115438 /*
115439 ** Argument ppHead contains a pointer to the current head of a query 
115440 ** expression tree being parsed. pPrev is the expression node most recently
115441 ** inserted into the tree. This function adds pNew, which is always a binary
115442 ** operator node, into the expression tree based on the relative precedence
115443 ** of pNew and the existing nodes of the tree. This may result in the head
115444 ** of the tree changing, in which case *ppHead is set to the new root node.
115445 */
115446 static void insertBinaryOperator(
115447   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
115448   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
115449   Fts3Expr *pNew           /* New binary node to insert into expression tree */
115450 ){
115451   Fts3Expr *pSplit = pPrev;
115452   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
115453     pSplit = pSplit->pParent;
115454   }
115455
115456   if( pSplit->pParent ){
115457     assert( pSplit->pParent->pRight==pSplit );
115458     pSplit->pParent->pRight = pNew;
115459     pNew->pParent = pSplit->pParent;
115460   }else{
115461     *ppHead = pNew;
115462   }
115463   pNew->pLeft = pSplit;
115464   pSplit->pParent = pNew;
115465 }
115466
115467 /*
115468 ** Parse the fts3 query expression found in buffer z, length n. This function
115469 ** returns either when the end of the buffer is reached or an unmatched 
115470 ** closing bracket - ')' - is encountered.
115471 **
115472 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
115473 ** parsed form of the expression and *pnConsumed is set to the number of
115474 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
115475 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
115476 */
115477 static int fts3ExprParse(
115478   ParseContext *pParse,                   /* fts3 query parse context */
115479   const char *z, int n,                   /* Text of MATCH query */
115480   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
115481   int *pnConsumed                         /* OUT: Number of bytes consumed */
115482 ){
115483   Fts3Expr *pRet = 0;
115484   Fts3Expr *pPrev = 0;
115485   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
115486   int nIn = n;
115487   const char *zIn = z;
115488   int rc = SQLITE_OK;
115489   int isRequirePhrase = 1;
115490
115491   while( rc==SQLITE_OK ){
115492     Fts3Expr *p = 0;
115493     int nByte = 0;
115494     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
115495     if( rc==SQLITE_OK ){
115496       int isPhrase;
115497
115498       if( !sqlite3_fts3_enable_parentheses 
115499        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
115500       ){
115501         /* Create an implicit NOT operator. */
115502         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
115503         if( !pNot ){
115504           sqlite3Fts3ExprFree(p);
115505           rc = SQLITE_NOMEM;
115506           goto exprparse_out;
115507         }
115508         pNot->eType = FTSQUERY_NOT;
115509         pNot->pRight = p;
115510         if( pNotBranch ){
115511           pNot->pLeft = pNotBranch;
115512         }
115513         pNotBranch = pNot;
115514         p = pPrev;
115515       }else{
115516         int eType = p->eType;
115517         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
115518         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
115519
115520         /* The isRequirePhrase variable is set to true if a phrase or
115521         ** an expression contained in parenthesis is required. If a
115522         ** binary operator (AND, OR, NOT or NEAR) is encounted when
115523         ** isRequirePhrase is set, this is a syntax error.
115524         */
115525         if( !isPhrase && isRequirePhrase ){
115526           sqlite3Fts3ExprFree(p);
115527           rc = SQLITE_ERROR;
115528           goto exprparse_out;
115529         }
115530   
115531         if( isPhrase && !isRequirePhrase ){
115532           /* Insert an implicit AND operator. */
115533           Fts3Expr *pAnd;
115534           assert( pRet && pPrev );
115535           pAnd = fts3MallocZero(sizeof(Fts3Expr));
115536           if( !pAnd ){
115537             sqlite3Fts3ExprFree(p);
115538             rc = SQLITE_NOMEM;
115539             goto exprparse_out;
115540           }
115541           pAnd->eType = FTSQUERY_AND;
115542           insertBinaryOperator(&pRet, pPrev, pAnd);
115543           pPrev = pAnd;
115544         }
115545
115546         /* This test catches attempts to make either operand of a NEAR
115547         ** operator something other than a phrase. For example, either of
115548         ** the following:
115549         **
115550         **    (bracketed expression) NEAR phrase
115551         **    phrase NEAR (bracketed expression)
115552         **
115553         ** Return an error in either case.
115554         */
115555         if( pPrev && (
115556             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
115557          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
115558         )){
115559           sqlite3Fts3ExprFree(p);
115560           rc = SQLITE_ERROR;
115561           goto exprparse_out;
115562         }
115563   
115564         if( isPhrase ){
115565           if( pRet ){
115566             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
115567             pPrev->pRight = p;
115568             p->pParent = pPrev;
115569           }else{
115570             pRet = p;
115571           }
115572         }else{
115573           insertBinaryOperator(&pRet, pPrev, p);
115574         }
115575         isRequirePhrase = !isPhrase;
115576       }
115577       assert( nByte>0 );
115578     }
115579     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
115580     nIn -= nByte;
115581     zIn += nByte;
115582     pPrev = p;
115583   }
115584
115585   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
115586     rc = SQLITE_ERROR;
115587   }
115588
115589   if( rc==SQLITE_DONE ){
115590     rc = SQLITE_OK;
115591     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
115592       if( !pRet ){
115593         rc = SQLITE_ERROR;
115594       }else{
115595         Fts3Expr *pIter = pNotBranch;
115596         while( pIter->pLeft ){
115597           pIter = pIter->pLeft;
115598         }
115599         pIter->pLeft = pRet;
115600         pRet = pNotBranch;
115601       }
115602     }
115603   }
115604   *pnConsumed = n - nIn;
115605
115606 exprparse_out:
115607   if( rc!=SQLITE_OK ){
115608     sqlite3Fts3ExprFree(pRet);
115609     sqlite3Fts3ExprFree(pNotBranch);
115610     pRet = 0;
115611   }
115612   *ppExpr = pRet;
115613   return rc;
115614 }
115615
115616 /*
115617 ** Parameters z and n contain a pointer to and length of a buffer containing
115618 ** an fts3 query expression, respectively. This function attempts to parse the
115619 ** query expression and create a tree of Fts3Expr structures representing the
115620 ** parsed expression. If successful, *ppExpr is set to point to the head
115621 ** of the parsed expression tree and SQLITE_OK is returned. If an error
115622 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
115623 ** error) is returned and *ppExpr is set to 0.
115624 **
115625 ** If parameter n is a negative number, then z is assumed to point to a
115626 ** nul-terminated string and the length is determined using strlen().
115627 **
115628 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
115629 ** use to normalize query tokens while parsing the expression. The azCol[]
115630 ** array, which is assumed to contain nCol entries, should contain the names
115631 ** of each column in the target fts3 table, in order from left to right. 
115632 ** Column names must be nul-terminated strings.
115633 **
115634 ** The iDefaultCol parameter should be passed the index of the table column
115635 ** that appears on the left-hand-side of the MATCH operator (the default
115636 ** column to match against for tokens for which a column name is not explicitly
115637 ** specified as part of the query string), or -1 if tokens may by default
115638 ** match any table column.
115639 */
115640 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
115641   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
115642   char **azCol,                       /* Array of column names for fts3 table */
115643   int nCol,                           /* Number of entries in azCol[] */
115644   int iDefaultCol,                    /* Default column to query */
115645   const char *z, int n,               /* Text of MATCH query */
115646   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
115647 ){
115648   int nParsed;
115649   int rc;
115650   ParseContext sParse;
115651   sParse.pTokenizer = pTokenizer;
115652   sParse.azCol = (const char **)azCol;
115653   sParse.nCol = nCol;
115654   sParse.iDefaultCol = iDefaultCol;
115655   sParse.nNest = 0;
115656   if( z==0 ){
115657     *ppExpr = 0;
115658     return SQLITE_OK;
115659   }
115660   if( n<0 ){
115661     n = (int)strlen(z);
115662   }
115663   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
115664
115665   /* Check for mismatched parenthesis */
115666   if( rc==SQLITE_OK && sParse.nNest ){
115667     rc = SQLITE_ERROR;
115668     sqlite3Fts3ExprFree(*ppExpr);
115669     *ppExpr = 0;
115670   }
115671
115672   return rc;
115673 }
115674
115675 /*
115676 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
115677 */
115678 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
115679   if( p ){
115680     sqlite3Fts3ExprFree(p->pLeft);
115681     sqlite3Fts3ExprFree(p->pRight);
115682     sqlite3_free(p->aDoclist);
115683     sqlite3_free(p);
115684   }
115685 }
115686
115687 /****************************************************************************
115688 *****************************************************************************
115689 ** Everything after this point is just test code.
115690 */
115691
115692 #ifdef SQLITE_TEST
115693
115694
115695 /*
115696 ** Function to query the hash-table of tokenizers (see README.tokenizers).
115697 */
115698 static int queryTestTokenizer(
115699   sqlite3 *db, 
115700   const char *zName,  
115701   const sqlite3_tokenizer_module **pp
115702 ){
115703   int rc;
115704   sqlite3_stmt *pStmt;
115705   const char zSql[] = "SELECT fts3_tokenizer(?)";
115706
115707   *pp = 0;
115708   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
115709   if( rc!=SQLITE_OK ){
115710     return rc;
115711   }
115712
115713   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
115714   if( SQLITE_ROW==sqlite3_step(pStmt) ){
115715     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
115716       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
115717     }
115718   }
115719
115720   return sqlite3_finalize(pStmt);
115721 }
115722
115723 /*
115724 ** Return a pointer to a buffer containing a text representation of the
115725 ** expression passed as the first argument. The buffer is obtained from
115726 ** sqlite3_malloc(). It is the responsibility of the caller to use 
115727 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
115728 ** NULL is returned.
115729 **
115730 ** If the second argument is not NULL, then its contents are prepended to 
115731 ** the returned expression text and then freed using sqlite3_free().
115732 */
115733 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
115734   switch( pExpr->eType ){
115735     case FTSQUERY_PHRASE: {
115736       Fts3Phrase *pPhrase = pExpr->pPhrase;
115737       int i;
115738       zBuf = sqlite3_mprintf(
115739           "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
115740       for(i=0; zBuf && i<pPhrase->nToken; i++){
115741         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
115742             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
115743             (pPhrase->aToken[i].isPrefix?"+":"")
115744         );
115745       }
115746       return zBuf;
115747     }
115748
115749     case FTSQUERY_NEAR:
115750       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
115751       break;
115752     case FTSQUERY_NOT:
115753       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
115754       break;
115755     case FTSQUERY_AND:
115756       zBuf = sqlite3_mprintf("%zAND ", zBuf);
115757       break;
115758     case FTSQUERY_OR:
115759       zBuf = sqlite3_mprintf("%zOR ", zBuf);
115760       break;
115761   }
115762
115763   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
115764   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
115765   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
115766
115767   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
115768   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
115769
115770   return zBuf;
115771 }
115772
115773 /*
115774 ** This is the implementation of a scalar SQL function used to test the 
115775 ** expression parser. It should be called as follows:
115776 **
115777 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
115778 **
115779 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
115780 ** to parse the query expression (see README.tokenizers). The second argument
115781 ** is the query expression to parse. Each subsequent argument is the name
115782 ** of a column of the fts3 table that the query expression may refer to.
115783 ** For example:
115784 **
115785 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
115786 */
115787 static void fts3ExprTest(
115788   sqlite3_context *context,
115789   int argc,
115790   sqlite3_value **argv
115791 ){
115792   sqlite3_tokenizer_module const *pModule = 0;
115793   sqlite3_tokenizer *pTokenizer = 0;
115794   int rc;
115795   char **azCol = 0;
115796   const char *zExpr;
115797   int nExpr;
115798   int nCol;
115799   int ii;
115800   Fts3Expr *pExpr;
115801   char *zBuf = 0;
115802   sqlite3 *db = sqlite3_context_db_handle(context);
115803
115804   if( argc<3 ){
115805     sqlite3_result_error(context, 
115806         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
115807     );
115808     return;
115809   }
115810
115811   rc = queryTestTokenizer(db,
115812                           (const char *)sqlite3_value_text(argv[0]), &pModule);
115813   if( rc==SQLITE_NOMEM ){
115814     sqlite3_result_error_nomem(context);
115815     goto exprtest_out;
115816   }else if( !pModule ){
115817     sqlite3_result_error(context, "No such tokenizer module", -1);
115818     goto exprtest_out;
115819   }
115820
115821   rc = pModule->xCreate(0, 0, &pTokenizer);
115822   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
115823   if( rc==SQLITE_NOMEM ){
115824     sqlite3_result_error_nomem(context);
115825     goto exprtest_out;
115826   }
115827   pTokenizer->pModule = pModule;
115828
115829   zExpr = (const char *)sqlite3_value_text(argv[1]);
115830   nExpr = sqlite3_value_bytes(argv[1]);
115831   nCol = argc-2;
115832   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
115833   if( !azCol ){
115834     sqlite3_result_error_nomem(context);
115835     goto exprtest_out;
115836   }
115837   for(ii=0; ii<nCol; ii++){
115838     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
115839   }
115840
115841   rc = sqlite3Fts3ExprParse(
115842       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
115843   );
115844   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
115845     sqlite3_result_error(context, "Error parsing expression", -1);
115846   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
115847     sqlite3_result_error_nomem(context);
115848   }else{
115849     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
115850     sqlite3_free(zBuf);
115851   }
115852
115853   sqlite3Fts3ExprFree(pExpr);
115854
115855 exprtest_out:
115856   if( pModule && pTokenizer ){
115857     rc = pModule->xDestroy(pTokenizer);
115858   }
115859   sqlite3_free(azCol);
115860 }
115861
115862 /*
115863 ** Register the query expression parser test function fts3_exprtest() 
115864 ** with database connection db. 
115865 */
115866 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
115867   return sqlite3_create_function(
115868       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
115869   );
115870 }
115871
115872 #endif
115873 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
115874
115875 /************** End of fts3_expr.c *******************************************/
115876 /************** Begin file fts3_hash.c ***************************************/
115877 /*
115878 ** 2001 September 22
115879 **
115880 ** The author disclaims copyright to this source code.  In place of
115881 ** a legal notice, here is a blessing:
115882 **
115883 **    May you do good and not evil.
115884 **    May you find forgiveness for yourself and forgive others.
115885 **    May you share freely, never taking more than you give.
115886 **
115887 *************************************************************************
115888 ** This is the implementation of generic hash-tables used in SQLite.
115889 ** We've modified it slightly to serve as a standalone hash table
115890 ** implementation for the full-text indexing module.
115891 */
115892
115893 /*
115894 ** The code in this file is only compiled if:
115895 **
115896 **     * The FTS3 module is being built as an extension
115897 **       (in which case SQLITE_CORE is not defined), or
115898 **
115899 **     * The FTS3 module is being built into the core of
115900 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
115901 */
115902 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
115903
115904
115905
115906 /*
115907 ** Malloc and Free functions
115908 */
115909 static void *fts3HashMalloc(int n){
115910   void *p = sqlite3_malloc(n);
115911   if( p ){
115912     memset(p, 0, n);
115913   }
115914   return p;
115915 }
115916 static void fts3HashFree(void *p){
115917   sqlite3_free(p);
115918 }
115919
115920 /* Turn bulk memory into a hash table object by initializing the
115921 ** fields of the Hash structure.
115922 **
115923 ** "pNew" is a pointer to the hash table that is to be initialized.
115924 ** keyClass is one of the constants 
115925 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
115926 ** determines what kind of key the hash table will use.  "copyKey" is
115927 ** true if the hash table should make its own private copy of keys and
115928 ** false if it should just use the supplied pointer.
115929 */
115930 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
115931   assert( pNew!=0 );
115932   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
115933   pNew->keyClass = keyClass;
115934   pNew->copyKey = copyKey;
115935   pNew->first = 0;
115936   pNew->count = 0;
115937   pNew->htsize = 0;
115938   pNew->ht = 0;
115939 }
115940
115941 /* Remove all entries from a hash table.  Reclaim all memory.
115942 ** Call this routine to delete a hash table or to reset a hash table
115943 ** to the empty state.
115944 */
115945 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
115946   Fts3HashElem *elem;         /* For looping over all elements of the table */
115947
115948   assert( pH!=0 );
115949   elem = pH->first;
115950   pH->first = 0;
115951   fts3HashFree(pH->ht);
115952   pH->ht = 0;
115953   pH->htsize = 0;
115954   while( elem ){
115955     Fts3HashElem *next_elem = elem->next;
115956     if( pH->copyKey && elem->pKey ){
115957       fts3HashFree(elem->pKey);
115958     }
115959     fts3HashFree(elem);
115960     elem = next_elem;
115961   }
115962   pH->count = 0;
115963 }
115964
115965 /*
115966 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
115967 */
115968 static int fts3StrHash(const void *pKey, int nKey){
115969   const char *z = (const char *)pKey;
115970   int h = 0;
115971   if( nKey<=0 ) nKey = (int) strlen(z);
115972   while( nKey > 0  ){
115973     h = (h<<3) ^ h ^ *z++;
115974     nKey--;
115975   }
115976   return h & 0x7fffffff;
115977 }
115978 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
115979   if( n1!=n2 ) return 1;
115980   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
115981 }
115982
115983 /*
115984 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
115985 */
115986 static int fts3BinHash(const void *pKey, int nKey){
115987   int h = 0;
115988   const char *z = (const char *)pKey;
115989   while( nKey-- > 0 ){
115990     h = (h<<3) ^ h ^ *(z++);
115991   }
115992   return h & 0x7fffffff;
115993 }
115994 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
115995   if( n1!=n2 ) return 1;
115996   return memcmp(pKey1,pKey2,n1);
115997 }
115998
115999 /*
116000 ** Return a pointer to the appropriate hash function given the key class.
116001 **
116002 ** The C syntax in this function definition may be unfamilar to some 
116003 ** programmers, so we provide the following additional explanation:
116004 **
116005 ** The name of the function is "ftsHashFunction".  The function takes a
116006 ** single parameter "keyClass".  The return value of ftsHashFunction()
116007 ** is a pointer to another function.  Specifically, the return value
116008 ** of ftsHashFunction() is a pointer to a function that takes two parameters
116009 ** with types "const void*" and "int" and returns an "int".
116010 */
116011 static int (*ftsHashFunction(int keyClass))(const void*,int){
116012   if( keyClass==FTS3_HASH_STRING ){
116013     return &fts3StrHash;
116014   }else{
116015     assert( keyClass==FTS3_HASH_BINARY );
116016     return &fts3BinHash;
116017   }
116018 }
116019
116020 /*
116021 ** Return a pointer to the appropriate hash function given the key class.
116022 **
116023 ** For help in interpreted the obscure C code in the function definition,
116024 ** see the header comment on the previous function.
116025 */
116026 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
116027   if( keyClass==FTS3_HASH_STRING ){
116028     return &fts3StrCompare;
116029   }else{
116030     assert( keyClass==FTS3_HASH_BINARY );
116031     return &fts3BinCompare;
116032   }
116033 }
116034
116035 /* Link an element into the hash table
116036 */
116037 static void fts3HashInsertElement(
116038   Fts3Hash *pH,            /* The complete hash table */
116039   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
116040   Fts3HashElem *pNew       /* The element to be inserted */
116041 ){
116042   Fts3HashElem *pHead;     /* First element already in pEntry */
116043   pHead = pEntry->chain;
116044   if( pHead ){
116045     pNew->next = pHead;
116046     pNew->prev = pHead->prev;
116047     if( pHead->prev ){ pHead->prev->next = pNew; }
116048     else             { pH->first = pNew; }
116049     pHead->prev = pNew;
116050   }else{
116051     pNew->next = pH->first;
116052     if( pH->first ){ pH->first->prev = pNew; }
116053     pNew->prev = 0;
116054     pH->first = pNew;
116055   }
116056   pEntry->count++;
116057   pEntry->chain = pNew;
116058 }
116059
116060
116061 /* Resize the hash table so that it cantains "new_size" buckets.
116062 ** "new_size" must be a power of 2.  The hash table might fail 
116063 ** to resize if sqliteMalloc() fails.
116064 **
116065 ** Return non-zero if a memory allocation error occurs.
116066 */
116067 static int fts3Rehash(Fts3Hash *pH, int new_size){
116068   struct _fts3ht *new_ht;          /* The new hash table */
116069   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
116070   int (*xHash)(const void*,int);   /* The hash function */
116071
116072   assert( (new_size & (new_size-1))==0 );
116073   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
116074   if( new_ht==0 ) return 1;
116075   fts3HashFree(pH->ht);
116076   pH->ht = new_ht;
116077   pH->htsize = new_size;
116078   xHash = ftsHashFunction(pH->keyClass);
116079   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
116080     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
116081     next_elem = elem->next;
116082     fts3HashInsertElement(pH, &new_ht[h], elem);
116083   }
116084   return 0;
116085 }
116086
116087 /* This function (for internal use only) locates an element in an
116088 ** hash table that matches the given key.  The hash for this key has
116089 ** already been computed and is passed as the 4th parameter.
116090 */
116091 static Fts3HashElem *fts3FindElementByHash(
116092   const Fts3Hash *pH, /* The pH to be searched */
116093   const void *pKey,   /* The key we are searching for */
116094   int nKey,
116095   int h               /* The hash for this key. */
116096 ){
116097   Fts3HashElem *elem;            /* Used to loop thru the element list */
116098   int count;                     /* Number of elements left to test */
116099   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
116100
116101   if( pH->ht ){
116102     struct _fts3ht *pEntry = &pH->ht[h];
116103     elem = pEntry->chain;
116104     count = pEntry->count;
116105     xCompare = ftsCompareFunction(pH->keyClass);
116106     while( count-- && elem ){
116107       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
116108         return elem;
116109       }
116110       elem = elem->next;
116111     }
116112   }
116113   return 0;
116114 }
116115
116116 /* Remove a single entry from the hash table given a pointer to that
116117 ** element and a hash on the element's key.
116118 */
116119 static void fts3RemoveElementByHash(
116120   Fts3Hash *pH,         /* The pH containing "elem" */
116121   Fts3HashElem* elem,   /* The element to be removed from the pH */
116122   int h                 /* Hash value for the element */
116123 ){
116124   struct _fts3ht *pEntry;
116125   if( elem->prev ){
116126     elem->prev->next = elem->next; 
116127   }else{
116128     pH->first = elem->next;
116129   }
116130   if( elem->next ){
116131     elem->next->prev = elem->prev;
116132   }
116133   pEntry = &pH->ht[h];
116134   if( pEntry->chain==elem ){
116135     pEntry->chain = elem->next;
116136   }
116137   pEntry->count--;
116138   if( pEntry->count<=0 ){
116139     pEntry->chain = 0;
116140   }
116141   if( pH->copyKey && elem->pKey ){
116142     fts3HashFree(elem->pKey);
116143   }
116144   fts3HashFree( elem );
116145   pH->count--;
116146   if( pH->count<=0 ){
116147     assert( pH->first==0 );
116148     assert( pH->count==0 );
116149     fts3HashClear(pH);
116150   }
116151 }
116152
116153 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
116154   const Fts3Hash *pH, 
116155   const void *pKey, 
116156   int nKey
116157 ){
116158   int h;                          /* A hash on key */
116159   int (*xHash)(const void*,int);  /* The hash function */
116160
116161   if( pH==0 || pH->ht==0 ) return 0;
116162   xHash = ftsHashFunction(pH->keyClass);
116163   assert( xHash!=0 );
116164   h = (*xHash)(pKey,nKey);
116165   assert( (pH->htsize & (pH->htsize-1))==0 );
116166   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
116167 }
116168
116169 /* 
116170 ** Attempt to locate an element of the hash table pH with a key
116171 ** that matches pKey,nKey.  Return the data for this element if it is
116172 ** found, or NULL if there is no match.
116173 */
116174 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
116175   Fts3HashElem *pElem;            /* The element that matches key (if any) */
116176
116177   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
116178   return pElem ? pElem->data : 0;
116179 }
116180
116181 /* Insert an element into the hash table pH.  The key is pKey,nKey
116182 ** and the data is "data".
116183 **
116184 ** If no element exists with a matching key, then a new
116185 ** element is created.  A copy of the key is made if the copyKey
116186 ** flag is set.  NULL is returned.
116187 **
116188 ** If another element already exists with the same key, then the
116189 ** new data replaces the old data and the old data is returned.
116190 ** The key is not copied in this instance.  If a malloc fails, then
116191 ** the new data is returned and the hash table is unchanged.
116192 **
116193 ** If the "data" parameter to this function is NULL, then the
116194 ** element corresponding to "key" is removed from the hash table.
116195 */
116196 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
116197   Fts3Hash *pH,        /* The hash table to insert into */
116198   const void *pKey,    /* The key */
116199   int nKey,            /* Number of bytes in the key */
116200   void *data           /* The data */
116201 ){
116202   int hraw;                 /* Raw hash value of the key */
116203   int h;                    /* the hash of the key modulo hash table size */
116204   Fts3HashElem *elem;       /* Used to loop thru the element list */
116205   Fts3HashElem *new_elem;   /* New element added to the pH */
116206   int (*xHash)(const void*,int);  /* The hash function */
116207
116208   assert( pH!=0 );
116209   xHash = ftsHashFunction(pH->keyClass);
116210   assert( xHash!=0 );
116211   hraw = (*xHash)(pKey, nKey);
116212   assert( (pH->htsize & (pH->htsize-1))==0 );
116213   h = hraw & (pH->htsize-1);
116214   elem = fts3FindElementByHash(pH,pKey,nKey,h);
116215   if( elem ){
116216     void *old_data = elem->data;
116217     if( data==0 ){
116218       fts3RemoveElementByHash(pH,elem,h);
116219     }else{
116220       elem->data = data;
116221     }
116222     return old_data;
116223   }
116224   if( data==0 ) return 0;
116225   if( (pH->htsize==0 && fts3Rehash(pH,8))
116226    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
116227   ){
116228     pH->count = 0;
116229     return data;
116230   }
116231   assert( pH->htsize>0 );
116232   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
116233   if( new_elem==0 ) return data;
116234   if( pH->copyKey && pKey!=0 ){
116235     new_elem->pKey = fts3HashMalloc( nKey );
116236     if( new_elem->pKey==0 ){
116237       fts3HashFree(new_elem);
116238       return data;
116239     }
116240     memcpy((void*)new_elem->pKey, pKey, nKey);
116241   }else{
116242     new_elem->pKey = (void*)pKey;
116243   }
116244   new_elem->nKey = nKey;
116245   pH->count++;
116246   assert( pH->htsize>0 );
116247   assert( (pH->htsize & (pH->htsize-1))==0 );
116248   h = hraw & (pH->htsize-1);
116249   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
116250   new_elem->data = data;
116251   return 0;
116252 }
116253
116254 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116255
116256 /************** End of fts3_hash.c *******************************************/
116257 /************** Begin file fts3_porter.c *************************************/
116258 /*
116259 ** 2006 September 30
116260 **
116261 ** The author disclaims copyright to this source code.  In place of
116262 ** a legal notice, here is a blessing:
116263 **
116264 **    May you do good and not evil.
116265 **    May you find forgiveness for yourself and forgive others.
116266 **    May you share freely, never taking more than you give.
116267 **
116268 *************************************************************************
116269 ** Implementation of the full-text-search tokenizer that implements
116270 ** a Porter stemmer.
116271 */
116272
116273 /*
116274 ** The code in this file is only compiled if:
116275 **
116276 **     * The FTS3 module is being built as an extension
116277 **       (in which case SQLITE_CORE is not defined), or
116278 **
116279 **     * The FTS3 module is being built into the core of
116280 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116281 */
116282 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116283
116284
116285
116286
116287 /*
116288 ** Class derived from sqlite3_tokenizer
116289 */
116290 typedef struct porter_tokenizer {
116291   sqlite3_tokenizer base;      /* Base class */
116292 } porter_tokenizer;
116293
116294 /*
116295 ** Class derived from sqlit3_tokenizer_cursor
116296 */
116297 typedef struct porter_tokenizer_cursor {
116298   sqlite3_tokenizer_cursor base;
116299   const char *zInput;          /* input we are tokenizing */
116300   int nInput;                  /* size of the input */
116301   int iOffset;                 /* current position in zInput */
116302   int iToken;                  /* index of next token to be returned */
116303   char *zToken;                /* storage for current token */
116304   int nAllocated;              /* space allocated to zToken buffer */
116305 } porter_tokenizer_cursor;
116306
116307
116308 /*
116309 ** Create a new tokenizer instance.
116310 */
116311 static int porterCreate(
116312   int argc, const char * const *argv,
116313   sqlite3_tokenizer **ppTokenizer
116314 ){
116315   porter_tokenizer *t;
116316
116317   UNUSED_PARAMETER(argc);
116318   UNUSED_PARAMETER(argv);
116319
116320   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
116321   if( t==NULL ) return SQLITE_NOMEM;
116322   memset(t, 0, sizeof(*t));
116323   *ppTokenizer = &t->base;
116324   return SQLITE_OK;
116325 }
116326
116327 /*
116328 ** Destroy a tokenizer
116329 */
116330 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
116331   sqlite3_free(pTokenizer);
116332   return SQLITE_OK;
116333 }
116334
116335 /*
116336 ** Prepare to begin tokenizing a particular string.  The input
116337 ** string to be tokenized is zInput[0..nInput-1].  A cursor
116338 ** used to incrementally tokenize this string is returned in 
116339 ** *ppCursor.
116340 */
116341 static int porterOpen(
116342   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
116343   const char *zInput, int nInput,        /* String to be tokenized */
116344   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
116345 ){
116346   porter_tokenizer_cursor *c;
116347
116348   UNUSED_PARAMETER(pTokenizer);
116349
116350   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
116351   if( c==NULL ) return SQLITE_NOMEM;
116352
116353   c->zInput = zInput;
116354   if( zInput==0 ){
116355     c->nInput = 0;
116356   }else if( nInput<0 ){
116357     c->nInput = (int)strlen(zInput);
116358   }else{
116359     c->nInput = nInput;
116360   }
116361   c->iOffset = 0;                 /* start tokenizing at the beginning */
116362   c->iToken = 0;
116363   c->zToken = NULL;               /* no space allocated, yet. */
116364   c->nAllocated = 0;
116365
116366   *ppCursor = &c->base;
116367   return SQLITE_OK;
116368 }
116369
116370 /*
116371 ** Close a tokenization cursor previously opened by a call to
116372 ** porterOpen() above.
116373 */
116374 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
116375   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
116376   sqlite3_free(c->zToken);
116377   sqlite3_free(c);
116378   return SQLITE_OK;
116379 }
116380 /*
116381 ** Vowel or consonant
116382 */
116383 static const char cType[] = {
116384    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
116385    1, 1, 1, 2, 1
116386 };
116387
116388 /*
116389 ** isConsonant() and isVowel() determine if their first character in
116390 ** the string they point to is a consonant or a vowel, according
116391 ** to Porter ruls.  
116392 **
116393 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
116394 ** 'Y' is a consonant unless it follows another consonant,
116395 ** in which case it is a vowel.
116396 **
116397 ** In these routine, the letters are in reverse order.  So the 'y' rule
116398 ** is that 'y' is a consonant unless it is followed by another
116399 ** consonent.
116400 */
116401 static int isVowel(const char*);
116402 static int isConsonant(const char *z){
116403   int j;
116404   char x = *z;
116405   if( x==0 ) return 0;
116406   assert( x>='a' && x<='z' );
116407   j = cType[x-'a'];
116408   if( j<2 ) return j;
116409   return z[1]==0 || isVowel(z + 1);
116410 }
116411 static int isVowel(const char *z){
116412   int j;
116413   char x = *z;
116414   if( x==0 ) return 0;
116415   assert( x>='a' && x<='z' );
116416   j = cType[x-'a'];
116417   if( j<2 ) return 1-j;
116418   return isConsonant(z + 1);
116419 }
116420
116421 /*
116422 ** Let any sequence of one or more vowels be represented by V and let
116423 ** C be sequence of one or more consonants.  Then every word can be
116424 ** represented as:
116425 **
116426 **           [C] (VC){m} [V]
116427 **
116428 ** In prose:  A word is an optional consonant followed by zero or
116429 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
116430 ** number of vowel consonant pairs.  This routine computes the value
116431 ** of m for the first i bytes of a word.
116432 **
116433 ** Return true if the m-value for z is 1 or more.  In other words,
116434 ** return true if z contains at least one vowel that is followed
116435 ** by a consonant.
116436 **
116437 ** In this routine z[] is in reverse order.  So we are really looking
116438 ** for an instance of of a consonant followed by a vowel.
116439 */
116440 static int m_gt_0(const char *z){
116441   while( isVowel(z) ){ z++; }
116442   if( *z==0 ) return 0;
116443   while( isConsonant(z) ){ z++; }
116444   return *z!=0;
116445 }
116446
116447 /* Like mgt0 above except we are looking for a value of m which is
116448 ** exactly 1
116449 */
116450 static int m_eq_1(const char *z){
116451   while( isVowel(z) ){ z++; }
116452   if( *z==0 ) return 0;
116453   while( isConsonant(z) ){ z++; }
116454   if( *z==0 ) return 0;
116455   while( isVowel(z) ){ z++; }
116456   if( *z==0 ) return 1;
116457   while( isConsonant(z) ){ z++; }
116458   return *z==0;
116459 }
116460
116461 /* Like mgt0 above except we are looking for a value of m>1 instead
116462 ** or m>0
116463 */
116464 static int m_gt_1(const char *z){
116465   while( isVowel(z) ){ z++; }
116466   if( *z==0 ) return 0;
116467   while( isConsonant(z) ){ z++; }
116468   if( *z==0 ) return 0;
116469   while( isVowel(z) ){ z++; }
116470   if( *z==0 ) return 0;
116471   while( isConsonant(z) ){ z++; }
116472   return *z!=0;
116473 }
116474
116475 /*
116476 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
116477 */
116478 static int hasVowel(const char *z){
116479   while( isConsonant(z) ){ z++; }
116480   return *z!=0;
116481 }
116482
116483 /*
116484 ** Return TRUE if the word ends in a double consonant.
116485 **
116486 ** The text is reversed here. So we are really looking at
116487 ** the first two characters of z[].
116488 */
116489 static int doubleConsonant(const char *z){
116490   return isConsonant(z) && z[0]==z[1];
116491 }
116492
116493 /*
116494 ** Return TRUE if the word ends with three letters which
116495 ** are consonant-vowel-consonent and where the final consonant
116496 ** is not 'w', 'x', or 'y'.
116497 **
116498 ** The word is reversed here.  So we are really checking the
116499 ** first three letters and the first one cannot be in [wxy].
116500 */
116501 static int star_oh(const char *z){
116502   return
116503     isConsonant(z) &&
116504     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
116505     isVowel(z+1) &&
116506     isConsonant(z+2);
116507 }
116508
116509 /*
116510 ** If the word ends with zFrom and xCond() is true for the stem
116511 ** of the word that preceeds the zFrom ending, then change the 
116512 ** ending to zTo.
116513 **
116514 ** The input word *pz and zFrom are both in reverse order.  zTo
116515 ** is in normal order. 
116516 **
116517 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
116518 ** match.  Not that TRUE is returned even if xCond() fails and
116519 ** no substitution occurs.
116520 */
116521 static int stem(
116522   char **pz,             /* The word being stemmed (Reversed) */
116523   const char *zFrom,     /* If the ending matches this... (Reversed) */
116524   const char *zTo,       /* ... change the ending to this (not reversed) */
116525   int (*xCond)(const char*)   /* Condition that must be true */
116526 ){
116527   char *z = *pz;
116528   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
116529   if( *zFrom!=0 ) return 0;
116530   if( xCond && !xCond(z) ) return 1;
116531   while( *zTo ){
116532     *(--z) = *(zTo++);
116533   }
116534   *pz = z;
116535   return 1;
116536 }
116537
116538 /*
116539 ** This is the fallback stemmer used when the porter stemmer is
116540 ** inappropriate.  The input word is copied into the output with
116541 ** US-ASCII case folding.  If the input word is too long (more
116542 ** than 20 bytes if it contains no digits or more than 6 bytes if
116543 ** it contains digits) then word is truncated to 20 or 6 bytes
116544 ** by taking 10 or 3 bytes from the beginning and end.
116545 */
116546 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116547   int i, mx, j;
116548   int hasDigit = 0;
116549   for(i=0; i<nIn; i++){
116550     char c = zIn[i];
116551     if( c>='A' && c<='Z' ){
116552       zOut[i] = c - 'A' + 'a';
116553     }else{
116554       if( c>='0' && c<='9' ) hasDigit = 1;
116555       zOut[i] = c;
116556     }
116557   }
116558   mx = hasDigit ? 3 : 10;
116559   if( nIn>mx*2 ){
116560     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
116561       zOut[j] = zOut[i];
116562     }
116563     i = j;
116564   }
116565   zOut[i] = 0;
116566   *pnOut = i;
116567 }
116568
116569
116570 /*
116571 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
116572 ** zOut is at least big enough to hold nIn bytes.  Write the actual
116573 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
116574 **
116575 ** Any upper-case characters in the US-ASCII character set ([A-Z])
116576 ** are converted to lower case.  Upper-case UTF characters are
116577 ** unchanged.
116578 **
116579 ** Words that are longer than about 20 bytes are stemmed by retaining
116580 ** a few bytes from the beginning and the end of the word.  If the
116581 ** word contains digits, 3 bytes are taken from the beginning and
116582 ** 3 bytes from the end.  For long words without digits, 10 bytes
116583 ** are taken from each end.  US-ASCII case folding still applies.
116584 ** 
116585 ** If the input word contains not digits but does characters not 
116586 ** in [a-zA-Z] then no stemming is attempted and this routine just 
116587 ** copies the input into the input into the output with US-ASCII
116588 ** case folding.
116589 **
116590 ** Stemming never increases the length of the word.  So there is
116591 ** no chance of overflowing the zOut buffer.
116592 */
116593 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
116594   int i, j;
116595   char zReverse[28];
116596   char *z, *z2;
116597   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
116598     /* The word is too big or too small for the porter stemmer.
116599     ** Fallback to the copy stemmer */
116600     copy_stemmer(zIn, nIn, zOut, pnOut);
116601     return;
116602   }
116603   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
116604     char c = zIn[i];
116605     if( c>='A' && c<='Z' ){
116606       zReverse[j] = c + 'a' - 'A';
116607     }else if( c>='a' && c<='z' ){
116608       zReverse[j] = c;
116609     }else{
116610       /* The use of a character not in [a-zA-Z] means that we fallback
116611       ** to the copy stemmer */
116612       copy_stemmer(zIn, nIn, zOut, pnOut);
116613       return;
116614     }
116615   }
116616   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
116617   z = &zReverse[j+1];
116618
116619
116620   /* Step 1a */
116621   if( z[0]=='s' ){
116622     if(
116623      !stem(&z, "sess", "ss", 0) &&
116624      !stem(&z, "sei", "i", 0)  &&
116625      !stem(&z, "ss", "ss", 0)
116626     ){
116627       z++;
116628     }
116629   }
116630
116631   /* Step 1b */  
116632   z2 = z;
116633   if( stem(&z, "dee", "ee", m_gt_0) ){
116634     /* Do nothing.  The work was all in the test */
116635   }else if( 
116636      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
116637       && z!=z2
116638   ){
116639      if( stem(&z, "ta", "ate", 0) ||
116640          stem(&z, "lb", "ble", 0) ||
116641          stem(&z, "zi", "ize", 0) ){
116642        /* Do nothing.  The work was all in the test */
116643      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
116644        z++;
116645      }else if( m_eq_1(z) && star_oh(z) ){
116646        *(--z) = 'e';
116647      }
116648   }
116649
116650   /* Step 1c */
116651   if( z[0]=='y' && hasVowel(z+1) ){
116652     z[0] = 'i';
116653   }
116654
116655   /* Step 2 */
116656   switch( z[1] ){
116657    case 'a':
116658      stem(&z, "lanoita", "ate", m_gt_0) ||
116659      stem(&z, "lanoit", "tion", m_gt_0);
116660      break;
116661    case 'c':
116662      stem(&z, "icne", "ence", m_gt_0) ||
116663      stem(&z, "icna", "ance", m_gt_0);
116664      break;
116665    case 'e':
116666      stem(&z, "rezi", "ize", m_gt_0);
116667      break;
116668    case 'g':
116669      stem(&z, "igol", "log", m_gt_0);
116670      break;
116671    case 'l':
116672      stem(&z, "ilb", "ble", m_gt_0) ||
116673      stem(&z, "illa", "al", m_gt_0) ||
116674      stem(&z, "iltne", "ent", m_gt_0) ||
116675      stem(&z, "ile", "e", m_gt_0) ||
116676      stem(&z, "ilsuo", "ous", m_gt_0);
116677      break;
116678    case 'o':
116679      stem(&z, "noitazi", "ize", m_gt_0) ||
116680      stem(&z, "noita", "ate", m_gt_0) ||
116681      stem(&z, "rota", "ate", m_gt_0);
116682      break;
116683    case 's':
116684      stem(&z, "msila", "al", m_gt_0) ||
116685      stem(&z, "ssenevi", "ive", m_gt_0) ||
116686      stem(&z, "ssenluf", "ful", m_gt_0) ||
116687      stem(&z, "ssensuo", "ous", m_gt_0);
116688      break;
116689    case 't':
116690      stem(&z, "itila", "al", m_gt_0) ||
116691      stem(&z, "itivi", "ive", m_gt_0) ||
116692      stem(&z, "itilib", "ble", m_gt_0);
116693      break;
116694   }
116695
116696   /* Step 3 */
116697   switch( z[0] ){
116698    case 'e':
116699      stem(&z, "etaci", "ic", m_gt_0) ||
116700      stem(&z, "evita", "", m_gt_0)   ||
116701      stem(&z, "ezila", "al", m_gt_0);
116702      break;
116703    case 'i':
116704      stem(&z, "itici", "ic", m_gt_0);
116705      break;
116706    case 'l':
116707      stem(&z, "laci", "ic", m_gt_0) ||
116708      stem(&z, "luf", "", m_gt_0);
116709      break;
116710    case 's':
116711      stem(&z, "ssen", "", m_gt_0);
116712      break;
116713   }
116714
116715   /* Step 4 */
116716   switch( z[1] ){
116717    case 'a':
116718      if( z[0]=='l' && m_gt_1(z+2) ){
116719        z += 2;
116720      }
116721      break;
116722    case 'c':
116723      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
116724        z += 4;
116725      }
116726      break;
116727    case 'e':
116728      if( z[0]=='r' && m_gt_1(z+2) ){
116729        z += 2;
116730      }
116731      break;
116732    case 'i':
116733      if( z[0]=='c' && m_gt_1(z+2) ){
116734        z += 2;
116735      }
116736      break;
116737    case 'l':
116738      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
116739        z += 4;
116740      }
116741      break;
116742    case 'n':
116743      if( z[0]=='t' ){
116744        if( z[2]=='a' ){
116745          if( m_gt_1(z+3) ){
116746            z += 3;
116747          }
116748        }else if( z[2]=='e' ){
116749          stem(&z, "tneme", "", m_gt_1) ||
116750          stem(&z, "tnem", "", m_gt_1) ||
116751          stem(&z, "tne", "", m_gt_1);
116752        }
116753      }
116754      break;
116755    case 'o':
116756      if( z[0]=='u' ){
116757        if( m_gt_1(z+2) ){
116758          z += 2;
116759        }
116760      }else if( z[3]=='s' || z[3]=='t' ){
116761        stem(&z, "noi", "", m_gt_1);
116762      }
116763      break;
116764    case 's':
116765      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
116766        z += 3;
116767      }
116768      break;
116769    case 't':
116770      stem(&z, "eta", "", m_gt_1) ||
116771      stem(&z, "iti", "", m_gt_1);
116772      break;
116773    case 'u':
116774      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
116775        z += 3;
116776      }
116777      break;
116778    case 'v':
116779    case 'z':
116780      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
116781        z += 3;
116782      }
116783      break;
116784   }
116785
116786   /* Step 5a */
116787   if( z[0]=='e' ){
116788     if( m_gt_1(z+1) ){
116789       z++;
116790     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
116791       z++;
116792     }
116793   }
116794
116795   /* Step 5b */
116796   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
116797     z++;
116798   }
116799
116800   /* z[] is now the stemmed word in reverse order.  Flip it back
116801   ** around into forward order and return.
116802   */
116803   *pnOut = i = (int)strlen(z);
116804   zOut[i] = 0;
116805   while( *z ){
116806     zOut[--i] = *(z++);
116807   }
116808 }
116809
116810 /*
116811 ** Characters that can be part of a token.  We assume any character
116812 ** whose value is greater than 0x80 (any UTF character) can be
116813 ** part of a token.  In other words, delimiters all must have
116814 ** values of 0x7f or lower.
116815 */
116816 static const char porterIdChar[] = {
116817 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
116818     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
116819     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
116820     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
116821     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
116822     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
116823 };
116824 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
116825
116826 /*
116827 ** Extract the next token from a tokenization cursor.  The cursor must
116828 ** have been opened by a prior call to porterOpen().
116829 */
116830 static int porterNext(
116831   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
116832   const char **pzToken,               /* OUT: *pzToken is the token text */
116833   int *pnBytes,                       /* OUT: Number of bytes in token */
116834   int *piStartOffset,                 /* OUT: Starting offset of token */
116835   int *piEndOffset,                   /* OUT: Ending offset of token */
116836   int *piPosition                     /* OUT: Position integer of token */
116837 ){
116838   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
116839   const char *z = c->zInput;
116840
116841   while( c->iOffset<c->nInput ){
116842     int iStartOffset, ch;
116843
116844     /* Scan past delimiter characters */
116845     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
116846       c->iOffset++;
116847     }
116848
116849     /* Count non-delimiter characters. */
116850     iStartOffset = c->iOffset;
116851     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
116852       c->iOffset++;
116853     }
116854
116855     if( c->iOffset>iStartOffset ){
116856       int n = c->iOffset-iStartOffset;
116857       if( n>c->nAllocated ){
116858         char *pNew;
116859         c->nAllocated = n+20;
116860         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
116861         if( !pNew ) return SQLITE_NOMEM;
116862         c->zToken = pNew;
116863       }
116864       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
116865       *pzToken = c->zToken;
116866       *piStartOffset = iStartOffset;
116867       *piEndOffset = c->iOffset;
116868       *piPosition = c->iToken++;
116869       return SQLITE_OK;
116870     }
116871   }
116872   return SQLITE_DONE;
116873 }
116874
116875 /*
116876 ** The set of routines that implement the porter-stemmer tokenizer
116877 */
116878 static const sqlite3_tokenizer_module porterTokenizerModule = {
116879   0,
116880   porterCreate,
116881   porterDestroy,
116882   porterOpen,
116883   porterClose,
116884   porterNext,
116885 };
116886
116887 /*
116888 ** Allocate a new porter tokenizer.  Return a pointer to the new
116889 ** tokenizer in *ppModule
116890 */
116891 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
116892   sqlite3_tokenizer_module const**ppModule
116893 ){
116894   *ppModule = &porterTokenizerModule;
116895 }
116896
116897 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116898
116899 /************** End of fts3_porter.c *****************************************/
116900 /************** Begin file fts3_tokenizer.c **********************************/
116901 /*
116902 ** 2007 June 22
116903 **
116904 ** The author disclaims copyright to this source code.  In place of
116905 ** a legal notice, here is a blessing:
116906 **
116907 **    May you do good and not evil.
116908 **    May you find forgiveness for yourself and forgive others.
116909 **    May you share freely, never taking more than you give.
116910 **
116911 ******************************************************************************
116912 **
116913 ** This is part of an SQLite module implementing full-text search.
116914 ** This particular file implements the generic tokenizer interface.
116915 */
116916
116917 /*
116918 ** The code in this file is only compiled if:
116919 **
116920 **     * The FTS3 module is being built as an extension
116921 **       (in which case SQLITE_CORE is not defined), or
116922 **
116923 **     * The FTS3 module is being built into the core of
116924 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116925 */
116926 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116927
116928 #ifndef SQLITE_CORE
116929   SQLITE_EXTENSION_INIT1
116930 #endif
116931
116932
116933 /*
116934 ** Implementation of the SQL scalar function for accessing the underlying 
116935 ** hash table. This function may be called as follows:
116936 **
116937 **   SELECT <function-name>(<key-name>);
116938 **   SELECT <function-name>(<key-name>, <pointer>);
116939 **
116940 ** where <function-name> is the name passed as the second argument
116941 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
116942 **
116943 ** If the <pointer> argument is specified, it must be a blob value
116944 ** containing a pointer to be stored as the hash data corresponding
116945 ** to the string <key-name>. If <pointer> is not specified, then
116946 ** the string <key-name> must already exist in the has table. Otherwise,
116947 ** an error is returned.
116948 **
116949 ** Whether or not the <pointer> argument is specified, the value returned
116950 ** is a blob containing the pointer stored as the hash data corresponding
116951 ** to string <key-name> (after the hash-table is updated, if applicable).
116952 */
116953 static void scalarFunc(
116954   sqlite3_context *context,
116955   int argc,
116956   sqlite3_value **argv
116957 ){
116958   Fts3Hash *pHash;
116959   void *pPtr = 0;
116960   const unsigned char *zName;
116961   int nName;
116962
116963   assert( argc==1 || argc==2 );
116964
116965   pHash = (Fts3Hash *)sqlite3_user_data(context);
116966
116967   zName = sqlite3_value_text(argv[0]);
116968   nName = sqlite3_value_bytes(argv[0])+1;
116969
116970   if( argc==2 ){
116971     void *pOld;
116972     int n = sqlite3_value_bytes(argv[1]);
116973     if( n!=sizeof(pPtr) ){
116974       sqlite3_result_error(context, "argument type mismatch", -1);
116975       return;
116976     }
116977     pPtr = *(void **)sqlite3_value_blob(argv[1]);
116978     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
116979     if( pOld==pPtr ){
116980       sqlite3_result_error(context, "out of memory", -1);
116981       return;
116982     }
116983   }else{
116984     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
116985     if( !pPtr ){
116986       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
116987       sqlite3_result_error(context, zErr, -1);
116988       sqlite3_free(zErr);
116989       return;
116990     }
116991   }
116992
116993   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
116994 }
116995
116996 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
116997   static const char isFtsIdChar[] = {
116998       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
116999       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
117000       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
117001       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
117002       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
117003       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
117004       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
117005       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
117006   };
117007   return (c&0x80 || isFtsIdChar[(int)(c)]);
117008 }
117009
117010 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
117011   const char *z1;
117012   const char *z2 = 0;
117013
117014   /* Find the start of the next token. */
117015   z1 = zStr;
117016   while( z2==0 ){
117017     char c = *z1;
117018     switch( c ){
117019       case '\0': return 0;        /* No more tokens here */
117020       case '\'':
117021       case '"':
117022       case '`': {
117023         z2 = z1;
117024         while( *++z2 && (*z2!=c || *++z2==c) );
117025         break;
117026       }
117027       case '[':
117028         z2 = &z1[1];
117029         while( *z2 && z2[0]!=']' ) z2++;
117030         if( *z2 ) z2++;
117031         break;
117032
117033       default:
117034         if( sqlite3Fts3IsIdChar(*z1) ){
117035           z2 = &z1[1];
117036           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
117037         }else{
117038           z1++;
117039         }
117040     }
117041   }
117042
117043   *pn = (int)(z2-z1);
117044   return z1;
117045 }
117046
117047 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
117048   Fts3Hash *pHash,                /* Tokenizer hash table */
117049   const char *zArg,               /* Tokenizer name */
117050   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
117051   char **pzErr                    /* OUT: Set to malloced error message */
117052 ){
117053   int rc;
117054   char *z = (char *)zArg;
117055   int n;
117056   char *zCopy;
117057   char *zEnd;                     /* Pointer to nul-term of zCopy */
117058   sqlite3_tokenizer_module *m;
117059
117060   zCopy = sqlite3_mprintf("%s", zArg);
117061   if( !zCopy ) return SQLITE_NOMEM;
117062   zEnd = &zCopy[strlen(zCopy)];
117063
117064   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
117065   z[n] = '\0';
117066   sqlite3Fts3Dequote(z);
117067
117068   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
117069   if( !m ){
117070     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
117071     rc = SQLITE_ERROR;
117072   }else{
117073     char const **aArg = 0;
117074     int iArg = 0;
117075     z = &z[n+1];
117076     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
117077       int nNew = sizeof(char *)*(iArg+1);
117078       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
117079       if( !aNew ){
117080         sqlite3_free(zCopy);
117081         sqlite3_free((void *)aArg);
117082         return SQLITE_NOMEM;
117083       }
117084       aArg = aNew;
117085       aArg[iArg++] = z;
117086       z[n] = '\0';
117087       sqlite3Fts3Dequote(z);
117088       z = &z[n+1];
117089     }
117090     rc = m->xCreate(iArg, aArg, ppTok);
117091     assert( rc!=SQLITE_OK || *ppTok );
117092     if( rc!=SQLITE_OK ){
117093       *pzErr = sqlite3_mprintf("unknown tokenizer");
117094     }else{
117095       (*ppTok)->pModule = m; 
117096     }
117097     sqlite3_free((void *)aArg);
117098   }
117099
117100   sqlite3_free(zCopy);
117101   return rc;
117102 }
117103
117104
117105 #ifdef SQLITE_TEST
117106
117107
117108 /*
117109 ** Implementation of a special SQL scalar function for testing tokenizers 
117110 ** designed to be used in concert with the Tcl testing framework. This
117111 ** function must be called with two arguments:
117112 **
117113 **   SELECT <function-name>(<key-name>, <input-string>);
117114 **   SELECT <function-name>(<key-name>, <pointer>);
117115 **
117116 ** where <function-name> is the name passed as the second argument
117117 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
117118 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
117119 **
117120 ** The return value is a string that may be interpreted as a Tcl
117121 ** list. For each token in the <input-string>, three elements are
117122 ** added to the returned list. The first is the token position, the 
117123 ** second is the token text (folded, stemmed, etc.) and the third is the
117124 ** substring of <input-string> associated with the token. For example, 
117125 ** using the built-in "simple" tokenizer:
117126 **
117127 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
117128 **
117129 ** will return the string:
117130 **
117131 **   "{0 i I 1 dont don't 2 see see 3 how how}"
117132 **   
117133 */
117134 static void testFunc(
117135   sqlite3_context *context,
117136   int argc,
117137   sqlite3_value **argv
117138 ){
117139   Fts3Hash *pHash;
117140   sqlite3_tokenizer_module *p;
117141   sqlite3_tokenizer *pTokenizer = 0;
117142   sqlite3_tokenizer_cursor *pCsr = 0;
117143
117144   const char *zErr = 0;
117145
117146   const char *zName;
117147   int nName;
117148   const char *zInput;
117149   int nInput;
117150
117151   const char *zArg = 0;
117152
117153   const char *zToken;
117154   int nToken;
117155   int iStart;
117156   int iEnd;
117157   int iPos;
117158
117159   Tcl_Obj *pRet;
117160
117161   assert( argc==2 || argc==3 );
117162
117163   nName = sqlite3_value_bytes(argv[0]);
117164   zName = (const char *)sqlite3_value_text(argv[0]);
117165   nInput = sqlite3_value_bytes(argv[argc-1]);
117166   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
117167
117168   if( argc==3 ){
117169     zArg = (const char *)sqlite3_value_text(argv[1]);
117170   }
117171
117172   pHash = (Fts3Hash *)sqlite3_user_data(context);
117173   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
117174
117175   if( !p ){
117176     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
117177     sqlite3_result_error(context, zErr, -1);
117178     sqlite3_free(zErr);
117179     return;
117180   }
117181
117182   pRet = Tcl_NewObj();
117183   Tcl_IncrRefCount(pRet);
117184
117185   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
117186     zErr = "error in xCreate()";
117187     goto finish;
117188   }
117189   pTokenizer->pModule = p;
117190   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
117191     zErr = "error in xOpen()";
117192     goto finish;
117193   }
117194   pCsr->pTokenizer = pTokenizer;
117195
117196   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
117197     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
117198     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117199     zToken = &zInput[iStart];
117200     nToken = iEnd-iStart;
117201     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
117202   }
117203
117204   if( SQLITE_OK!=p->xClose(pCsr) ){
117205     zErr = "error in xClose()";
117206     goto finish;
117207   }
117208   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
117209     zErr = "error in xDestroy()";
117210     goto finish;
117211   }
117212
117213 finish:
117214   if( zErr ){
117215     sqlite3_result_error(context, zErr, -1);
117216   }else{
117217     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
117218   }
117219   Tcl_DecrRefCount(pRet);
117220 }
117221
117222 static
117223 int registerTokenizer(
117224   sqlite3 *db, 
117225   char *zName, 
117226   const sqlite3_tokenizer_module *p
117227 ){
117228   int rc;
117229   sqlite3_stmt *pStmt;
117230   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
117231
117232   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117233   if( rc!=SQLITE_OK ){
117234     return rc;
117235   }
117236
117237   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117238   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
117239   sqlite3_step(pStmt);
117240
117241   return sqlite3_finalize(pStmt);
117242 }
117243
117244 static
117245 int queryTokenizer(
117246   sqlite3 *db, 
117247   char *zName,  
117248   const sqlite3_tokenizer_module **pp
117249 ){
117250   int rc;
117251   sqlite3_stmt *pStmt;
117252   const char zSql[] = "SELECT fts3_tokenizer(?)";
117253
117254   *pp = 0;
117255   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117256   if( rc!=SQLITE_OK ){
117257     return rc;
117258   }
117259
117260   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117261   if( SQLITE_ROW==sqlite3_step(pStmt) ){
117262     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
117263       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
117264     }
117265   }
117266
117267   return sqlite3_finalize(pStmt);
117268 }
117269
117270 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117271
117272 /*
117273 ** Implementation of the scalar function fts3_tokenizer_internal_test().
117274 ** This function is used for testing only, it is not included in the
117275 ** build unless SQLITE_TEST is defined.
117276 **
117277 ** The purpose of this is to test that the fts3_tokenizer() function
117278 ** can be used as designed by the C-code in the queryTokenizer and
117279 ** registerTokenizer() functions above. These two functions are repeated
117280 ** in the README.tokenizer file as an example, so it is important to
117281 ** test them.
117282 **
117283 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
117284 ** function with no arguments. An assert() will fail if a problem is
117285 ** detected. i.e.:
117286 **
117287 **     SELECT fts3_tokenizer_internal_test();
117288 **
117289 */
117290 static void intTestFunc(
117291   sqlite3_context *context,
117292   int argc,
117293   sqlite3_value **argv
117294 ){
117295   int rc;
117296   const sqlite3_tokenizer_module *p1;
117297   const sqlite3_tokenizer_module *p2;
117298   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
117299
117300   UNUSED_PARAMETER(argc);
117301   UNUSED_PARAMETER(argv);
117302
117303   /* Test the query function */
117304   sqlite3Fts3SimpleTokenizerModule(&p1);
117305   rc = queryTokenizer(db, "simple", &p2);
117306   assert( rc==SQLITE_OK );
117307   assert( p1==p2 );
117308   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117309   assert( rc==SQLITE_ERROR );
117310   assert( p2==0 );
117311   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
117312
117313   /* Test the storage function */
117314   rc = registerTokenizer(db, "nosuchtokenizer", p1);
117315   assert( rc==SQLITE_OK );
117316   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
117317   assert( rc==SQLITE_OK );
117318   assert( p2==p1 );
117319
117320   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
117321 }
117322
117323 #endif
117324
117325 /*
117326 ** Set up SQL objects in database db used to access the contents of
117327 ** the hash table pointed to by argument pHash. The hash table must
117328 ** been initialised to use string keys, and to take a private copy 
117329 ** of the key when a value is inserted. i.e. by a call similar to:
117330 **
117331 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
117332 **
117333 ** This function adds a scalar function (see header comment above
117334 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
117335 ** defined at compilation time, a temporary virtual table (see header 
117336 ** comment above struct HashTableVtab) to the database schema. Both 
117337 ** provide read/write access to the contents of *pHash.
117338 **
117339 ** The third argument to this function, zName, is used as the name
117340 ** of both the scalar and, if created, the virtual table.
117341 */
117342 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
117343   sqlite3 *db, 
117344   Fts3Hash *pHash, 
117345   const char *zName
117346 ){
117347   int rc = SQLITE_OK;
117348   void *p = (void *)pHash;
117349   const int any = SQLITE_ANY;
117350
117351 #ifdef SQLITE_TEST
117352   char *zTest = 0;
117353   char *zTest2 = 0;
117354   void *pdb = (void *)db;
117355   zTest = sqlite3_mprintf("%s_test", zName);
117356   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
117357   if( !zTest || !zTest2 ){
117358     rc = SQLITE_NOMEM;
117359   }
117360 #endif
117361
117362   if( SQLITE_OK==rc ){
117363     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
117364   }
117365   if( SQLITE_OK==rc ){
117366     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
117367   }
117368 #ifdef SQLITE_TEST
117369   if( SQLITE_OK==rc ){
117370     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
117371   }
117372   if( SQLITE_OK==rc ){
117373     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
117374   }
117375   if( SQLITE_OK==rc ){
117376     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
117377   }
117378 #endif
117379
117380 #ifdef SQLITE_TEST
117381   sqlite3_free(zTest);
117382   sqlite3_free(zTest2);
117383 #endif
117384
117385   return rc;
117386 }
117387
117388 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117389
117390 /************** End of fts3_tokenizer.c **************************************/
117391 /************** Begin file fts3_tokenizer1.c *********************************/
117392 /*
117393 ** 2006 Oct 10
117394 **
117395 ** The author disclaims copyright to this source code.  In place of
117396 ** a legal notice, here is a blessing:
117397 **
117398 **    May you do good and not evil.
117399 **    May you find forgiveness for yourself and forgive others.
117400 **    May you share freely, never taking more than you give.
117401 **
117402 ******************************************************************************
117403 **
117404 ** Implementation of the "simple" full-text-search tokenizer.
117405 */
117406
117407 /*
117408 ** The code in this file is only compiled if:
117409 **
117410 **     * The FTS3 module is being built as an extension
117411 **       (in which case SQLITE_CORE is not defined), or
117412 **
117413 **     * The FTS3 module is being built into the core of
117414 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117415 */
117416 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117417
117418
117419
117420
117421 typedef struct simple_tokenizer {
117422   sqlite3_tokenizer base;
117423   char delim[128];             /* flag ASCII delimiters */
117424 } simple_tokenizer;
117425
117426 typedef struct simple_tokenizer_cursor {
117427   sqlite3_tokenizer_cursor base;
117428   const char *pInput;          /* input we are tokenizing */
117429   int nBytes;                  /* size of the input */
117430   int iOffset;                 /* current position in pInput */
117431   int iToken;                  /* index of next token to be returned */
117432   char *pToken;                /* storage for current token */
117433   int nTokenAllocated;         /* space allocated to zToken buffer */
117434 } simple_tokenizer_cursor;
117435
117436
117437 static int simpleDelim(simple_tokenizer *t, unsigned char c){
117438   return c<0x80 && t->delim[c];
117439 }
117440 static int fts3_isalnum(int x){
117441   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
117442 }
117443
117444 /*
117445 ** Create a new tokenizer instance.
117446 */
117447 static int simpleCreate(
117448   int argc, const char * const *argv,
117449   sqlite3_tokenizer **ppTokenizer
117450 ){
117451   simple_tokenizer *t;
117452
117453   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
117454   if( t==NULL ) return SQLITE_NOMEM;
117455   memset(t, 0, sizeof(*t));
117456
117457   /* TODO(shess) Delimiters need to remain the same from run to run,
117458   ** else we need to reindex.  One solution would be a meta-table to
117459   ** track such information in the database, then we'd only want this
117460   ** information on the initial create.
117461   */
117462   if( argc>1 ){
117463     int i, n = (int)strlen(argv[1]);
117464     for(i=0; i<n; i++){
117465       unsigned char ch = argv[1][i];
117466       /* We explicitly don't support UTF-8 delimiters for now. */
117467       if( ch>=0x80 ){
117468         sqlite3_free(t);
117469         return SQLITE_ERROR;
117470       }
117471       t->delim[ch] = 1;
117472     }
117473   } else {
117474     /* Mark non-alphanumeric ASCII characters as delimiters */
117475     int i;
117476     for(i=1; i<0x80; i++){
117477       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
117478     }
117479   }
117480
117481   *ppTokenizer = &t->base;
117482   return SQLITE_OK;
117483 }
117484
117485 /*
117486 ** Destroy a tokenizer
117487 */
117488 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
117489   sqlite3_free(pTokenizer);
117490   return SQLITE_OK;
117491 }
117492
117493 /*
117494 ** Prepare to begin tokenizing a particular string.  The input
117495 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
117496 ** used to incrementally tokenize this string is returned in 
117497 ** *ppCursor.
117498 */
117499 static int simpleOpen(
117500   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
117501   const char *pInput, int nBytes,        /* String to be tokenized */
117502   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
117503 ){
117504   simple_tokenizer_cursor *c;
117505
117506   UNUSED_PARAMETER(pTokenizer);
117507
117508   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
117509   if( c==NULL ) return SQLITE_NOMEM;
117510
117511   c->pInput = pInput;
117512   if( pInput==0 ){
117513     c->nBytes = 0;
117514   }else if( nBytes<0 ){
117515     c->nBytes = (int)strlen(pInput);
117516   }else{
117517     c->nBytes = nBytes;
117518   }
117519   c->iOffset = 0;                 /* start tokenizing at the beginning */
117520   c->iToken = 0;
117521   c->pToken = NULL;               /* no space allocated, yet. */
117522   c->nTokenAllocated = 0;
117523
117524   *ppCursor = &c->base;
117525   return SQLITE_OK;
117526 }
117527
117528 /*
117529 ** Close a tokenization cursor previously opened by a call to
117530 ** simpleOpen() above.
117531 */
117532 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
117533   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117534   sqlite3_free(c->pToken);
117535   sqlite3_free(c);
117536   return SQLITE_OK;
117537 }
117538
117539 /*
117540 ** Extract the next token from a tokenization cursor.  The cursor must
117541 ** have been opened by a prior call to simpleOpen().
117542 */
117543 static int simpleNext(
117544   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
117545   const char **ppToken,               /* OUT: *ppToken is the token text */
117546   int *pnBytes,                       /* OUT: Number of bytes in token */
117547   int *piStartOffset,                 /* OUT: Starting offset of token */
117548   int *piEndOffset,                   /* OUT: Ending offset of token */
117549   int *piPosition                     /* OUT: Position integer of token */
117550 ){
117551   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
117552   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
117553   unsigned char *p = (unsigned char *)c->pInput;
117554
117555   while( c->iOffset<c->nBytes ){
117556     int iStartOffset;
117557
117558     /* Scan past delimiter characters */
117559     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
117560       c->iOffset++;
117561     }
117562
117563     /* Count non-delimiter characters. */
117564     iStartOffset = c->iOffset;
117565     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
117566       c->iOffset++;
117567     }
117568
117569     if( c->iOffset>iStartOffset ){
117570       int i, n = c->iOffset-iStartOffset;
117571       if( n>c->nTokenAllocated ){
117572         char *pNew;
117573         c->nTokenAllocated = n+20;
117574         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
117575         if( !pNew ) return SQLITE_NOMEM;
117576         c->pToken = pNew;
117577       }
117578       for(i=0; i<n; i++){
117579         /* TODO(shess) This needs expansion to handle UTF-8
117580         ** case-insensitivity.
117581         */
117582         unsigned char ch = p[iStartOffset+i];
117583         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
117584       }
117585       *ppToken = c->pToken;
117586       *pnBytes = n;
117587       *piStartOffset = iStartOffset;
117588       *piEndOffset = c->iOffset;
117589       *piPosition = c->iToken++;
117590
117591       return SQLITE_OK;
117592     }
117593   }
117594   return SQLITE_DONE;
117595 }
117596
117597 /*
117598 ** The set of routines that implement the simple tokenizer
117599 */
117600 static const sqlite3_tokenizer_module simpleTokenizerModule = {
117601   0,
117602   simpleCreate,
117603   simpleDestroy,
117604   simpleOpen,
117605   simpleClose,
117606   simpleNext,
117607 };
117608
117609 /*
117610 ** Allocate a new simple tokenizer.  Return a pointer to the new
117611 ** tokenizer in *ppModule
117612 */
117613 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
117614   sqlite3_tokenizer_module const**ppModule
117615 ){
117616   *ppModule = &simpleTokenizerModule;
117617 }
117618
117619 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117620
117621 /************** End of fts3_tokenizer1.c *************************************/
117622 /************** Begin file fts3_write.c **************************************/
117623 /*
117624 ** 2009 Oct 23
117625 **
117626 ** The author disclaims copyright to this source code.  In place of
117627 ** a legal notice, here is a blessing:
117628 **
117629 **    May you do good and not evil.
117630 **    May you find forgiveness for yourself and forgive others.
117631 **    May you share freely, never taking more than you give.
117632 **
117633 ******************************************************************************
117634 **
117635 ** This file is part of the SQLite FTS3 extension module. Specifically,
117636 ** this file contains code to insert, update and delete rows from FTS3
117637 ** tables. It also contains code to merge FTS3 b-tree segments. Some
117638 ** of the sub-routines used to merge segments are also used by the query 
117639 ** code in fts3.c.
117640 */
117641
117642 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117643
117644
117645 /*
117646 ** When full-text index nodes are loaded from disk, the buffer that they
117647 ** are loaded into has the following number of bytes of padding at the end 
117648 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
117649 ** of 920 bytes is allocated for it.
117650 **
117651 ** This means that if we have a pointer into a buffer containing node data,
117652 ** it is always safe to read up to two varints from it without risking an
117653 ** overread, even if the node data is corrupted.
117654 */
117655 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
117656
117657 typedef struct PendingList PendingList;
117658 typedef struct SegmentNode SegmentNode;
117659 typedef struct SegmentWriter SegmentWriter;
117660
117661 /*
117662 ** Data structure used while accumulating terms in the pending-terms hash
117663 ** table. The hash table entry maps from term (a string) to a malloc'd
117664 ** instance of this structure.
117665 */
117666 struct PendingList {
117667   int nData;
117668   char *aData;
117669   int nSpace;
117670   sqlite3_int64 iLastDocid;
117671   sqlite3_int64 iLastCol;
117672   sqlite3_int64 iLastPos;
117673 };
117674
117675
117676 /*
117677 ** Each cursor has a (possibly empty) linked list of the following objects.
117678 */
117679 struct Fts3DeferredToken {
117680   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
117681   int iCol;                       /* Column token must occur in */
117682   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
117683   PendingList *pList;             /* Doclist is assembled here */
117684 };
117685
117686 /*
117687 ** An instance of this structure is used to iterate through the terms on
117688 ** a contiguous set of segment b-tree leaf nodes. Although the details of
117689 ** this structure are only manipulated by code in this file, opaque handles
117690 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
117691 ** terms when querying the full-text index. See functions:
117692 **
117693 **   sqlite3Fts3SegReaderNew()
117694 **   sqlite3Fts3SegReaderFree()
117695 **   sqlite3Fts3SegReaderCost()
117696 **   sqlite3Fts3SegReaderIterate()
117697 **
117698 ** Methods used to manipulate Fts3SegReader structures:
117699 **
117700 **   fts3SegReaderNext()
117701 **   fts3SegReaderFirstDocid()
117702 **   fts3SegReaderNextDocid()
117703 */
117704 struct Fts3SegReader {
117705   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
117706
117707   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
117708   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
117709   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
117710   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
117711
117712   char *aNode;                    /* Pointer to node data (or NULL) */
117713   int nNode;                      /* Size of buffer at aNode (or 0) */
117714   Fts3HashElem **ppNextElem;
117715
117716   /* Variables set by fts3SegReaderNext(). These may be read directly
117717   ** by the caller. They are valid from the time SegmentReaderNew() returns
117718   ** until SegmentReaderNext() returns something other than SQLITE_OK
117719   ** (i.e. SQLITE_DONE).
117720   */
117721   int nTerm;                      /* Number of bytes in current term */
117722   char *zTerm;                    /* Pointer to current term */
117723   int nTermAlloc;                 /* Allocated size of zTerm buffer */
117724   char *aDoclist;                 /* Pointer to doclist of current entry */
117725   int nDoclist;                   /* Size of doclist in current entry */
117726
117727   /* The following variables are used to iterate through the current doclist */
117728   char *pOffsetList;
117729   sqlite3_int64 iDocid;
117730 };
117731
117732 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
117733 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
117734
117735 /*
117736 ** An instance of this structure is used to create a segment b-tree in the
117737 ** database. The internal details of this type are only accessed by the
117738 ** following functions:
117739 **
117740 **   fts3SegWriterAdd()
117741 **   fts3SegWriterFlush()
117742 **   fts3SegWriterFree()
117743 */
117744 struct SegmentWriter {
117745   SegmentNode *pTree;             /* Pointer to interior tree structure */
117746   sqlite3_int64 iFirst;           /* First slot in %_segments written */
117747   sqlite3_int64 iFree;            /* Next free slot in %_segments */
117748   char *zTerm;                    /* Pointer to previous term buffer */
117749   int nTerm;                      /* Number of bytes in zTerm */
117750   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
117751   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
117752   int nSize;                      /* Size of allocation at aData */
117753   int nData;                      /* Bytes of data in aData */
117754   char *aData;                    /* Pointer to block from malloc() */
117755 };
117756
117757 /*
117758 ** Type SegmentNode is used by the following three functions to create
117759 ** the interior part of the segment b+-tree structures (everything except
117760 ** the leaf nodes). These functions and type are only ever used by code
117761 ** within the fts3SegWriterXXX() family of functions described above.
117762 **
117763 **   fts3NodeAddTerm()
117764 **   fts3NodeWrite()
117765 **   fts3NodeFree()
117766 */
117767 struct SegmentNode {
117768   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
117769   SegmentNode *pRight;            /* Pointer to right-sibling */
117770   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
117771   int nEntry;                     /* Number of terms written to node so far */
117772   char *zTerm;                    /* Pointer to previous term buffer */
117773   int nTerm;                      /* Number of bytes in zTerm */
117774   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
117775   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
117776   int nData;                      /* Bytes of valid data so far */
117777   char *aData;                    /* Node data */
117778 };
117779
117780 /*
117781 ** Valid values for the second argument to fts3SqlStmt().
117782 */
117783 #define SQL_DELETE_CONTENT             0
117784 #define SQL_IS_EMPTY                   1
117785 #define SQL_DELETE_ALL_CONTENT         2 
117786 #define SQL_DELETE_ALL_SEGMENTS        3
117787 #define SQL_DELETE_ALL_SEGDIR          4
117788 #define SQL_DELETE_ALL_DOCSIZE         5
117789 #define SQL_DELETE_ALL_STAT            6
117790 #define SQL_SELECT_CONTENT_BY_ROWID    7
117791 #define SQL_NEXT_SEGMENT_INDEX         8
117792 #define SQL_INSERT_SEGMENTS            9
117793 #define SQL_NEXT_SEGMENTS_ID          10
117794 #define SQL_INSERT_SEGDIR             11
117795 #define SQL_SELECT_LEVEL              12
117796 #define SQL_SELECT_ALL_LEVEL          13
117797 #define SQL_SELECT_LEVEL_COUNT        14
117798 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
117799 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
117800 #define SQL_DELETE_SEGMENTS_RANGE     17
117801 #define SQL_CONTENT_INSERT            18
117802 #define SQL_DELETE_DOCSIZE            19
117803 #define SQL_REPLACE_DOCSIZE           20
117804 #define SQL_SELECT_DOCSIZE            21
117805 #define SQL_SELECT_DOCTOTAL           22
117806 #define SQL_REPLACE_DOCTOTAL          23
117807
117808 /*
117809 ** This function is used to obtain an SQLite prepared statement handle
117810 ** for the statement identified by the second argument. If successful,
117811 ** *pp is set to the requested statement handle and SQLITE_OK returned.
117812 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
117813 **
117814 ** If argument apVal is not NULL, then it must point to an array with
117815 ** at least as many entries as the requested statement has bound 
117816 ** parameters. The values are bound to the statements parameters before
117817 ** returning.
117818 */
117819 static int fts3SqlStmt(
117820   Fts3Table *p,                   /* Virtual table handle */
117821   int eStmt,                      /* One of the SQL_XXX constants above */
117822   sqlite3_stmt **pp,              /* OUT: Statement handle */
117823   sqlite3_value **apVal           /* Values to bind to statement */
117824 ){
117825   const char *azSql[] = {
117826 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
117827 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
117828 /* 2  */  "DELETE FROM %Q.'%q_content'",
117829 /* 3  */  "DELETE FROM %Q.'%q_segments'",
117830 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
117831 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
117832 /* 6  */  "DELETE FROM %Q.'%q_stat'",
117833 /* 7  */  "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
117834 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
117835 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
117836 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
117837 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
117838
117839           /* Return segments in order from oldest to newest.*/ 
117840 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
117841             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
117842 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
117843             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
117844
117845 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
117846 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
117847
117848 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
117849 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
117850 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
117851 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
117852 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
117853 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
117854 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
117855 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
117856   };
117857   int rc = SQLITE_OK;
117858   sqlite3_stmt *pStmt;
117859
117860   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
117861   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
117862   
117863   pStmt = p->aStmt[eStmt];
117864   if( !pStmt ){
117865     char *zSql;
117866     if( eStmt==SQL_CONTENT_INSERT ){
117867       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
117868     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
117869       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
117870     }else{
117871       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
117872     }
117873     if( !zSql ){
117874       rc = SQLITE_NOMEM;
117875     }else{
117876       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
117877       sqlite3_free(zSql);
117878       assert( rc==SQLITE_OK || pStmt==0 );
117879       p->aStmt[eStmt] = pStmt;
117880     }
117881   }
117882   if( apVal ){
117883     int i;
117884     int nParam = sqlite3_bind_parameter_count(pStmt);
117885     for(i=0; rc==SQLITE_OK && i<nParam; i++){
117886       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
117887     }
117888   }
117889   *pp = pStmt;
117890   return rc;
117891 }
117892
117893 static int fts3SelectDocsize(
117894   Fts3Table *pTab,                /* FTS3 table handle */
117895   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
117896   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
117897   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117898 ){
117899   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
117900   int rc;                         /* Return code */
117901
117902   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
117903
117904   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
117905   if( rc==SQLITE_OK ){
117906     if( eStmt==SQL_SELECT_DOCSIZE ){
117907       sqlite3_bind_int64(pStmt, 1, iDocid);
117908     }
117909     rc = sqlite3_step(pStmt);
117910     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
117911       rc = sqlite3_reset(pStmt);
117912       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
117913       pStmt = 0;
117914     }else{
117915       rc = SQLITE_OK;
117916     }
117917   }
117918
117919   *ppStmt = pStmt;
117920   return rc;
117921 }
117922
117923 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
117924   Fts3Table *pTab,                /* Fts3 table handle */
117925   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117926 ){
117927   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
117928 }
117929
117930 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
117931   Fts3Table *pTab,                /* Fts3 table handle */
117932   sqlite3_int64 iDocid,           /* Docid to read size data for */
117933   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
117934 ){
117935   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
117936 }
117937
117938 /*
117939 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
117940 ** array apVal[] to the SQL statement identified by eStmt, the statement
117941 ** is executed.
117942 **
117943 ** Returns SQLITE_OK if the statement is successfully executed, or an
117944 ** SQLite error code otherwise.
117945 */
117946 static void fts3SqlExec(
117947   int *pRC,                /* Result code */
117948   Fts3Table *p,            /* The FTS3 table */
117949   int eStmt,               /* Index of statement to evaluate */
117950   sqlite3_value **apVal    /* Parameters to bind */
117951 ){
117952   sqlite3_stmt *pStmt;
117953   int rc;
117954   if( *pRC ) return;
117955   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
117956   if( rc==SQLITE_OK ){
117957     sqlite3_step(pStmt);
117958     rc = sqlite3_reset(pStmt);
117959   }
117960   *pRC = rc;
117961 }
117962
117963
117964 /*
117965 ** This function ensures that the caller has obtained a shared-cache
117966 ** table-lock on the %_content table. This is required before reading
117967 ** data from the fts3 table. If this lock is not acquired first, then
117968 ** the caller may end up holding read-locks on the %_segments and %_segdir
117969 ** tables, but no read-lock on the %_content table. If this happens 
117970 ** a second connection will be able to write to the fts3 table, but
117971 ** attempting to commit those writes might return SQLITE_LOCKED or
117972 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
117973 ** write-locks on the %_segments and %_segdir ** tables). 
117974 **
117975 ** We try to avoid this because if FTS3 returns any error when committing
117976 ** a transaction, the whole transaction will be rolled back. And this is
117977 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
117978 ** still happen if the user reads data directly from the %_segments or
117979 ** %_segdir tables instead of going through FTS3 though.
117980 */
117981 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
117982   int rc;                         /* Return code */
117983   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
117984
117985   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
117986   if( rc==SQLITE_OK ){
117987     sqlite3_bind_null(pStmt, 1);
117988     sqlite3_step(pStmt);
117989     rc = sqlite3_reset(pStmt);
117990   }
117991   return rc;
117992 }
117993
117994 /*
117995 ** Set *ppStmt to a statement handle that may be used to iterate through
117996 ** all rows in the %_segdir table, from oldest to newest. If successful,
117997 ** return SQLITE_OK. If an error occurs while preparing the statement, 
117998 ** return an SQLite error code.
117999 **
118000 ** There is only ever one instance of this SQL statement compiled for
118001 ** each FTS3 table.
118002 **
118003 ** The statement returns the following columns from the %_segdir table:
118004 **
118005 **   0: idx
118006 **   1: start_block
118007 **   2: leaves_end_block
118008 **   3: end_block
118009 **   4: root
118010 */
118011 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
118012   int rc;
118013   sqlite3_stmt *pStmt = 0;
118014   if( iLevel<0 ){
118015     rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
118016   }else{
118017     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
118018     if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
118019   }
118020   *ppStmt = pStmt;
118021   return rc;
118022 }
118023
118024
118025 /*
118026 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
118027 ** if successful, or an SQLite error code otherwise.
118028 **
118029 ** This function also serves to allocate the PendingList structure itself.
118030 ** For example, to create a new PendingList structure containing two
118031 ** varints:
118032 **
118033 **   PendingList *p = 0;
118034 **   fts3PendingListAppendVarint(&p, 1);
118035 **   fts3PendingListAppendVarint(&p, 2);
118036 */
118037 static int fts3PendingListAppendVarint(
118038   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
118039   sqlite3_int64 i                 /* Value to append to data */
118040 ){
118041   PendingList *p = *pp;
118042
118043   /* Allocate or grow the PendingList as required. */
118044   if( !p ){
118045     p = sqlite3_malloc(sizeof(*p) + 100);
118046     if( !p ){
118047       return SQLITE_NOMEM;
118048     }
118049     p->nSpace = 100;
118050     p->aData = (char *)&p[1];
118051     p->nData = 0;
118052   }
118053   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
118054     int nNew = p->nSpace * 2;
118055     p = sqlite3_realloc(p, sizeof(*p) + nNew);
118056     if( !p ){
118057       sqlite3_free(*pp);
118058       *pp = 0;
118059       return SQLITE_NOMEM;
118060     }
118061     p->nSpace = nNew;
118062     p->aData = (char *)&p[1];
118063   }
118064
118065   /* Append the new serialized varint to the end of the list. */
118066   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
118067   p->aData[p->nData] = '\0';
118068   *pp = p;
118069   return SQLITE_OK;
118070 }
118071
118072 /*
118073 ** Add a docid/column/position entry to a PendingList structure. Non-zero
118074 ** is returned if the structure is sqlite3_realloced as part of adding
118075 ** the entry. Otherwise, zero.
118076 **
118077 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
118078 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
118079 ** it is set to SQLITE_OK.
118080 */
118081 static int fts3PendingListAppend(
118082   PendingList **pp,               /* IN/OUT: PendingList structure */
118083   sqlite3_int64 iDocid,           /* Docid for entry to add */
118084   sqlite3_int64 iCol,             /* Column for entry to add */
118085   sqlite3_int64 iPos,             /* Position of term for entry to add */
118086   int *pRc                        /* OUT: Return code */
118087 ){
118088   PendingList *p = *pp;
118089   int rc = SQLITE_OK;
118090
118091   assert( !p || p->iLastDocid<=iDocid );
118092
118093   if( !p || p->iLastDocid!=iDocid ){
118094     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
118095     if( p ){
118096       assert( p->nData<p->nSpace );
118097       assert( p->aData[p->nData]==0 );
118098       p->nData++;
118099     }
118100     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
118101       goto pendinglistappend_out;
118102     }
118103     p->iLastCol = -1;
118104     p->iLastPos = 0;
118105     p->iLastDocid = iDocid;
118106   }
118107   if( iCol>0 && p->iLastCol!=iCol ){
118108     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
118109      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
118110     ){
118111       goto pendinglistappend_out;
118112     }
118113     p->iLastCol = iCol;
118114     p->iLastPos = 0;
118115   }
118116   if( iCol>=0 ){
118117     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
118118     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
118119     if( rc==SQLITE_OK ){
118120       p->iLastPos = iPos;
118121     }
118122   }
118123
118124  pendinglistappend_out:
118125   *pRc = rc;
118126   if( p!=*pp ){
118127     *pp = p;
118128     return 1;
118129   }
118130   return 0;
118131 }
118132
118133 /*
118134 ** Tokenize the nul-terminated string zText and add all tokens to the
118135 ** pending-terms hash-table. The docid used is that currently stored in
118136 ** p->iPrevDocid, and the column is specified by argument iCol.
118137 **
118138 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
118139 */
118140 static int fts3PendingTermsAdd(
118141   Fts3Table *p,                   /* Table into which text will be inserted */
118142   const char *zText,              /* Text of document to be inserted */
118143   int iCol,                       /* Column into which text is being inserted */
118144   u32 *pnWord                     /* OUT: Number of tokens inserted */
118145 ){
118146   int rc;
118147   int iStart;
118148   int iEnd;
118149   int iPos;
118150   int nWord = 0;
118151
118152   char const *zToken;
118153   int nToken;
118154
118155   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
118156   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
118157   sqlite3_tokenizer_cursor *pCsr;
118158   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
118159       const char**,int*,int*,int*,int*);
118160
118161   assert( pTokenizer && pModule );
118162
118163   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
118164   if( rc!=SQLITE_OK ){
118165     return rc;
118166   }
118167   pCsr->pTokenizer = pTokenizer;
118168
118169   xNext = pModule->xNext;
118170   while( SQLITE_OK==rc
118171       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
118172   ){
118173     PendingList *pList;
118174  
118175     if( iPos>=nWord ) nWord = iPos+1;
118176
118177     /* Positions cannot be negative; we use -1 as a terminator internally.
118178     ** Tokens must have a non-zero length.
118179     */
118180     if( iPos<0 || !zToken || nToken<=0 ){
118181       rc = SQLITE_ERROR;
118182       break;
118183     }
118184
118185     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
118186     if( pList ){
118187       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
118188     }
118189     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
118190       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
118191         /* Malloc failed while inserting the new entry. This can only 
118192         ** happen if there was no previous entry for this token.
118193         */
118194         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
118195         sqlite3_free(pList);
118196         rc = SQLITE_NOMEM;
118197       }
118198     }
118199     if( rc==SQLITE_OK ){
118200       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
118201     }
118202   }
118203
118204   pModule->xClose(pCsr);
118205   *pnWord = nWord;
118206   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
118207 }
118208
118209 /* 
118210 ** Calling this function indicates that subsequent calls to 
118211 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
118212 ** contents of the document with docid iDocid.
118213 */
118214 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
118215   /* TODO(shess) Explore whether partially flushing the buffer on
118216   ** forced-flush would provide better performance.  I suspect that if
118217   ** we ordered the doclists by size and flushed the largest until the
118218   ** buffer was half empty, that would let the less frequent terms
118219   ** generate longer doclists.
118220   */
118221   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
118222     int rc = sqlite3Fts3PendingTermsFlush(p);
118223     if( rc!=SQLITE_OK ) return rc;
118224   }
118225   p->iPrevDocid = iDocid;
118226   return SQLITE_OK;
118227 }
118228
118229 /*
118230 ** Discard the contents of the pending-terms hash table. 
118231 */
118232 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
118233   Fts3HashElem *pElem;
118234   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
118235     sqlite3_free(fts3HashData(pElem));
118236   }
118237   fts3HashClear(&p->pendingTerms);
118238   p->nPendingData = 0;
118239 }
118240
118241 /*
118242 ** This function is called by the xUpdate() method as part of an INSERT
118243 ** operation. It adds entries for each term in the new record to the
118244 ** pendingTerms hash table.
118245 **
118246 ** Argument apVal is the same as the similarly named argument passed to
118247 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
118248 */
118249 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
118250   int i;                          /* Iterator variable */
118251   for(i=2; i<p->nColumn+2; i++){
118252     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
118253     if( zText ){
118254       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
118255       if( rc!=SQLITE_OK ){
118256         return rc;
118257       }
118258     }
118259     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
118260   }
118261   return SQLITE_OK;
118262 }
118263
118264 /*
118265 ** This function is called by the xUpdate() method for an INSERT operation.
118266 ** The apVal parameter is passed a copy of the apVal argument passed by
118267 ** SQLite to the xUpdate() method. i.e:
118268 **
118269 **   apVal[0]                Not used for INSERT.
118270 **   apVal[1]                rowid
118271 **   apVal[2]                Left-most user-defined column
118272 **   ...
118273 **   apVal[p->nColumn+1]     Right-most user-defined column
118274 **   apVal[p->nColumn+2]     Hidden column with same name as table
118275 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
118276 */
118277 static int fts3InsertData(
118278   Fts3Table *p,                   /* Full-text table */
118279   sqlite3_value **apVal,          /* Array of values to insert */
118280   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
118281 ){
118282   int rc;                         /* Return code */
118283   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
118284
118285   /* Locate the statement handle used to insert data into the %_content
118286   ** table. The SQL for this statement is:
118287   **
118288   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
118289   **
118290   ** The statement features N '?' variables, where N is the number of user
118291   ** defined columns in the FTS3 table, plus one for the docid field.
118292   */
118293   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
118294   if( rc!=SQLITE_OK ){
118295     return rc;
118296   }
118297
118298   /* There is a quirk here. The users INSERT statement may have specified
118299   ** a value for the "rowid" field, for the "docid" field, or for both.
118300   ** Which is a problem, since "rowid" and "docid" are aliases for the
118301   ** same value. For example:
118302   **
118303   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
118304   **
118305   ** In FTS3, this is an error. It is an error to specify non-NULL values
118306   ** for both docid and some other rowid alias.
118307   */
118308   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
118309     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
118310      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
118311     ){
118312       /* A rowid/docid conflict. */
118313       return SQLITE_ERROR;
118314     }
118315     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
118316     if( rc!=SQLITE_OK ) return rc;
118317   }
118318
118319   /* Execute the statement to insert the record. Set *piDocid to the 
118320   ** new docid value. 
118321   */
118322   sqlite3_step(pContentInsert);
118323   rc = sqlite3_reset(pContentInsert);
118324
118325   *piDocid = sqlite3_last_insert_rowid(p->db);
118326   return rc;
118327 }
118328
118329
118330
118331 /*
118332 ** Remove all data from the FTS3 table. Clear the hash table containing
118333 ** pending terms.
118334 */
118335 static int fts3DeleteAll(Fts3Table *p){
118336   int rc = SQLITE_OK;             /* Return code */
118337
118338   /* Discard the contents of the pending-terms hash table. */
118339   sqlite3Fts3PendingTermsClear(p);
118340
118341   /* Delete everything from the %_content, %_segments and %_segdir tables. */
118342   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
118343   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
118344   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
118345   if( p->bHasDocsize ){
118346     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
118347   }
118348   if( p->bHasStat ){
118349     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
118350   }
118351   return rc;
118352 }
118353
118354 /*
118355 ** The first element in the apVal[] array is assumed to contain the docid
118356 ** (an integer) of a row about to be deleted. Remove all terms from the
118357 ** full-text index.
118358 */
118359 static void fts3DeleteTerms( 
118360   int *pRC,               /* Result code */
118361   Fts3Table *p,           /* The FTS table to delete from */
118362   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
118363   u32 *aSz                /* Sizes of deleted document written here */
118364 ){
118365   int rc;
118366   sqlite3_stmt *pSelect;
118367
118368   if( *pRC ) return;
118369   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
118370   if( rc==SQLITE_OK ){
118371     if( SQLITE_ROW==sqlite3_step(pSelect) ){
118372       int i;
118373       for(i=1; i<=p->nColumn; i++){
118374         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
118375         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
118376         if( rc!=SQLITE_OK ){
118377           sqlite3_reset(pSelect);
118378           *pRC = rc;
118379           return;
118380         }
118381         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
118382       }
118383     }
118384     rc = sqlite3_reset(pSelect);
118385   }else{
118386     sqlite3_reset(pSelect);
118387   }
118388   *pRC = rc;
118389 }
118390
118391 /*
118392 ** Forward declaration to account for the circular dependency between
118393 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
118394 */
118395 static int fts3SegmentMerge(Fts3Table *, int);
118396
118397 /* 
118398 ** This function allocates a new level iLevel index in the segdir table.
118399 ** Usually, indexes are allocated within a level sequentially starting
118400 ** with 0, so the allocated index is one greater than the value returned
118401 ** by:
118402 **
118403 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
118404 **
118405 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
118406 ** level, they are merged into a single level (iLevel+1) segment and the 
118407 ** allocated index is 0.
118408 **
118409 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
118410 ** returned. Otherwise, an SQLite error code is returned.
118411 */
118412 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
118413   int rc;                         /* Return Code */
118414   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
118415   int iNext = 0;                  /* Result of query pNextIdx */
118416
118417   /* Set variable iNext to the next available segdir index at level iLevel. */
118418   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
118419   if( rc==SQLITE_OK ){
118420     sqlite3_bind_int(pNextIdx, 1, iLevel);
118421     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
118422       iNext = sqlite3_column_int(pNextIdx, 0);
118423     }
118424     rc = sqlite3_reset(pNextIdx);
118425   }
118426
118427   if( rc==SQLITE_OK ){
118428     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
118429     ** full, merge all segments in level iLevel into a single iLevel+1
118430     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
118431     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
118432     */
118433     if( iNext>=FTS3_MERGE_COUNT ){
118434       rc = fts3SegmentMerge(p, iLevel);
118435       *piIdx = 0;
118436     }else{
118437       *piIdx = iNext;
118438     }
118439   }
118440
118441   return rc;
118442 }
118443
118444 /*
118445 ** The %_segments table is declared as follows:
118446 **
118447 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
118448 **
118449 ** This function reads data from a single row of the %_segments table. The
118450 ** specific row is identified by the iBlockid parameter. If paBlob is not
118451 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
118452 ** with the contents of the blob stored in the "block" column of the 
118453 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
118454 ** to the size of the blob in bytes before returning.
118455 **
118456 ** If an error occurs, or the table does not contain the specified row,
118457 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
118458 ** paBlob is non-NULL, then it is the responsibility of the caller to
118459 ** eventually free the returned buffer.
118460 **
118461 ** This function may leave an open sqlite3_blob* handle in the
118462 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
118463 ** to this function. The handle may be closed by calling the
118464 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
118465 ** performance improvement, but the blob handle should always be closed
118466 ** before control is returned to the user (to prevent a lock being held
118467 ** on the database file for longer than necessary). Thus, any virtual table
118468 ** method (xFilter etc.) that may directly or indirectly call this function
118469 ** must call sqlite3Fts3SegmentsClose() before returning.
118470 */
118471 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
118472   Fts3Table *p,                   /* FTS3 table handle */
118473   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
118474   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
118475   int *pnBlob                     /* OUT: Size of blob data */
118476 ){
118477   int rc;                         /* Return code */
118478
118479   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
118480   assert( pnBlob);
118481
118482   if( p->pSegments ){
118483     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
118484   }else{
118485     if( 0==p->zSegmentsTbl ){
118486       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
118487       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
118488     }
118489     rc = sqlite3_blob_open(
118490        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
118491     );
118492   }
118493
118494   if( rc==SQLITE_OK ){
118495     int nByte = sqlite3_blob_bytes(p->pSegments);
118496     if( paBlob ){
118497       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
118498       if( !aByte ){
118499         rc = SQLITE_NOMEM;
118500       }else{
118501         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
118502         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
118503         if( rc!=SQLITE_OK ){
118504           sqlite3_free(aByte);
118505           aByte = 0;
118506         }
118507       }
118508       *paBlob = aByte;
118509     }
118510     *pnBlob = nByte;
118511   }
118512
118513   return rc;
118514 }
118515
118516 /*
118517 ** Close the blob handle at p->pSegments, if it is open. See comments above
118518 ** the sqlite3Fts3ReadBlock() function for details.
118519 */
118520 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
118521   sqlite3_blob_close(p->pSegments);
118522   p->pSegments = 0;
118523 }
118524
118525 /*
118526 ** Move the iterator passed as the first argument to the next term in the
118527 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
118528 ** SQLITE_DONE. Otherwise, an SQLite error code.
118529 */
118530 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
118531   char *pNext;                    /* Cursor variable */
118532   int nPrefix;                    /* Number of bytes in term prefix */
118533   int nSuffix;                    /* Number of bytes in term suffix */
118534
118535   if( !pReader->aDoclist ){
118536     pNext = pReader->aNode;
118537   }else{
118538     pNext = &pReader->aDoclist[pReader->nDoclist];
118539   }
118540
118541   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
118542     int rc;                       /* Return code from Fts3ReadBlock() */
118543
118544     if( fts3SegReaderIsPending(pReader) ){
118545       Fts3HashElem *pElem = *(pReader->ppNextElem);
118546       if( pElem==0 ){
118547         pReader->aNode = 0;
118548       }else{
118549         PendingList *pList = (PendingList *)fts3HashData(pElem);
118550         pReader->zTerm = (char *)fts3HashKey(pElem);
118551         pReader->nTerm = fts3HashKeysize(pElem);
118552         pReader->nNode = pReader->nDoclist = pList->nData + 1;
118553         pReader->aNode = pReader->aDoclist = pList->aData;
118554         pReader->ppNextElem++;
118555         assert( pReader->aNode );
118556       }
118557       return SQLITE_OK;
118558     }
118559
118560     if( !fts3SegReaderIsRootOnly(pReader) ){
118561       sqlite3_free(pReader->aNode);
118562     }
118563     pReader->aNode = 0;
118564
118565     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
118566     ** blocks have already been traversed.  */
118567     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
118568     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
118569       return SQLITE_OK;
118570     }
118571
118572     rc = sqlite3Fts3ReadBlock(
118573         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
118574     );
118575     if( rc!=SQLITE_OK ) return rc;
118576     pNext = pReader->aNode;
118577   }
118578   
118579   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
118580   ** safe (no risk of overread) even if the node data is corrupted.  
118581   */
118582   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
118583   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
118584   if( nPrefix<0 || nSuffix<=0 
118585    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
118586   ){
118587     return SQLITE_CORRUPT;
118588   }
118589
118590   if( nPrefix+nSuffix>pReader->nTermAlloc ){
118591     int nNew = (nPrefix+nSuffix)*2;
118592     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
118593     if( !zNew ){
118594       return SQLITE_NOMEM;
118595     }
118596     pReader->zTerm = zNew;
118597     pReader->nTermAlloc = nNew;
118598   }
118599   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
118600   pReader->nTerm = nPrefix+nSuffix;
118601   pNext += nSuffix;
118602   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
118603   pReader->aDoclist = pNext;
118604   pReader->pOffsetList = 0;
118605
118606   /* Check that the doclist does not appear to extend past the end of the
118607   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
118608   ** of these statements is untrue, then the data structure is corrupt.
118609   */
118610   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
118611    || pReader->aDoclist[pReader->nDoclist-1]
118612   ){
118613     return SQLITE_CORRUPT;
118614   }
118615   return SQLITE_OK;
118616 }
118617
118618 /*
118619 ** Set the SegReader to point to the first docid in the doclist associated
118620 ** with the current term.
118621 */
118622 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
118623   int n;
118624   assert( pReader->aDoclist );
118625   assert( !pReader->pOffsetList );
118626   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
118627   pReader->pOffsetList = &pReader->aDoclist[n];
118628 }
118629
118630 /*
118631 ** Advance the SegReader to point to the next docid in the doclist
118632 ** associated with the current term.
118633 ** 
118634 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
118635 ** *ppOffsetList is set to point to the first column-offset list
118636 ** in the doclist entry (i.e. immediately past the docid varint).
118637 ** *pnOffsetList is set to the length of the set of column-offset
118638 ** lists, not including the nul-terminator byte. For example:
118639 */
118640 static void fts3SegReaderNextDocid(
118641   Fts3SegReader *pReader,
118642   char **ppOffsetList,
118643   int *pnOffsetList
118644 ){
118645   char *p = pReader->pOffsetList;
118646   char c = 0;
118647
118648   /* Pointer p currently points at the first byte of an offset list. The
118649   ** following two lines advance it to point one byte past the end of
118650   ** the same offset list.
118651   */
118652   while( *p | c ) c = *p++ & 0x80;
118653   p++;
118654
118655   /* If required, populate the output variables with a pointer to and the
118656   ** size of the previous offset-list.
118657   */
118658   if( ppOffsetList ){
118659     *ppOffsetList = pReader->pOffsetList;
118660     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
118661   }
118662
118663   /* If there are no more entries in the doclist, set pOffsetList to
118664   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
118665   ** Fts3SegReader.pOffsetList to point to the next offset list before
118666   ** returning.
118667   */
118668   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
118669     pReader->pOffsetList = 0;
118670   }else{
118671     sqlite3_int64 iDelta;
118672     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
118673     pReader->iDocid += iDelta;
118674   }
118675 }
118676
118677 /*
118678 ** This function is called to estimate the amount of data that will be 
118679 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
118680 ** in units of average document size.
118681 ** 
118682 ** This can be used as follows: If the caller has a small doclist that 
118683 ** contains references to N documents, and is considering merging it with
118684 ** a large doclist (size X "average documents"), it may opt not to load
118685 ** the large doclist if X>N.
118686 */
118687 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
118688   Fts3Cursor *pCsr,               /* FTS3 cursor handle */
118689   Fts3SegReader *pReader,         /* Segment-reader handle */
118690   int *pnCost                     /* IN/OUT: Number of bytes read */
118691 ){
118692   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
118693   int rc = SQLITE_OK;             /* Return code */
118694   int nCost = 0;                  /* Cost in bytes to return */
118695   int pgsz = p->nPgsz;            /* Database page size */
118696
118697   /* If this seg-reader is reading the pending-terms table, or if all data
118698   ** for the segment is stored on the root page of the b-tree, then the cost
118699   ** is zero. In this case all required data is already in main memory.
118700   */
118701   if( p->bHasStat 
118702    && !fts3SegReaderIsPending(pReader) 
118703    && !fts3SegReaderIsRootOnly(pReader) 
118704   ){
118705     int nBlob = 0;
118706     sqlite3_int64 iBlock;
118707
118708     if( pCsr->nRowAvg==0 ){
118709       /* The average document size, which is required to calculate the cost
118710       ** of each doclist, has not yet been determined. Read the required 
118711       ** data from the %_stat table to calculate it.
118712       **
118713       ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
118714       ** varints, where nCol is the number of columns in the FTS3 table.
118715       ** The first varint is the number of documents currently stored in
118716       ** the table. The following nCol varints contain the total amount of
118717       ** data stored in all rows of each column of the table, from left
118718       ** to right.
118719       */
118720       sqlite3_stmt *pStmt;
118721       sqlite3_int64 nDoc = 0;
118722       sqlite3_int64 nByte = 0;
118723       const char *pEnd;
118724       const char *a;
118725
118726       rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
118727       if( rc!=SQLITE_OK ) return rc;
118728       a = sqlite3_column_blob(pStmt, 0);
118729       assert( a );
118730
118731       pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
118732       a += sqlite3Fts3GetVarint(a, &nDoc);
118733       while( a<pEnd ){
118734         a += sqlite3Fts3GetVarint(a, &nByte);
118735       }
118736       if( nDoc==0 || nByte==0 ){
118737         sqlite3_reset(pStmt);
118738         return SQLITE_CORRUPT;
118739       }
118740
118741       pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
118742       assert( pCsr->nRowAvg>0 ); 
118743       rc = sqlite3_reset(pStmt);
118744       if( rc!=SQLITE_OK ) return rc;
118745     }
118746
118747     /* Assume that a blob flows over onto overflow pages if it is larger
118748     ** than (pgsz-35) bytes in size (the file-format documentation
118749     ** confirms this).
118750     */
118751     for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
118752       rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
118753       if( rc!=SQLITE_OK ) break;
118754       if( (nBlob+35)>pgsz ){
118755         int nOvfl = (nBlob + 34)/pgsz;
118756         nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
118757       }
118758     }
118759   }
118760
118761   *pnCost += nCost;
118762   return rc;
118763 }
118764
118765 /*
118766 ** Free all allocations associated with the iterator passed as the 
118767 ** second argument.
118768 */
118769 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
118770   if( pReader && !fts3SegReaderIsPending(pReader) ){
118771     sqlite3_free(pReader->zTerm);
118772     if( !fts3SegReaderIsRootOnly(pReader) ){
118773       sqlite3_free(pReader->aNode);
118774     }
118775   }
118776   sqlite3_free(pReader);
118777 }
118778
118779 /*
118780 ** Allocate a new SegReader object.
118781 */
118782 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
118783   int iAge,                       /* Segment "age". */
118784   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
118785   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
118786   sqlite3_int64 iEndBlock,        /* Final block of segment */
118787   const char *zRoot,              /* Buffer containing root node */
118788   int nRoot,                      /* Size of buffer containing root node */
118789   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
118790 ){
118791   int rc = SQLITE_OK;             /* Return code */
118792   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
118793   int nExtra = 0;                 /* Bytes to allocate segment root node */
118794
118795   assert( iStartLeaf<=iEndLeaf );
118796   if( iStartLeaf==0 ){
118797     nExtra = nRoot + FTS3_NODE_PADDING;
118798   }
118799
118800   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
118801   if( !pReader ){
118802     return SQLITE_NOMEM;
118803   }
118804   memset(pReader, 0, sizeof(Fts3SegReader));
118805   pReader->iIdx = iAge;
118806   pReader->iStartBlock = iStartLeaf;
118807   pReader->iLeafEndBlock = iEndLeaf;
118808   pReader->iEndBlock = iEndBlock;
118809
118810   if( nExtra ){
118811     /* The entire segment is stored in the root node. */
118812     pReader->aNode = (char *)&pReader[1];
118813     pReader->nNode = nRoot;
118814     memcpy(pReader->aNode, zRoot, nRoot);
118815     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
118816   }else{
118817     pReader->iCurrentBlock = iStartLeaf-1;
118818   }
118819
118820   if( rc==SQLITE_OK ){
118821     *ppReader = pReader;
118822   }else{
118823     sqlite3Fts3SegReaderFree(pReader);
118824   }
118825   return rc;
118826 }
118827
118828 /*
118829 ** This is a comparison function used as a qsort() callback when sorting
118830 ** an array of pending terms by term. This occurs as part of flushing
118831 ** the contents of the pending-terms hash table to the database.
118832 */
118833 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
118834   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
118835   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
118836   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
118837   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
118838
118839   int n = (n1<n2 ? n1 : n2);
118840   int c = memcmp(z1, z2, n);
118841   if( c==0 ){
118842     c = n1 - n2;
118843   }
118844   return c;
118845 }
118846
118847 /*
118848 ** This function is used to allocate an Fts3SegReader that iterates through
118849 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
118850 */
118851 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
118852   Fts3Table *p,                   /* Virtual table handle */
118853   const char *zTerm,              /* Term to search for */
118854   int nTerm,                      /* Size of buffer zTerm */
118855   int isPrefix,                   /* True for a term-prefix query */
118856   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
118857 ){
118858   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
118859   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
118860   int nElem = 0;                  /* Size of array at aElem */
118861   int rc = SQLITE_OK;             /* Return Code */
118862
118863   if( isPrefix ){
118864     int nAlloc = 0;               /* Size of allocated array at aElem */
118865     Fts3HashElem *pE = 0;         /* Iterator variable */
118866
118867     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
118868       char *zKey = (char *)fts3HashKey(pE);
118869       int nKey = fts3HashKeysize(pE);
118870       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
118871         if( nElem==nAlloc ){
118872           Fts3HashElem **aElem2;
118873           nAlloc += 16;
118874           aElem2 = (Fts3HashElem **)sqlite3_realloc(
118875               aElem, nAlloc*sizeof(Fts3HashElem *)
118876           );
118877           if( !aElem2 ){
118878             rc = SQLITE_NOMEM;
118879             nElem = 0;
118880             break;
118881           }
118882           aElem = aElem2;
118883         }
118884         aElem[nElem++] = pE;
118885       }
118886     }
118887
118888     /* If more than one term matches the prefix, sort the Fts3HashElem
118889     ** objects in term order using qsort(). This uses the same comparison
118890     ** callback as is used when flushing terms to disk.
118891     */
118892     if( nElem>1 ){
118893       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
118894     }
118895
118896   }else{
118897     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
118898     if( pE ){
118899       aElem = &pE;
118900       nElem = 1;
118901     }
118902   }
118903
118904   if( nElem>0 ){
118905     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
118906     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
118907     if( !pReader ){
118908       rc = SQLITE_NOMEM;
118909     }else{
118910       memset(pReader, 0, nByte);
118911       pReader->iIdx = 0x7FFFFFFF;
118912       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
118913       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
118914     }
118915   }
118916
118917   if( isPrefix ){
118918     sqlite3_free(aElem);
118919   }
118920   *ppReader = pReader;
118921   return rc;
118922 }
118923
118924 /*
118925 ** Compare the entries pointed to by two Fts3SegReader structures. 
118926 ** Comparison is as follows:
118927 **
118928 **   1) EOF is greater than not EOF.
118929 **
118930 **   2) The current terms (if any) are compared using memcmp(). If one
118931 **      term is a prefix of another, the longer term is considered the
118932 **      larger.
118933 **
118934 **   3) By segment age. An older segment is considered larger.
118935 */
118936 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
118937   int rc;
118938   if( pLhs->aNode && pRhs->aNode ){
118939     int rc2 = pLhs->nTerm - pRhs->nTerm;
118940     if( rc2<0 ){
118941       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
118942     }else{
118943       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
118944     }
118945     if( rc==0 ){
118946       rc = rc2;
118947     }
118948   }else{
118949     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
118950   }
118951   if( rc==0 ){
118952     rc = pRhs->iIdx - pLhs->iIdx;
118953   }
118954   assert( rc!=0 );
118955   return rc;
118956 }
118957
118958 /*
118959 ** A different comparison function for SegReader structures. In this
118960 ** version, it is assumed that each SegReader points to an entry in
118961 ** a doclist for identical terms. Comparison is made as follows:
118962 **
118963 **   1) EOF (end of doclist in this case) is greater than not EOF.
118964 **
118965 **   2) By current docid.
118966 **
118967 **   3) By segment age. An older segment is considered larger.
118968 */
118969 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
118970   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
118971   if( rc==0 ){
118972     if( pLhs->iDocid==pRhs->iDocid ){
118973       rc = pRhs->iIdx - pLhs->iIdx;
118974     }else{
118975       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
118976     }
118977   }
118978   assert( pLhs->aNode && pRhs->aNode );
118979   return rc;
118980 }
118981
118982 /*
118983 ** Compare the term that the Fts3SegReader object passed as the first argument
118984 ** points to with the term specified by arguments zTerm and nTerm. 
118985 **
118986 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
118987 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
118988 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
118989 */
118990 static int fts3SegReaderTermCmp(
118991   Fts3SegReader *pSeg,            /* Segment reader object */
118992   const char *zTerm,              /* Term to compare to */
118993   int nTerm                       /* Size of term zTerm in bytes */
118994 ){
118995   int res = 0;
118996   if( pSeg->aNode ){
118997     if( pSeg->nTerm>nTerm ){
118998       res = memcmp(pSeg->zTerm, zTerm, nTerm);
118999     }else{
119000       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
119001     }
119002     if( res==0 ){
119003       res = pSeg->nTerm-nTerm;
119004     }
119005   }
119006   return res;
119007 }
119008
119009 /*
119010 ** Argument apSegment is an array of nSegment elements. It is known that
119011 ** the final (nSegment-nSuspect) members are already in sorted order
119012 ** (according to the comparison function provided). This function shuffles
119013 ** the array around until all entries are in sorted order.
119014 */
119015 static void fts3SegReaderSort(
119016   Fts3SegReader **apSegment,                     /* Array to sort entries of */
119017   int nSegment,                                  /* Size of apSegment array */
119018   int nSuspect,                                  /* Unsorted entry count */
119019   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
119020 ){
119021   int i;                          /* Iterator variable */
119022
119023   assert( nSuspect<=nSegment );
119024
119025   if( nSuspect==nSegment ) nSuspect--;
119026   for(i=nSuspect-1; i>=0; i--){
119027     int j;
119028     for(j=i; j<(nSegment-1); j++){
119029       Fts3SegReader *pTmp;
119030       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
119031       pTmp = apSegment[j+1];
119032       apSegment[j+1] = apSegment[j];
119033       apSegment[j] = pTmp;
119034     }
119035   }
119036
119037 #ifndef NDEBUG
119038   /* Check that the list really is sorted now. */
119039   for(i=0; i<(nSuspect-1); i++){
119040     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
119041   }
119042 #endif
119043 }
119044
119045 /* 
119046 ** Insert a record into the %_segments table.
119047 */
119048 static int fts3WriteSegment(
119049   Fts3Table *p,                   /* Virtual table handle */
119050   sqlite3_int64 iBlock,           /* Block id for new block */
119051   char *z,                        /* Pointer to buffer containing block data */
119052   int n                           /* Size of buffer z in bytes */
119053 ){
119054   sqlite3_stmt *pStmt;
119055   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
119056   if( rc==SQLITE_OK ){
119057     sqlite3_bind_int64(pStmt, 1, iBlock);
119058     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
119059     sqlite3_step(pStmt);
119060     rc = sqlite3_reset(pStmt);
119061   }
119062   return rc;
119063 }
119064
119065 /* 
119066 ** Insert a record into the %_segdir table.
119067 */
119068 static int fts3WriteSegdir(
119069   Fts3Table *p,                   /* Virtual table handle */
119070   int iLevel,                     /* Value for "level" field */
119071   int iIdx,                       /* Value for "idx" field */
119072   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
119073   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
119074   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
119075   char *zRoot,                    /* Blob value for "root" field */
119076   int nRoot                       /* Number of bytes in buffer zRoot */
119077 ){
119078   sqlite3_stmt *pStmt;
119079   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
119080   if( rc==SQLITE_OK ){
119081     sqlite3_bind_int(pStmt, 1, iLevel);
119082     sqlite3_bind_int(pStmt, 2, iIdx);
119083     sqlite3_bind_int64(pStmt, 3, iStartBlock);
119084     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
119085     sqlite3_bind_int64(pStmt, 5, iEndBlock);
119086     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
119087     sqlite3_step(pStmt);
119088     rc = sqlite3_reset(pStmt);
119089   }
119090   return rc;
119091 }
119092
119093 /*
119094 ** Return the size of the common prefix (if any) shared by zPrev and
119095 ** zNext, in bytes. For example, 
119096 **
119097 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
119098 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
119099 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
119100 */
119101 static int fts3PrefixCompress(
119102   const char *zPrev,              /* Buffer containing previous term */
119103   int nPrev,                      /* Size of buffer zPrev in bytes */
119104   const char *zNext,              /* Buffer containing next term */
119105   int nNext                       /* Size of buffer zNext in bytes */
119106 ){
119107   int n;
119108   UNUSED_PARAMETER(nNext);
119109   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
119110   return n;
119111 }
119112
119113 /*
119114 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
119115 ** (according to memcmp) than the previous term.
119116 */
119117 static int fts3NodeAddTerm(
119118   Fts3Table *p,                   /* Virtual table handle */
119119   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
119120   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
119121   const char *zTerm,              /* Pointer to buffer containing term */
119122   int nTerm                       /* Size of term in bytes */
119123 ){
119124   SegmentNode *pTree = *ppTree;
119125   int rc;
119126   SegmentNode *pNew;
119127
119128   /* First try to append the term to the current node. Return early if 
119129   ** this is possible.
119130   */
119131   if( pTree ){
119132     int nData = pTree->nData;     /* Current size of node in bytes */
119133     int nReq = nData;             /* Required space after adding zTerm */
119134     int nPrefix;                  /* Number of bytes of prefix compression */
119135     int nSuffix;                  /* Suffix length */
119136
119137     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
119138     nSuffix = nTerm-nPrefix;
119139
119140     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
119141     if( nReq<=p->nNodeSize || !pTree->zTerm ){
119142
119143       if( nReq>p->nNodeSize ){
119144         /* An unusual case: this is the first term to be added to the node
119145         ** and the static node buffer (p->nNodeSize bytes) is not large
119146         ** enough. Use a separately malloced buffer instead This wastes
119147         ** p->nNodeSize bytes, but since this scenario only comes about when
119148         ** the database contain two terms that share a prefix of almost 2KB, 
119149         ** this is not expected to be a serious problem. 
119150         */
119151         assert( pTree->aData==(char *)&pTree[1] );
119152         pTree->aData = (char *)sqlite3_malloc(nReq);
119153         if( !pTree->aData ){
119154           return SQLITE_NOMEM;
119155         }
119156       }
119157
119158       if( pTree->zTerm ){
119159         /* There is no prefix-length field for first term in a node */
119160         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
119161       }
119162
119163       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
119164       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
119165       pTree->nData = nData + nSuffix;
119166       pTree->nEntry++;
119167
119168       if( isCopyTerm ){
119169         if( pTree->nMalloc<nTerm ){
119170           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
119171           if( !zNew ){
119172             return SQLITE_NOMEM;
119173           }
119174           pTree->nMalloc = nTerm*2;
119175           pTree->zMalloc = zNew;
119176         }
119177         pTree->zTerm = pTree->zMalloc;
119178         memcpy(pTree->zTerm, zTerm, nTerm);
119179         pTree->nTerm = nTerm;
119180       }else{
119181         pTree->zTerm = (char *)zTerm;
119182         pTree->nTerm = nTerm;
119183       }
119184       return SQLITE_OK;
119185     }
119186   }
119187
119188   /* If control flows to here, it was not possible to append zTerm to the
119189   ** current node. Create a new node (a right-sibling of the current node).
119190   ** If this is the first node in the tree, the term is added to it.
119191   **
119192   ** Otherwise, the term is not added to the new node, it is left empty for
119193   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
119194   ** has no parent, one is created here.
119195   */
119196   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
119197   if( !pNew ){
119198     return SQLITE_NOMEM;
119199   }
119200   memset(pNew, 0, sizeof(SegmentNode));
119201   pNew->nData = 1 + FTS3_VARINT_MAX;
119202   pNew->aData = (char *)&pNew[1];
119203
119204   if( pTree ){
119205     SegmentNode *pParent = pTree->pParent;
119206     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
119207     if( pTree->pParent==0 ){
119208       pTree->pParent = pParent;
119209     }
119210     pTree->pRight = pNew;
119211     pNew->pLeftmost = pTree->pLeftmost;
119212     pNew->pParent = pParent;
119213     pNew->zMalloc = pTree->zMalloc;
119214     pNew->nMalloc = pTree->nMalloc;
119215     pTree->zMalloc = 0;
119216   }else{
119217     pNew->pLeftmost = pNew;
119218     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
119219   }
119220
119221   *ppTree = pNew;
119222   return rc;
119223 }
119224
119225 /*
119226 ** Helper function for fts3NodeWrite().
119227 */
119228 static int fts3TreeFinishNode(
119229   SegmentNode *pTree, 
119230   int iHeight, 
119231   sqlite3_int64 iLeftChild
119232 ){
119233   int nStart;
119234   assert( iHeight>=1 && iHeight<128 );
119235   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
119236   pTree->aData[nStart] = (char)iHeight;
119237   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
119238   return nStart;
119239 }
119240
119241 /*
119242 ** Write the buffer for the segment node pTree and all of its peers to the
119243 ** database. Then call this function recursively to write the parent of 
119244 ** pTree and its peers to the database. 
119245 **
119246 ** Except, if pTree is a root node, do not write it to the database. Instead,
119247 ** set output variables *paRoot and *pnRoot to contain the root node.
119248 **
119249 ** If successful, SQLITE_OK is returned and output variable *piLast is
119250 ** set to the largest blockid written to the database (or zero if no
119251 ** blocks were written to the db). Otherwise, an SQLite error code is 
119252 ** returned.
119253 */
119254 static int fts3NodeWrite(
119255   Fts3Table *p,                   /* Virtual table handle */
119256   SegmentNode *pTree,             /* SegmentNode handle */
119257   int iHeight,                    /* Height of this node in tree */
119258   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
119259   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
119260   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
119261   char **paRoot,                  /* OUT: Data for root node */
119262   int *pnRoot                     /* OUT: Size of root node in bytes */
119263 ){
119264   int rc = SQLITE_OK;
119265
119266   if( !pTree->pParent ){
119267     /* Root node of the tree. */
119268     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
119269     *piLast = iFree-1;
119270     *pnRoot = pTree->nData - nStart;
119271     *paRoot = &pTree->aData[nStart];
119272   }else{
119273     SegmentNode *pIter;
119274     sqlite3_int64 iNextFree = iFree;
119275     sqlite3_int64 iNextLeaf = iLeaf;
119276     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
119277       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
119278       int nWrite = pIter->nData - nStart;
119279   
119280       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
119281       iNextFree++;
119282       iNextLeaf += (pIter->nEntry+1);
119283     }
119284     if( rc==SQLITE_OK ){
119285       assert( iNextLeaf==iFree );
119286       rc = fts3NodeWrite(
119287           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
119288       );
119289     }
119290   }
119291
119292   return rc;
119293 }
119294
119295 /*
119296 ** Free all memory allocations associated with the tree pTree.
119297 */
119298 static void fts3NodeFree(SegmentNode *pTree){
119299   if( pTree ){
119300     SegmentNode *p = pTree->pLeftmost;
119301     fts3NodeFree(p->pParent);
119302     while( p ){
119303       SegmentNode *pRight = p->pRight;
119304       if( p->aData!=(char *)&p[1] ){
119305         sqlite3_free(p->aData);
119306       }
119307       assert( pRight==0 || p->zMalloc==0 );
119308       sqlite3_free(p->zMalloc);
119309       sqlite3_free(p);
119310       p = pRight;
119311     }
119312   }
119313 }
119314
119315 /*
119316 ** Add a term to the segment being constructed by the SegmentWriter object
119317 ** *ppWriter. When adding the first term to a segment, *ppWriter should
119318 ** be passed NULL. This function will allocate a new SegmentWriter object
119319 ** and return it via the input/output variable *ppWriter in this case.
119320 **
119321 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
119322 */
119323 static int fts3SegWriterAdd(
119324   Fts3Table *p,                   /* Virtual table handle */
119325   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
119326   int isCopyTerm,                 /* True if buffer zTerm must be copied */
119327   const char *zTerm,              /* Pointer to buffer containing term */
119328   int nTerm,                      /* Size of term in bytes */
119329   const char *aDoclist,           /* Pointer to buffer containing doclist */
119330   int nDoclist                    /* Size of doclist in bytes */
119331 ){
119332   int nPrefix;                    /* Size of term prefix in bytes */
119333   int nSuffix;                    /* Size of term suffix in bytes */
119334   int nReq;                       /* Number of bytes required on leaf page */
119335   int nData;
119336   SegmentWriter *pWriter = *ppWriter;
119337
119338   if( !pWriter ){
119339     int rc;
119340     sqlite3_stmt *pStmt;
119341
119342     /* Allocate the SegmentWriter structure */
119343     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
119344     if( !pWriter ) return SQLITE_NOMEM;
119345     memset(pWriter, 0, sizeof(SegmentWriter));
119346     *ppWriter = pWriter;
119347
119348     /* Allocate a buffer in which to accumulate data */
119349     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
119350     if( !pWriter->aData ) return SQLITE_NOMEM;
119351     pWriter->nSize = p->nNodeSize;
119352
119353     /* Find the next free blockid in the %_segments table */
119354     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
119355     if( rc!=SQLITE_OK ) return rc;
119356     if( SQLITE_ROW==sqlite3_step(pStmt) ){
119357       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
119358       pWriter->iFirst = pWriter->iFree;
119359     }
119360     rc = sqlite3_reset(pStmt);
119361     if( rc!=SQLITE_OK ) return rc;
119362   }
119363   nData = pWriter->nData;
119364
119365   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
119366   nSuffix = nTerm-nPrefix;
119367
119368   /* Figure out how many bytes are required by this new entry */
119369   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
119370     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
119371     nSuffix +                               /* Term suffix */
119372     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
119373     nDoclist;                               /* Doclist data */
119374
119375   if( nData>0 && nData+nReq>p->nNodeSize ){
119376     int rc;
119377
119378     /* The current leaf node is full. Write it out to the database. */
119379     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
119380     if( rc!=SQLITE_OK ) return rc;
119381
119382     /* Add the current term to the interior node tree. The term added to
119383     ** the interior tree must:
119384     **
119385     **   a) be greater than the largest term on the leaf node just written
119386     **      to the database (still available in pWriter->zTerm), and
119387     **
119388     **   b) be less than or equal to the term about to be added to the new
119389     **      leaf node (zTerm/nTerm).
119390     **
119391     ** In other words, it must be the prefix of zTerm 1 byte longer than
119392     ** the common prefix (if any) of zTerm and pWriter->zTerm.
119393     */
119394     assert( nPrefix<nTerm );
119395     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
119396     if( rc!=SQLITE_OK ) return rc;
119397
119398     nData = 0;
119399     pWriter->nTerm = 0;
119400
119401     nPrefix = 0;
119402     nSuffix = nTerm;
119403     nReq = 1 +                              /* varint containing prefix size */
119404       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
119405       nTerm +                               /* Term suffix */
119406       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
119407       nDoclist;                             /* Doclist data */
119408   }
119409
119410   /* If the buffer currently allocated is too small for this entry, realloc
119411   ** the buffer to make it large enough.
119412   */
119413   if( nReq>pWriter->nSize ){
119414     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
119415     if( !aNew ) return SQLITE_NOMEM;
119416     pWriter->aData = aNew;
119417     pWriter->nSize = nReq;
119418   }
119419   assert( nData+nReq<=pWriter->nSize );
119420
119421   /* Append the prefix-compressed term and doclist to the buffer. */
119422   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
119423   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
119424   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
119425   nData += nSuffix;
119426   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
119427   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
119428   pWriter->nData = nData + nDoclist;
119429
119430   /* Save the current term so that it can be used to prefix-compress the next.
119431   ** If the isCopyTerm parameter is true, then the buffer pointed to by
119432   ** zTerm is transient, so take a copy of the term data. Otherwise, just
119433   ** store a copy of the pointer.
119434   */
119435   if( isCopyTerm ){
119436     if( nTerm>pWriter->nMalloc ){
119437       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
119438       if( !zNew ){
119439         return SQLITE_NOMEM;
119440       }
119441       pWriter->nMalloc = nTerm*2;
119442       pWriter->zMalloc = zNew;
119443       pWriter->zTerm = zNew;
119444     }
119445     assert( pWriter->zTerm==pWriter->zMalloc );
119446     memcpy(pWriter->zTerm, zTerm, nTerm);
119447   }else{
119448     pWriter->zTerm = (char *)zTerm;
119449   }
119450   pWriter->nTerm = nTerm;
119451
119452   return SQLITE_OK;
119453 }
119454
119455 /*
119456 ** Flush all data associated with the SegmentWriter object pWriter to the
119457 ** database. This function must be called after all terms have been added
119458 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
119459 ** returned. Otherwise, an SQLite error code.
119460 */
119461 static int fts3SegWriterFlush(
119462   Fts3Table *p,                   /* Virtual table handle */
119463   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
119464   int iLevel,                     /* Value for 'level' column of %_segdir */
119465   int iIdx                        /* Value for 'idx' column of %_segdir */
119466 ){
119467   int rc;                         /* Return code */
119468   if( pWriter->pTree ){
119469     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
119470     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
119471     char *zRoot = NULL;           /* Pointer to buffer containing root node */
119472     int nRoot = 0;                /* Size of buffer zRoot */
119473
119474     iLastLeaf = pWriter->iFree;
119475     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
119476     if( rc==SQLITE_OK ){
119477       rc = fts3NodeWrite(p, pWriter->pTree, 1,
119478           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
119479     }
119480     if( rc==SQLITE_OK ){
119481       rc = fts3WriteSegdir(
119482           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
119483     }
119484   }else{
119485     /* The entire tree fits on the root node. Write it to the segdir table. */
119486     rc = fts3WriteSegdir(
119487         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
119488   }
119489   return rc;
119490 }
119491
119492 /*
119493 ** Release all memory held by the SegmentWriter object passed as the 
119494 ** first argument.
119495 */
119496 static void fts3SegWriterFree(SegmentWriter *pWriter){
119497   if( pWriter ){
119498     sqlite3_free(pWriter->aData);
119499     sqlite3_free(pWriter->zMalloc);
119500     fts3NodeFree(pWriter->pTree);
119501     sqlite3_free(pWriter);
119502   }
119503 }
119504
119505 /*
119506 ** The first value in the apVal[] array is assumed to contain an integer.
119507 ** This function tests if there exist any documents with docid values that
119508 ** are different from that integer. i.e. if deleting the document with docid
119509 ** apVal[0] would mean the FTS3 table were empty.
119510 **
119511 ** If successful, *pisEmpty is set to true if the table is empty except for
119512 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
119513 ** error occurs, an SQLite error code is returned.
119514 */
119515 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
119516   sqlite3_stmt *pStmt;
119517   int rc;
119518   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
119519   if( rc==SQLITE_OK ){
119520     if( SQLITE_ROW==sqlite3_step(pStmt) ){
119521       *pisEmpty = sqlite3_column_int(pStmt, 0);
119522     }
119523     rc = sqlite3_reset(pStmt);
119524   }
119525   return rc;
119526 }
119527
119528 /*
119529 ** Set *pnSegment to the total number of segments in the database. Set
119530 ** *pnMax to the largest segment level in the database (segment levels
119531 ** are stored in the 'level' column of the %_segdir table).
119532 **
119533 ** Return SQLITE_OK if successful, or an SQLite error code if not.
119534 */
119535 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
119536   sqlite3_stmt *pStmt;
119537   int rc;
119538
119539   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
119540   if( rc!=SQLITE_OK ) return rc;
119541   if( SQLITE_ROW==sqlite3_step(pStmt) ){
119542     *pnSegment = sqlite3_column_int(pStmt, 0);
119543     *pnMax = sqlite3_column_int(pStmt, 1);
119544   }
119545   return sqlite3_reset(pStmt);
119546 }
119547
119548 /*
119549 ** This function is used after merging multiple segments into a single large
119550 ** segment to delete the old, now redundant, segment b-trees. Specifically,
119551 ** it:
119552 ** 
119553 **   1) Deletes all %_segments entries for the segments associated with 
119554 **      each of the SegReader objects in the array passed as the third 
119555 **      argument, and
119556 **
119557 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
119558 **      entries regardless of level if (iLevel<0).
119559 **
119560 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
119561 */
119562 static int fts3DeleteSegdir(
119563   Fts3Table *p,                   /* Virtual table handle */
119564   int iLevel,                     /* Level of %_segdir entries to delete */
119565   Fts3SegReader **apSegment,      /* Array of SegReader objects */
119566   int nReader                     /* Size of array apSegment */
119567 ){
119568   int rc;                         /* Return Code */
119569   int i;                          /* Iterator variable */
119570   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
119571
119572   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
119573   for(i=0; rc==SQLITE_OK && i<nReader; i++){
119574     Fts3SegReader *pSegment = apSegment[i];
119575     if( pSegment->iStartBlock ){
119576       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
119577       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
119578       sqlite3_step(pDelete);
119579       rc = sqlite3_reset(pDelete);
119580     }
119581   }
119582   if( rc!=SQLITE_OK ){
119583     return rc;
119584   }
119585
119586   if( iLevel==FTS3_SEGCURSOR_ALL ){
119587     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
119588   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
119589     sqlite3Fts3PendingTermsClear(p);
119590   }else{
119591     assert( iLevel>=0 );
119592     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
119593     if( rc==SQLITE_OK ){
119594       sqlite3_bind_int(pDelete, 1, iLevel);
119595       sqlite3_step(pDelete);
119596       rc = sqlite3_reset(pDelete);
119597     }
119598   }
119599
119600   return rc;
119601 }
119602
119603 /*
119604 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
119605 ** a position list that may (or may not) feature multiple columns. This
119606 ** function adjusts the pointer *ppList and the length *pnList so that they
119607 ** identify the subset of the position list that corresponds to column iCol.
119608 **
119609 ** If there are no entries in the input position list for column iCol, then
119610 ** *pnList is set to zero before returning.
119611 */
119612 static void fts3ColumnFilter(
119613   int iCol,                       /* Column to filter on */
119614   char **ppList,                  /* IN/OUT: Pointer to position list */
119615   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
119616 ){
119617   char *pList = *ppList;
119618   int nList = *pnList;
119619   char *pEnd = &pList[nList];
119620   int iCurrent = 0;
119621   char *p = pList;
119622
119623   assert( iCol>=0 );
119624   while( 1 ){
119625     char c = 0;
119626     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
119627   
119628     if( iCol==iCurrent ){
119629       nList = (int)(p - pList);
119630       break;
119631     }
119632
119633     nList -= (int)(p - pList);
119634     pList = p;
119635     if( nList==0 ){
119636       break;
119637     }
119638     p = &pList[1];
119639     p += sqlite3Fts3GetVarint32(p, &iCurrent);
119640   }
119641
119642   *ppList = pList;
119643   *pnList = nList;
119644 }
119645
119646 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
119647   Fts3Table *p,                   /* Virtual table handle */
119648   Fts3SegReaderCursor *pCsr,      /* Cursor object */
119649   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
119650 ){
119651   int i;
119652
119653   /* Initialize the cursor object */
119654   pCsr->pFilter = pFilter;
119655
119656   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
119657   ** for, then advance each segment iterator until it points to a term of
119658   ** equal or greater value than the specified term. This prevents many
119659   ** unnecessary merge/sort operations for the case where single segment
119660   ** b-tree leaf nodes contain more than one term.
119661   */
119662   for(i=0; i<pCsr->nSegment; i++){
119663     int nTerm = pFilter->nTerm;
119664     const char *zTerm = pFilter->zTerm;
119665     Fts3SegReader *pSeg = pCsr->apSegment[i];
119666     do {
119667       int rc = fts3SegReaderNext(p, pSeg);
119668       if( rc!=SQLITE_OK ) return rc;
119669     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
119670   }
119671   fts3SegReaderSort(
119672       pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
119673
119674   return SQLITE_OK;
119675 }
119676
119677 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
119678   Fts3Table *p,                   /* Virtual table handle */
119679   Fts3SegReaderCursor *pCsr       /* Cursor object */
119680 ){
119681   int rc = SQLITE_OK;
119682
119683   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
119684   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
119685   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
119686   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
119687   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
119688
119689   Fts3SegReader **apSegment = pCsr->apSegment;
119690   int nSegment = pCsr->nSegment;
119691   Fts3SegFilter *pFilter = pCsr->pFilter;
119692
119693   if( pCsr->nSegment==0 ) return SQLITE_OK;
119694
119695   do {
119696     int nMerge;
119697     int i;
119698   
119699     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
119700     ** forward. Then sort the list in order of current term again.  
119701     */
119702     for(i=0; i<pCsr->nAdvance; i++){
119703       rc = fts3SegReaderNext(p, apSegment[i]);
119704       if( rc!=SQLITE_OK ) return rc;
119705     }
119706     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
119707     pCsr->nAdvance = 0;
119708
119709     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
119710     assert( rc==SQLITE_OK );
119711     if( apSegment[0]->aNode==0 ) break;
119712
119713     pCsr->nTerm = apSegment[0]->nTerm;
119714     pCsr->zTerm = apSegment[0]->zTerm;
119715
119716     /* If this is a prefix-search, and if the term that apSegment[0] points
119717     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
119718     ** required callbacks have been made. In this case exit early.
119719     **
119720     ** Similarly, if this is a search for an exact match, and the first term
119721     ** of segment apSegment[0] is not a match, exit early.
119722     */
119723     if( pFilter->zTerm && !isScan ){
119724       if( pCsr->nTerm<pFilter->nTerm 
119725        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
119726        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
119727       ){
119728         break;
119729       }
119730     }
119731
119732     nMerge = 1;
119733     while( nMerge<nSegment 
119734         && apSegment[nMerge]->aNode
119735         && apSegment[nMerge]->nTerm==pCsr->nTerm 
119736         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
119737     ){
119738       nMerge++;
119739     }
119740
119741     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
119742     if( nMerge==1 && !isIgnoreEmpty ){
119743       pCsr->aDoclist = apSegment[0]->aDoclist;
119744       pCsr->nDoclist = apSegment[0]->nDoclist;
119745       rc = SQLITE_ROW;
119746     }else{
119747       int nDoclist = 0;           /* Size of doclist */
119748       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
119749
119750       /* The current term of the first nMerge entries in the array
119751       ** of Fts3SegReader objects is the same. The doclists must be merged
119752       ** and a single term returned with the merged doclist.
119753       */
119754       for(i=0; i<nMerge; i++){
119755         fts3SegReaderFirstDocid(apSegment[i]);
119756       }
119757       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
119758       while( apSegment[0]->pOffsetList ){
119759         int j;                    /* Number of segments that share a docid */
119760         char *pList;
119761         int nList;
119762         int nByte;
119763         sqlite3_int64 iDocid = apSegment[0]->iDocid;
119764         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
119765         j = 1;
119766         while( j<nMerge
119767             && apSegment[j]->pOffsetList
119768             && apSegment[j]->iDocid==iDocid
119769         ){
119770           fts3SegReaderNextDocid(apSegment[j], 0, 0);
119771           j++;
119772         }
119773
119774         if( isColFilter ){
119775           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
119776         }
119777
119778         if( !isIgnoreEmpty || nList>0 ){
119779           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
119780           if( nDoclist+nByte>pCsr->nBuffer ){
119781             char *aNew;
119782             pCsr->nBuffer = (nDoclist+nByte)*2;
119783             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
119784             if( !aNew ){
119785               return SQLITE_NOMEM;
119786             }
119787             pCsr->aBuffer = aNew;
119788           }
119789           nDoclist += sqlite3Fts3PutVarint(
119790               &pCsr->aBuffer[nDoclist], iDocid-iPrev
119791           );
119792           iPrev = iDocid;
119793           if( isRequirePos ){
119794             memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
119795             nDoclist += nList;
119796             pCsr->aBuffer[nDoclist++] = '\0';
119797           }
119798         }
119799
119800         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
119801       }
119802       if( nDoclist>0 ){
119803         pCsr->aDoclist = pCsr->aBuffer;
119804         pCsr->nDoclist = nDoclist;
119805         rc = SQLITE_ROW;
119806       }
119807     }
119808     pCsr->nAdvance = nMerge;
119809   }while( rc==SQLITE_OK );
119810
119811   return rc;
119812 }
119813
119814 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
119815   Fts3SegReaderCursor *pCsr       /* Cursor object */
119816 ){
119817   if( pCsr ){
119818     int i;
119819     for(i=0; i<pCsr->nSegment; i++){
119820       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
119821     }
119822     sqlite3_free(pCsr->apSegment);
119823     sqlite3_free(pCsr->aBuffer);
119824
119825     pCsr->nSegment = 0;
119826     pCsr->apSegment = 0;
119827     pCsr->aBuffer = 0;
119828   }
119829 }
119830
119831 /*
119832 ** Merge all level iLevel segments in the database into a single 
119833 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
119834 ** single segment with a level equal to the numerically largest level 
119835 ** currently present in the database.
119836 **
119837 ** If this function is called with iLevel<0, but there is only one
119838 ** segment in the database, SQLITE_DONE is returned immediately. 
119839 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
119840 ** an SQLite error code is returned.
119841 */
119842 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
119843   int rc;                         /* Return code */
119844   int iIdx = 0;                   /* Index of new segment */
119845   int iNewLevel = 0;              /* Level to create new segment at */
119846   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
119847   Fts3SegFilter filter;           /* Segment term filter condition */
119848   Fts3SegReaderCursor csr;        /* Cursor to iterate through level(s) */
119849
119850   rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
119851   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
119852
119853   if( iLevel==FTS3_SEGCURSOR_ALL ){
119854     /* This call is to merge all segments in the database to a single
119855     ** segment. The level of the new segment is equal to the the numerically 
119856     ** greatest segment level currently present in the database. The index
119857     ** of the new segment is always 0.  */
119858     int nDummy; /* TODO: Remove this */
119859     if( csr.nSegment==1 ){
119860       rc = SQLITE_DONE;
119861       goto finished;
119862     }
119863     rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
119864   }else{
119865     /* This call is to merge all segments at level iLevel. Find the next
119866     ** available segment index at level iLevel+1. The call to
119867     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
119868     ** a single iLevel+2 segment if necessary.  */
119869     iNewLevel = iLevel+1;
119870     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
119871   }
119872   if( rc!=SQLITE_OK ) goto finished;
119873   assert( csr.nSegment>0 );
119874   assert( iNewLevel>=0 );
119875
119876   memset(&filter, 0, sizeof(Fts3SegFilter));
119877   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
119878   filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
119879
119880   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
119881   while( SQLITE_OK==rc ){
119882     rc = sqlite3Fts3SegReaderStep(p, &csr);
119883     if( rc!=SQLITE_ROW ) break;
119884     rc = fts3SegWriterAdd(p, &pWriter, 1, 
119885         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
119886   }
119887   if( rc!=SQLITE_OK ) goto finished;
119888   assert( pWriter );
119889
119890   rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
119891   if( rc!=SQLITE_OK ) goto finished;
119892   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
119893
119894  finished:
119895   fts3SegWriterFree(pWriter);
119896   sqlite3Fts3SegReaderFinish(&csr);
119897   return rc;
119898 }
119899
119900
119901 /* 
119902 ** Flush the contents of pendingTerms to a level 0 segment.
119903 */
119904 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
119905   return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
119906 }
119907
119908 /*
119909 ** Encode N integers as varints into a blob.
119910 */
119911 static void fts3EncodeIntArray(
119912   int N,             /* The number of integers to encode */
119913   u32 *a,            /* The integer values */
119914   char *zBuf,        /* Write the BLOB here */
119915   int *pNBuf         /* Write number of bytes if zBuf[] used here */
119916 ){
119917   int i, j;
119918   for(i=j=0; i<N; i++){
119919     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
119920   }
119921   *pNBuf = j;
119922 }
119923
119924 /*
119925 ** Decode a blob of varints into N integers
119926 */
119927 static void fts3DecodeIntArray(
119928   int N,             /* The number of integers to decode */
119929   u32 *a,            /* Write the integer values */
119930   const char *zBuf,  /* The BLOB containing the varints */
119931   int nBuf           /* size of the BLOB */
119932 ){
119933   int i, j;
119934   UNUSED_PARAMETER(nBuf);
119935   for(i=j=0; i<N; i++){
119936     sqlite3_int64 x;
119937     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
119938     assert(j<=nBuf);
119939     a[i] = (u32)(x & 0xffffffff);
119940   }
119941 }
119942
119943 /*
119944 ** Insert the sizes (in tokens) for each column of the document
119945 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
119946 ** a blob of varints.
119947 */
119948 static void fts3InsertDocsize(
119949   int *pRC,         /* Result code */
119950   Fts3Table *p,     /* Table into which to insert */
119951   u32 *aSz          /* Sizes of each column */
119952 ){
119953   char *pBlob;             /* The BLOB encoding of the document size */
119954   int nBlob;               /* Number of bytes in the BLOB */
119955   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
119956   int rc;                  /* Result code from subfunctions */
119957
119958   if( *pRC ) return;
119959   pBlob = sqlite3_malloc( 10*p->nColumn );
119960   if( pBlob==0 ){
119961     *pRC = SQLITE_NOMEM;
119962     return;
119963   }
119964   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
119965   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
119966   if( rc ){
119967     sqlite3_free(pBlob);
119968     *pRC = rc;
119969     return;
119970   }
119971   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
119972   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
119973   sqlite3_step(pStmt);
119974   *pRC = sqlite3_reset(pStmt);
119975 }
119976
119977 /*
119978 ** Record 0 of the %_stat table contains a blob consisting of N varints,
119979 ** where N is the number of user defined columns in the fts3 table plus
119980 ** two. If nCol is the number of user defined columns, then values of the 
119981 ** varints are set as follows:
119982 **
119983 **   Varint 0:       Total number of rows in the table.
119984 **
119985 **   Varint 1..nCol: For each column, the total number of tokens stored in
119986 **                   the column for all rows of the table.
119987 **
119988 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
119989 **                   columns of all rows of the table.
119990 **
119991 */
119992 static void fts3UpdateDocTotals(
119993   int *pRC,                       /* The result code */
119994   Fts3Table *p,                   /* Table being updated */
119995   u32 *aSzIns,                    /* Size increases */
119996   u32 *aSzDel,                    /* Size decreases */
119997   int nChng                       /* Change in the number of documents */
119998 ){
119999   char *pBlob;             /* Storage for BLOB written into %_stat */
120000   int nBlob;               /* Size of BLOB written into %_stat */
120001   u32 *a;                  /* Array of integers that becomes the BLOB */
120002   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
120003   int i;                   /* Loop counter */
120004   int rc;                  /* Result code from subfunctions */
120005
120006   const int nStat = p->nColumn+2;
120007
120008   if( *pRC ) return;
120009   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
120010   if( a==0 ){
120011     *pRC = SQLITE_NOMEM;
120012     return;
120013   }
120014   pBlob = (char*)&a[nStat];
120015   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
120016   if( rc ){
120017     sqlite3_free(a);
120018     *pRC = rc;
120019     return;
120020   }
120021   if( sqlite3_step(pStmt)==SQLITE_ROW ){
120022     fts3DecodeIntArray(nStat, a,
120023          sqlite3_column_blob(pStmt, 0),
120024          sqlite3_column_bytes(pStmt, 0));
120025   }else{
120026     memset(a, 0, sizeof(u32)*(nStat) );
120027   }
120028   sqlite3_reset(pStmt);
120029   if( nChng<0 && a[0]<(u32)(-nChng) ){
120030     a[0] = 0;
120031   }else{
120032     a[0] += nChng;
120033   }
120034   for(i=0; i<p->nColumn+1; i++){
120035     u32 x = a[i+1];
120036     if( x+aSzIns[i] < aSzDel[i] ){
120037       x = 0;
120038     }else{
120039       x = x + aSzIns[i] - aSzDel[i];
120040     }
120041     a[i+1] = x;
120042   }
120043   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
120044   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
120045   if( rc ){
120046     sqlite3_free(a);
120047     *pRC = rc;
120048     return;
120049   }
120050   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
120051   sqlite3_step(pStmt);
120052   *pRC = sqlite3_reset(pStmt);
120053   sqlite3_free(a);
120054 }
120055
120056 /*
120057 ** Handle a 'special' INSERT of the form:
120058 **
120059 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
120060 **
120061 ** Argument pVal contains the result of <expr>. Currently the only 
120062 ** meaningful value to insert is the text 'optimize'.
120063 */
120064 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
120065   int rc;                         /* Return Code */
120066   const char *zVal = (const char *)sqlite3_value_text(pVal);
120067   int nVal = sqlite3_value_bytes(pVal);
120068
120069   if( !zVal ){
120070     return SQLITE_NOMEM;
120071   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
120072     rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120073     if( rc==SQLITE_DONE ){
120074       rc = SQLITE_OK;
120075     }else{
120076       sqlite3Fts3PendingTermsClear(p);
120077     }
120078 #ifdef SQLITE_TEST
120079   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
120080     p->nNodeSize = atoi(&zVal[9]);
120081     rc = SQLITE_OK;
120082   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
120083     p->nMaxPendingData = atoi(&zVal[11]);
120084     rc = SQLITE_OK;
120085 #endif
120086   }else{
120087     rc = SQLITE_ERROR;
120088   }
120089
120090   sqlite3Fts3SegmentsClose(p);
120091   return rc;
120092 }
120093
120094 /*
120095 ** Return the deferred doclist associated with deferred token pDeferred.
120096 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
120097 ** been called to allocate and populate the doclist.
120098 */
120099 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
120100   if( pDeferred->pList ){
120101     *pnByte = pDeferred->pList->nData;
120102     return pDeferred->pList->aData;
120103   }
120104   *pnByte = 0;
120105   return 0;
120106 }
120107
120108 /*
120109 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
120110 ** references to deferred doclists from within the tree of Fts3Expr 
120111 ** structures headed by 
120112 */
120113 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
120114   if( pExpr ){
120115     fts3DeferredDoclistClear(pExpr->pLeft);
120116     fts3DeferredDoclistClear(pExpr->pRight);
120117     if( pExpr->isLoaded ){
120118       sqlite3_free(pExpr->aDoclist);
120119       pExpr->isLoaded = 0;
120120       pExpr->aDoclist = 0;
120121       pExpr->nDoclist = 0;
120122       pExpr->pCurrent = 0;
120123       pExpr->iCurrent = 0;
120124     }
120125   }
120126 }
120127
120128 /*
120129 ** Delete all cached deferred doclists. Deferred doclists are cached
120130 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
120131 */
120132 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
120133   Fts3DeferredToken *pDef;
120134   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
120135     sqlite3_free(pDef->pList);
120136     pDef->pList = 0;
120137   }
120138   if( pCsr->pDeferred ){
120139     fts3DeferredDoclistClear(pCsr->pExpr);
120140   }
120141 }
120142
120143 /*
120144 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
120145 ** this list using sqlite3Fts3DeferToken().
120146 */
120147 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
120148   Fts3DeferredToken *pDef;
120149   Fts3DeferredToken *pNext;
120150   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
120151     pNext = pDef->pNext;
120152     sqlite3_free(pDef->pList);
120153     sqlite3_free(pDef);
120154   }
120155   pCsr->pDeferred = 0;
120156 }
120157
120158 /*
120159 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
120160 ** based on the row that pCsr currently points to.
120161 **
120162 ** A deferred-doclist is like any other doclist with position information
120163 ** included, except that it only contains entries for a single row of the
120164 ** table, not for all rows.
120165 */
120166 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
120167   int rc = SQLITE_OK;             /* Return code */
120168   if( pCsr->pDeferred ){
120169     int i;                        /* Used to iterate through table columns */
120170     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
120171     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
120172   
120173     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120174     sqlite3_tokenizer *pT = p->pTokenizer;
120175     sqlite3_tokenizer_module const *pModule = pT->pModule;
120176    
120177     assert( pCsr->isRequireSeek==0 );
120178     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
120179   
120180     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
120181       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
120182       sqlite3_tokenizer_cursor *pTC = 0;
120183   
120184       rc = pModule->xOpen(pT, zText, -1, &pTC);
120185       while( rc==SQLITE_OK ){
120186         char const *zToken;       /* Buffer containing token */
120187         int nToken;               /* Number of bytes in token */
120188         int iDum1, iDum2;         /* Dummy variables */
120189         int iPos;                 /* Position of token in zText */
120190   
120191         pTC->pTokenizer = pT;
120192         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
120193         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120194           Fts3PhraseToken *pPT = pDef->pToken;
120195           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
120196            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
120197            && (0==memcmp(zToken, pPT->z, pPT->n))
120198           ){
120199             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
120200           }
120201         }
120202       }
120203       if( pTC ) pModule->xClose(pTC);
120204       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
120205     }
120206   
120207     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
120208       if( pDef->pList ){
120209         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
120210       }
120211     }
120212   }
120213
120214   return rc;
120215 }
120216
120217 /*
120218 ** Add an entry for token pToken to the pCsr->pDeferred list.
120219 */
120220 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
120221   Fts3Cursor *pCsr,               /* Fts3 table cursor */
120222   Fts3PhraseToken *pToken,        /* Token to defer */
120223   int iCol                        /* Column that token must appear in (or -1) */
120224 ){
120225   Fts3DeferredToken *pDeferred;
120226   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
120227   if( !pDeferred ){
120228     return SQLITE_NOMEM;
120229   }
120230   memset(pDeferred, 0, sizeof(*pDeferred));
120231   pDeferred->pToken = pToken;
120232   pDeferred->pNext = pCsr->pDeferred; 
120233   pDeferred->iCol = iCol;
120234   pCsr->pDeferred = pDeferred;
120235
120236   assert( pToken->pDeferred==0 );
120237   pToken->pDeferred = pDeferred;
120238
120239   return SQLITE_OK;
120240 }
120241
120242
120243 /*
120244 ** This function does the work for the xUpdate method of FTS3 virtual
120245 ** tables.
120246 */
120247 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
120248   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
120249   int nArg,                       /* Size of argument array */
120250   sqlite3_value **apVal,          /* Array of arguments */
120251   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120252 ){
120253   Fts3Table *p = (Fts3Table *)pVtab;
120254   int rc = SQLITE_OK;             /* Return Code */
120255   int isRemove = 0;               /* True for an UPDATE or DELETE */
120256   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
120257   u32 *aSzIns;                    /* Sizes of inserted documents */
120258   u32 *aSzDel;                    /* Sizes of deleted documents */
120259   int nChng = 0;                  /* Net change in number of documents */
120260
120261   assert( p->pSegments==0 );
120262
120263   /* Allocate space to hold the change in document sizes */
120264   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
120265   if( aSzIns==0 ) return SQLITE_NOMEM;
120266   aSzDel = &aSzIns[p->nColumn+1];
120267   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
120268
120269   /* If this is a DELETE or UPDATE operation, remove the old record. */
120270   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120271     int isEmpty = 0;
120272     rc = fts3IsEmpty(p, apVal, &isEmpty);
120273     if( rc==SQLITE_OK ){
120274       if( isEmpty ){
120275         /* Deleting this row means the whole table is empty. In this case
120276         ** delete the contents of all three tables and throw away any
120277         ** data in the pendingTerms hash table.
120278         */
120279         rc = fts3DeleteAll(p);
120280       }else{
120281         isRemove = 1;
120282         iRemove = sqlite3_value_int64(apVal[0]);
120283         rc = fts3PendingTermsDocid(p, iRemove);
120284         fts3DeleteTerms(&rc, p, apVal, aSzDel);
120285         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
120286         if( p->bHasDocsize ){
120287           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
120288         }
120289         nChng--;
120290       }
120291     }
120292   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
120293     sqlite3_free(aSzIns);
120294     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
120295   }
120296   
120297   /* If this is an INSERT or UPDATE operation, insert the new record. */
120298   if( nArg>1 && rc==SQLITE_OK ){
120299     rc = fts3InsertData(p, apVal, pRowid);
120300     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
120301       rc = fts3PendingTermsDocid(p, *pRowid);
120302     }
120303     if( rc==SQLITE_OK ){
120304       rc = fts3InsertTerms(p, apVal, aSzIns);
120305     }
120306     if( p->bHasDocsize ){
120307       fts3InsertDocsize(&rc, p, aSzIns);
120308     }
120309     nChng++;
120310   }
120311
120312   if( p->bHasStat ){
120313     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
120314   }
120315
120316   sqlite3_free(aSzIns);
120317   sqlite3Fts3SegmentsClose(p);
120318   return rc;
120319 }
120320
120321 /* 
120322 ** Flush any data in the pending-terms hash table to disk. If successful,
120323 ** merge all segments in the database (including the new segment, if 
120324 ** there was any data to flush) into a single segment. 
120325 */
120326 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
120327   int rc;
120328   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
120329   if( rc==SQLITE_OK ){
120330     rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
120331     if( rc==SQLITE_OK ){
120332       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120333       if( rc==SQLITE_OK ){
120334         sqlite3Fts3PendingTermsClear(p);
120335       }
120336     }else{
120337       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
120338       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
120339     }
120340   }
120341   sqlite3Fts3SegmentsClose(p);
120342   return rc;
120343 }
120344
120345 #endif
120346
120347 /************** End of fts3_write.c ******************************************/
120348 /************** Begin file fts3_snippet.c ************************************/
120349 /*
120350 ** 2009 Oct 23
120351 **
120352 ** The author disclaims copyright to this source code.  In place of
120353 ** a legal notice, here is a blessing:
120354 **
120355 **    May you do good and not evil.
120356 **    May you find forgiveness for yourself and forgive others.
120357 **    May you share freely, never taking more than you give.
120358 **
120359 ******************************************************************************
120360 */
120361
120362 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120363
120364
120365 /*
120366 ** Characters that may appear in the second argument to matchinfo().
120367 */
120368 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
120369 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
120370 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
120371 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
120372 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
120373 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
120374 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
120375
120376 /*
120377 ** The default value for the second argument to matchinfo(). 
120378 */
120379 #define FTS3_MATCHINFO_DEFAULT   "pcx"
120380
120381
120382 /*
120383 ** Used as an fts3ExprIterate() context when loading phrase doclists to
120384 ** Fts3Expr.aDoclist[]/nDoclist.
120385 */
120386 typedef struct LoadDoclistCtx LoadDoclistCtx;
120387 struct LoadDoclistCtx {
120388   Fts3Cursor *pCsr;               /* FTS3 Cursor */
120389   int nPhrase;                    /* Number of phrases seen so far */
120390   int nToken;                     /* Number of tokens seen so far */
120391 };
120392
120393 /*
120394 ** The following types are used as part of the implementation of the 
120395 ** fts3BestSnippet() routine.
120396 */
120397 typedef struct SnippetIter SnippetIter;
120398 typedef struct SnippetPhrase SnippetPhrase;
120399 typedef struct SnippetFragment SnippetFragment;
120400
120401 struct SnippetIter {
120402   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
120403   int iCol;                       /* Extract snippet from this column */
120404   int nSnippet;                   /* Requested snippet length (in tokens) */
120405   int nPhrase;                    /* Number of phrases in query */
120406   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
120407   int iCurrent;                   /* First token of current snippet */
120408 };
120409
120410 struct SnippetPhrase {
120411   int nToken;                     /* Number of tokens in phrase */
120412   char *pList;                    /* Pointer to start of phrase position list */
120413   int iHead;                      /* Next value in position list */
120414   char *pHead;                    /* Position list data following iHead */
120415   int iTail;                      /* Next value in trailing position list */
120416   char *pTail;                    /* Position list data following iTail */
120417 };
120418
120419 struct SnippetFragment {
120420   int iCol;                       /* Column snippet is extracted from */
120421   int iPos;                       /* Index of first token in snippet */
120422   u64 covered;                    /* Mask of query phrases covered */
120423   u64 hlmask;                     /* Mask of snippet terms to highlight */
120424 };
120425
120426 /*
120427 ** This type is used as an fts3ExprIterate() context object while 
120428 ** accumulating the data returned by the matchinfo() function.
120429 */
120430 typedef struct MatchInfo MatchInfo;
120431 struct MatchInfo {
120432   Fts3Cursor *pCursor;            /* FTS3 Cursor */
120433   int nCol;                       /* Number of columns in table */
120434   int nPhrase;                    /* Number of matchable phrases in query */
120435   sqlite3_int64 nDoc;             /* Number of docs in database */
120436   u32 *aMatchinfo;                /* Pre-allocated buffer */
120437 };
120438
120439
120440
120441 /*
120442 ** The snippet() and offsets() functions both return text values. An instance
120443 ** of the following structure is used to accumulate those values while the
120444 ** functions are running. See fts3StringAppend() for details.
120445 */
120446 typedef struct StrBuffer StrBuffer;
120447 struct StrBuffer {
120448   char *z;                        /* Pointer to buffer containing string */
120449   int n;                          /* Length of z in bytes (excl. nul-term) */
120450   int nAlloc;                     /* Allocated size of buffer z in bytes */
120451 };
120452
120453
120454 /*
120455 ** This function is used to help iterate through a position-list. A position
120456 ** list is a list of unique integers, sorted from smallest to largest. Each
120457 ** element of the list is represented by an FTS3 varint that takes the value
120458 ** of the difference between the current element and the previous one plus
120459 ** two. For example, to store the position-list:
120460 **
120461 **     4 9 113
120462 **
120463 ** the three varints:
120464 **
120465 **     6 7 106
120466 **
120467 ** are encoded.
120468 **
120469 ** When this function is called, *pp points to the start of an element of
120470 ** the list. *piPos contains the value of the previous entry in the list.
120471 ** After it returns, *piPos contains the value of the next element of the
120472 ** list and *pp is advanced to the following varint.
120473 */
120474 static void fts3GetDeltaPosition(char **pp, int *piPos){
120475   int iVal;
120476   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
120477   *piPos += (iVal-2);
120478 }
120479
120480 /*
120481 ** Helper function for fts3ExprIterate() (see below).
120482 */
120483 static int fts3ExprIterate2(
120484   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
120485   int *piPhrase,                  /* Pointer to phrase counter */
120486   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
120487   void *pCtx                      /* Second argument to pass to callback */
120488 ){
120489   int rc;                         /* Return code */
120490   int eType = pExpr->eType;       /* Type of expression node pExpr */
120491
120492   if( eType!=FTSQUERY_PHRASE ){
120493     assert( pExpr->pLeft && pExpr->pRight );
120494     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
120495     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
120496       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
120497     }
120498   }else{
120499     rc = x(pExpr, *piPhrase, pCtx);
120500     (*piPhrase)++;
120501   }
120502   return rc;
120503 }
120504
120505 /*
120506 ** Iterate through all phrase nodes in an FTS3 query, except those that
120507 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
120508 ** For each phrase node found, the supplied callback function is invoked.
120509 **
120510 ** If the callback function returns anything other than SQLITE_OK, 
120511 ** the iteration is abandoned and the error code returned immediately.
120512 ** Otherwise, SQLITE_OK is returned after a callback has been made for
120513 ** all eligible phrase nodes.
120514 */
120515 static int fts3ExprIterate(
120516   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
120517   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
120518   void *pCtx                      /* Second argument to pass to callback */
120519 ){
120520   int iPhrase = 0;                /* Variable used as the phrase counter */
120521   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
120522 }
120523
120524 /*
120525 ** The argument to this function is always a phrase node. Its doclist 
120526 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
120527 ** to the left of this one in the query tree have already been loaded.
120528 **
120529 ** If this phrase node is part of a series of phrase nodes joined by 
120530 ** NEAR operators (and is not the left-most of said series), then elements are
120531 ** removed from the phrases doclist consistent with the NEAR restriction. If
120532 ** required, elements may be removed from the doclists of phrases to the
120533 ** left of this one that are part of the same series of NEAR operator 
120534 ** connected phrases.
120535 **
120536 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120537 */
120538 static int fts3ExprNearTrim(Fts3Expr *pExpr){
120539   int rc = SQLITE_OK;
120540   Fts3Expr *pParent = pExpr->pParent;
120541
120542   assert( pExpr->eType==FTSQUERY_PHRASE );
120543   while( rc==SQLITE_OK
120544    && pParent 
120545    && pParent->eType==FTSQUERY_NEAR 
120546    && pParent->pRight==pExpr 
120547   ){
120548     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
120549     ** Find the expression to the left of the same operator.
120550     */
120551     int nNear = pParent->nNear;
120552     Fts3Expr *pLeft = pParent->pLeft;
120553
120554     if( pLeft->eType!=FTSQUERY_PHRASE ){
120555       assert( pLeft->eType==FTSQUERY_NEAR );
120556       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
120557       pLeft = pLeft->pRight;
120558     }
120559
120560     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
120561
120562     pExpr = pLeft;
120563     pParent = pExpr->pParent;
120564   }
120565
120566   return rc;
120567 }
120568
120569 /*
120570 ** This is an fts3ExprIterate() callback used while loading the doclists
120571 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
120572 ** fts3ExprLoadDoclists().
120573 */
120574 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120575   int rc = SQLITE_OK;
120576   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
120577
120578   UNUSED_PARAMETER(iPhrase);
120579
120580   p->nPhrase++;
120581   p->nToken += pExpr->pPhrase->nToken;
120582
120583   if( pExpr->isLoaded==0 ){
120584     rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
120585     pExpr->isLoaded = 1;
120586     if( rc==SQLITE_OK ){
120587       rc = fts3ExprNearTrim(pExpr);
120588     }
120589   }
120590
120591   return rc;
120592 }
120593
120594 /*
120595 ** Load the doclists for each phrase in the query associated with FTS3 cursor
120596 ** pCsr. 
120597 **
120598 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
120599 ** phrases in the expression (all phrases except those directly or 
120600 ** indirectly descended from the right-hand-side of a NOT operator). If 
120601 ** pnToken is not NULL, then it is set to the number of tokens in all
120602 ** matchable phrases of the expression.
120603 */
120604 static int fts3ExprLoadDoclists(
120605   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
120606   int *pnPhrase,                  /* OUT: Number of phrases in query */
120607   int *pnToken                    /* OUT: Number of tokens in query */
120608 ){
120609   int rc;                         /* Return Code */
120610   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
120611   sCtx.pCsr = pCsr;
120612   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
120613   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
120614   if( pnToken ) *pnToken = sCtx.nToken;
120615   return rc;
120616 }
120617
120618 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
120619   (*(int *)ctx)++;
120620   UNUSED_PARAMETER(pExpr);
120621   UNUSED_PARAMETER(iPhrase);
120622   return SQLITE_OK;
120623 }
120624 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
120625   int nPhrase = 0;
120626   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
120627   return nPhrase;
120628 }
120629
120630 /*
120631 ** Advance the position list iterator specified by the first two 
120632 ** arguments so that it points to the first element with a value greater
120633 ** than or equal to parameter iNext.
120634 */
120635 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
120636   char *pIter = *ppIter;
120637   if( pIter ){
120638     int iIter = *piIter;
120639
120640     while( iIter<iNext ){
120641       if( 0==(*pIter & 0xFE) ){
120642         iIter = -1;
120643         pIter = 0;
120644         break;
120645       }
120646       fts3GetDeltaPosition(&pIter, &iIter);
120647     }
120648
120649     *piIter = iIter;
120650     *ppIter = pIter;
120651   }
120652 }
120653
120654 /*
120655 ** Advance the snippet iterator to the next candidate snippet.
120656 */
120657 static int fts3SnippetNextCandidate(SnippetIter *pIter){
120658   int i;                          /* Loop counter */
120659
120660   if( pIter->iCurrent<0 ){
120661     /* The SnippetIter object has just been initialized. The first snippet
120662     ** candidate always starts at offset 0 (even if this candidate has a
120663     ** score of 0.0).
120664     */
120665     pIter->iCurrent = 0;
120666
120667     /* Advance the 'head' iterator of each phrase to the first offset that
120668     ** is greater than or equal to (iNext+nSnippet).
120669     */
120670     for(i=0; i<pIter->nPhrase; i++){
120671       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120672       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
120673     }
120674   }else{
120675     int iStart;
120676     int iEnd = 0x7FFFFFFF;
120677
120678     for(i=0; i<pIter->nPhrase; i++){
120679       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120680       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
120681         iEnd = pPhrase->iHead;
120682       }
120683     }
120684     if( iEnd==0x7FFFFFFF ){
120685       return 1;
120686     }
120687
120688     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
120689     for(i=0; i<pIter->nPhrase; i++){
120690       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120691       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
120692       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
120693     }
120694   }
120695
120696   return 0;
120697 }
120698
120699 /*
120700 ** Retrieve information about the current candidate snippet of snippet 
120701 ** iterator pIter.
120702 */
120703 static void fts3SnippetDetails(
120704   SnippetIter *pIter,             /* Snippet iterator */
120705   u64 mCovered,                   /* Bitmask of phrases already covered */
120706   int *piToken,                   /* OUT: First token of proposed snippet */
120707   int *piScore,                   /* OUT: "Score" for this snippet */
120708   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
120709   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
120710 ){
120711   int iStart = pIter->iCurrent;   /* First token of snippet */
120712   int iScore = 0;                 /* Score of this snippet */
120713   int i;                          /* Loop counter */
120714   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
120715   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
120716
120717   for(i=0; i<pIter->nPhrase; i++){
120718     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
120719     if( pPhrase->pTail ){
120720       char *pCsr = pPhrase->pTail;
120721       int iCsr = pPhrase->iTail;
120722
120723       while( iCsr<(iStart+pIter->nSnippet) ){
120724         int j;
120725         u64 mPhrase = (u64)1 << i;
120726         u64 mPos = (u64)1 << (iCsr - iStart);
120727         assert( iCsr>=iStart );
120728         if( (mCover|mCovered)&mPhrase ){
120729           iScore++;
120730         }else{
120731           iScore += 1000;
120732         }
120733         mCover |= mPhrase;
120734
120735         for(j=0; j<pPhrase->nToken; j++){
120736           mHighlight |= (mPos>>j);
120737         }
120738
120739         if( 0==(*pCsr & 0x0FE) ) break;
120740         fts3GetDeltaPosition(&pCsr, &iCsr);
120741       }
120742     }
120743   }
120744
120745   /* Set the output variables before returning. */
120746   *piToken = iStart;
120747   *piScore = iScore;
120748   *pmCover = mCover;
120749   *pmHighlight = mHighlight;
120750 }
120751
120752 /*
120753 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
120754 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
120755 */
120756 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
120757   SnippetIter *p = (SnippetIter *)ctx;
120758   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
120759   char *pCsr;
120760
120761   pPhrase->nToken = pExpr->pPhrase->nToken;
120762
120763   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
120764   if( pCsr ){
120765     int iFirst = 0;
120766     pPhrase->pList = pCsr;
120767     fts3GetDeltaPosition(&pCsr, &iFirst);
120768     pPhrase->pHead = pCsr;
120769     pPhrase->pTail = pCsr;
120770     pPhrase->iHead = iFirst;
120771     pPhrase->iTail = iFirst;
120772   }else{
120773     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
120774   }
120775
120776   return SQLITE_OK;
120777 }
120778
120779 /*
120780 ** Select the fragment of text consisting of nFragment contiguous tokens 
120781 ** from column iCol that represent the "best" snippet. The best snippet
120782 ** is the snippet with the highest score, where scores are calculated
120783 ** by adding:
120784 **
120785 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
120786 **
120787 **   (b) +1000 points for the first occurence of each matchable phrase in 
120788 **       the snippet for which the corresponding mCovered bit is not set.
120789 **
120790 ** The selected snippet parameters are stored in structure *pFragment before
120791 ** returning. The score of the selected snippet is stored in *piScore
120792 ** before returning.
120793 */
120794 static int fts3BestSnippet(
120795   int nSnippet,                   /* Desired snippet length */
120796   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
120797   int iCol,                       /* Index of column to create snippet from */
120798   u64 mCovered,                   /* Mask of phrases already covered */
120799   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
120800   SnippetFragment *pFragment,     /* OUT: Best snippet found */
120801   int *piScore                    /* OUT: Score of snippet pFragment */
120802 ){
120803   int rc;                         /* Return Code */
120804   int nList;                      /* Number of phrases in expression */
120805   SnippetIter sIter;              /* Iterates through snippet candidates */
120806   int nByte;                      /* Number of bytes of space to allocate */
120807   int iBestScore = -1;            /* Best snippet score found so far */
120808   int i;                          /* Loop counter */
120809
120810   memset(&sIter, 0, sizeof(sIter));
120811
120812   /* Iterate through the phrases in the expression to count them. The same
120813   ** callback makes sure the doclists are loaded for each phrase.
120814   */
120815   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
120816   if( rc!=SQLITE_OK ){
120817     return rc;
120818   }
120819
120820   /* Now that it is known how many phrases there are, allocate and zero
120821   ** the required space using malloc().
120822   */
120823   nByte = sizeof(SnippetPhrase) * nList;
120824   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
120825   if( !sIter.aPhrase ){
120826     return SQLITE_NOMEM;
120827   }
120828   memset(sIter.aPhrase, 0, nByte);
120829
120830   /* Initialize the contents of the SnippetIter object. Then iterate through
120831   ** the set of phrases in the expression to populate the aPhrase[] array.
120832   */
120833   sIter.pCsr = pCsr;
120834   sIter.iCol = iCol;
120835   sIter.nSnippet = nSnippet;
120836   sIter.nPhrase = nList;
120837   sIter.iCurrent = -1;
120838   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
120839
120840   /* Set the *pmSeen output variable. */
120841   for(i=0; i<nList; i++){
120842     if( sIter.aPhrase[i].pHead ){
120843       *pmSeen |= (u64)1 << i;
120844     }
120845   }
120846
120847   /* Loop through all candidate snippets. Store the best snippet in 
120848   ** *pFragment. Store its associated 'score' in iBestScore.
120849   */
120850   pFragment->iCol = iCol;
120851   while( !fts3SnippetNextCandidate(&sIter) ){
120852     int iPos;
120853     int iScore;
120854     u64 mCover;
120855     u64 mHighlight;
120856     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
120857     assert( iScore>=0 );
120858     if( iScore>iBestScore ){
120859       pFragment->iPos = iPos;
120860       pFragment->hlmask = mHighlight;
120861       pFragment->covered = mCover;
120862       iBestScore = iScore;
120863     }
120864   }
120865
120866   sqlite3_free(sIter.aPhrase);
120867   *piScore = iBestScore;
120868   return SQLITE_OK;
120869 }
120870
120871
120872 /*
120873 ** Append a string to the string-buffer passed as the first argument.
120874 **
120875 ** If nAppend is negative, then the length of the string zAppend is
120876 ** determined using strlen().
120877 */
120878 static int fts3StringAppend(
120879   StrBuffer *pStr,                /* Buffer to append to */
120880   const char *zAppend,            /* Pointer to data to append to buffer */
120881   int nAppend                     /* Size of zAppend in bytes (or -1) */
120882 ){
120883   if( nAppend<0 ){
120884     nAppend = (int)strlen(zAppend);
120885   }
120886
120887   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
120888   ** to grow the buffer until so that it is big enough to accomadate the
120889   ** appended data.
120890   */
120891   if( pStr->n+nAppend+1>=pStr->nAlloc ){
120892     int nAlloc = pStr->nAlloc+nAppend+100;
120893     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
120894     if( !zNew ){
120895       return SQLITE_NOMEM;
120896     }
120897     pStr->z = zNew;
120898     pStr->nAlloc = nAlloc;
120899   }
120900
120901   /* Append the data to the string buffer. */
120902   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
120903   pStr->n += nAppend;
120904   pStr->z[pStr->n] = '\0';
120905
120906   return SQLITE_OK;
120907 }
120908
120909 /*
120910 ** The fts3BestSnippet() function often selects snippets that end with a
120911 ** query term. That is, the final term of the snippet is always a term
120912 ** that requires highlighting. For example, if 'X' is a highlighted term
120913 ** and '.' is a non-highlighted term, BestSnippet() may select:
120914 **
120915 **     ........X.....X
120916 **
120917 ** This function "shifts" the beginning of the snippet forward in the 
120918 ** document so that there are approximately the same number of 
120919 ** non-highlighted terms to the right of the final highlighted term as there
120920 ** are to the left of the first highlighted term. For example, to this:
120921 **
120922 **     ....X.....X....
120923 **
120924 ** This is done as part of extracting the snippet text, not when selecting
120925 ** the snippet. Snippet selection is done based on doclists only, so there
120926 ** is no way for fts3BestSnippet() to know whether or not the document 
120927 ** actually contains terms that follow the final highlighted term. 
120928 */
120929 static int fts3SnippetShift(
120930   Fts3Table *pTab,                /* FTS3 table snippet comes from */
120931   int nSnippet,                   /* Number of tokens desired for snippet */
120932   const char *zDoc,               /* Document text to extract snippet from */
120933   int nDoc,                       /* Size of buffer zDoc in bytes */
120934   int *piPos,                     /* IN/OUT: First token of snippet */
120935   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
120936 ){
120937   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
120938
120939   if( hlmask ){
120940     int nLeft;                    /* Tokens to the left of first highlight */
120941     int nRight;                   /* Tokens to the right of last highlight */
120942     int nDesired;                 /* Ideal number of tokens to shift forward */
120943
120944     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
120945     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
120946     nDesired = (nLeft-nRight)/2;
120947
120948     /* Ideally, the start of the snippet should be pushed forward in the
120949     ** document nDesired tokens. This block checks if there are actually
120950     ** nDesired tokens to the right of the snippet. If so, *piPos and
120951     ** *pHlMask are updated to shift the snippet nDesired tokens to the
120952     ** right. Otherwise, the snippet is shifted by the number of tokens
120953     ** available.
120954     */
120955     if( nDesired>0 ){
120956       int nShift;                 /* Number of tokens to shift snippet by */
120957       int iCurrent = 0;           /* Token counter */
120958       int rc;                     /* Return Code */
120959       sqlite3_tokenizer_module *pMod;
120960       sqlite3_tokenizer_cursor *pC;
120961       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
120962
120963       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
120964       ** or more tokens in zDoc/nDoc.
120965       */
120966       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
120967       if( rc!=SQLITE_OK ){
120968         return rc;
120969       }
120970       pC->pTokenizer = pTab->pTokenizer;
120971       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
120972         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
120973         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
120974       }
120975       pMod->xClose(pC);
120976       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
120977
120978       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
120979       assert( nShift<=nDesired );
120980       if( nShift>0 ){
120981         *piPos += nShift;
120982         *pHlmask = hlmask >> nShift;
120983       }
120984     }
120985   }
120986   return SQLITE_OK;
120987 }
120988
120989 /*
120990 ** Extract the snippet text for fragment pFragment from cursor pCsr and
120991 ** append it to string buffer pOut.
120992 */
120993 static int fts3SnippetText(
120994   Fts3Cursor *pCsr,               /* FTS3 Cursor */
120995   SnippetFragment *pFragment,     /* Snippet to extract */
120996   int iFragment,                  /* Fragment number */
120997   int isLast,                     /* True for final fragment in snippet */
120998   int nSnippet,                   /* Number of tokens in extracted snippet */
120999   const char *zOpen,              /* String inserted before highlighted term */
121000   const char *zClose,             /* String inserted after highlighted term */
121001   const char *zEllipsis,          /* String inserted between snippets */
121002   StrBuffer *pOut                 /* Write output here */
121003 ){
121004   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121005   int rc;                         /* Return code */
121006   const char *zDoc;               /* Document text to extract snippet from */
121007   int nDoc;                       /* Size of zDoc in bytes */
121008   int iCurrent = 0;               /* Current token number of document */
121009   int iEnd = 0;                   /* Byte offset of end of current token */
121010   int isShiftDone = 0;            /* True after snippet is shifted */
121011   int iPos = pFragment->iPos;     /* First token of snippet */
121012   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
121013   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
121014   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
121015   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
121016   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
121017   int DUMMY1;                     /* Dummy argument used with tokenizer */
121018   
121019   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
121020   if( zDoc==0 ){
121021     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
121022       return SQLITE_NOMEM;
121023     }
121024     return SQLITE_OK;
121025   }
121026   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
121027
121028   /* Open a token cursor on the document. */
121029   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
121030   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121031   if( rc!=SQLITE_OK ){
121032     return rc;
121033   }
121034   pC->pTokenizer = pTab->pTokenizer;
121035
121036   while( rc==SQLITE_OK ){
121037     int iBegin;                   /* Offset in zDoc of start of token */
121038     int iFin;                     /* Offset in zDoc of end of token */
121039     int isHighlight;              /* True for highlighted terms */
121040
121041     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
121042     if( rc!=SQLITE_OK ){
121043       if( rc==SQLITE_DONE ){
121044         /* Special case - the last token of the snippet is also the last token
121045         ** of the column. Append any punctuation that occurred between the end
121046         ** of the previous token and the end of the document to the output. 
121047         ** Then break out of the loop. */
121048         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
121049       }
121050       break;
121051     }
121052     if( iCurrent<iPos ){ continue; }
121053
121054     if( !isShiftDone ){
121055       int n = nDoc - iBegin;
121056       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
121057       isShiftDone = 1;
121058
121059       /* Now that the shift has been done, check if the initial "..." are
121060       ** required. They are required if (a) this is not the first fragment,
121061       ** or (b) this fragment does not begin at position 0 of its column. 
121062       */
121063       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
121064         rc = fts3StringAppend(pOut, zEllipsis, -1);
121065       }
121066       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
121067     }
121068
121069     if( iCurrent>=(iPos+nSnippet) ){
121070       if( isLast ){
121071         rc = fts3StringAppend(pOut, zEllipsis, -1);
121072       }
121073       break;
121074     }
121075
121076     /* Set isHighlight to true if this term should be highlighted. */
121077     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
121078
121079     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
121080     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
121081     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
121082     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
121083
121084     iEnd = iFin;
121085   }
121086
121087   pMod->xClose(pC);
121088   return rc;
121089 }
121090
121091
121092 /*
121093 ** This function is used to count the entries in a column-list (a 
121094 ** delta-encoded list of term offsets within a single column of a single 
121095 ** row). When this function is called, *ppCollist should point to the
121096 ** beginning of the first varint in the column-list (the varint that
121097 ** contains the position of the first matching term in the column data).
121098 ** Before returning, *ppCollist is set to point to the first byte after
121099 ** the last varint in the column-list (either the 0x00 signifying the end
121100 ** of the position-list, or the 0x01 that precedes the column number of
121101 ** the next column in the position-list).
121102 **
121103 ** The number of elements in the column-list is returned.
121104 */
121105 static int fts3ColumnlistCount(char **ppCollist){
121106   char *pEnd = *ppCollist;
121107   char c = 0;
121108   int nEntry = 0;
121109
121110   /* A column-list is terminated by either a 0x01 or 0x00. */
121111   while( 0xFE & (*pEnd | c) ){
121112     c = *pEnd++ & 0x80;
121113     if( !c ) nEntry++;
121114   }
121115
121116   *ppCollist = pEnd;
121117   return nEntry;
121118 }
121119
121120 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
121121   char *pCsr = *pp;
121122   while( *pCsr ){
121123     int nHit;
121124     sqlite3_int64 iCol = 0;
121125     if( *pCsr==0x01 ){
121126       pCsr++;
121127       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
121128     }
121129     nHit = fts3ColumnlistCount(&pCsr);
121130     assert( nHit>0 );
121131     if( isGlobal ){
121132       aOut[iCol*3+1]++;
121133     }
121134     aOut[iCol*3] += nHit;
121135   }
121136   pCsr++;
121137   *pp = pCsr;
121138 }
121139
121140 /*
121141 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
121142 ** for a single query. 
121143 **
121144 ** fts3ExprIterate() callback to load the 'global' elements of a
121145 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
121146 ** of the matchinfo array that are constant for all rows returned by the 
121147 ** current query.
121148 **
121149 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
121150 ** function populates Matchinfo.aMatchinfo[] as follows:
121151 **
121152 **   for(iCol=0; iCol<nCol; iCol++){
121153 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
121154 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
121155 **   }
121156 **
121157 ** where X is the number of matches for phrase iPhrase is column iCol of all
121158 ** rows of the table. Y is the number of rows for which column iCol contains
121159 ** at least one instance of phrase iPhrase.
121160 **
121161 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
121162 ** Y values are set to nDoc, where nDoc is the number of documents in the 
121163 ** file system. This is done because the full-text index doclist is required
121164 ** to calculate these values properly, and the full-text index doclist is
121165 ** not available for deferred tokens.
121166 */
121167 static int fts3ExprGlobalHitsCb(
121168   Fts3Expr *pExpr,                /* Phrase expression node */
121169   int iPhrase,                    /* Phrase number (numbered from zero) */
121170   void *pCtx                      /* Pointer to MatchInfo structure */
121171 ){
121172   MatchInfo *p = (MatchInfo *)pCtx;
121173   Fts3Cursor *pCsr = p->pCursor;
121174   char *pIter;
121175   char *pEnd;
121176   char *pFree = 0;
121177   u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
121178
121179   assert( pExpr->isLoaded );
121180   assert( pExpr->eType==FTSQUERY_PHRASE );
121181
121182   if( pCsr->pDeferred ){
121183     Fts3Phrase *pPhrase = pExpr->pPhrase;
121184     int ii;
121185     for(ii=0; ii<pPhrase->nToken; ii++){
121186       if( pPhrase->aToken[ii].bFulltext ) break;
121187     }
121188     if( ii<pPhrase->nToken ){
121189       int nFree = 0;
121190       int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
121191       if( rc!=SQLITE_OK ) return rc;
121192       pIter = pFree;
121193       pEnd = &pFree[nFree];
121194     }else{
121195       int iCol;                   /* Column index */
121196       for(iCol=0; iCol<p->nCol; iCol++){
121197         aOut[iCol*3 + 1] = (u32)p->nDoc;
121198         aOut[iCol*3 + 2] = (u32)p->nDoc;
121199       }
121200       return SQLITE_OK;
121201     }
121202   }else{
121203     pIter = pExpr->aDoclist;
121204     pEnd = &pExpr->aDoclist[pExpr->nDoclist];
121205   }
121206
121207   /* Fill in the global hit count matrix row for this phrase. */
121208   while( pIter<pEnd ){
121209     while( *pIter++ & 0x80 );      /* Skip past docid. */
121210     fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
121211   }
121212
121213   sqlite3_free(pFree);
121214   return SQLITE_OK;
121215 }
121216
121217 /*
121218 ** fts3ExprIterate() callback used to collect the "local" part of the
121219 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
121220 ** array that are different for each row returned by the query.
121221 */
121222 static int fts3ExprLocalHitsCb(
121223   Fts3Expr *pExpr,                /* Phrase expression node */
121224   int iPhrase,                    /* Phrase number */
121225   void *pCtx                      /* Pointer to MatchInfo structure */
121226 ){
121227   MatchInfo *p = (MatchInfo *)pCtx;
121228   int iStart = iPhrase * p->nCol * 3;
121229   int i;
121230
121231   for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
121232
121233   if( pExpr->aDoclist ){
121234     char *pCsr;
121235
121236     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
121237     if( pCsr ){
121238       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
121239     }
121240   }
121241
121242   return SQLITE_OK;
121243 }
121244
121245 static int fts3MatchinfoCheck(
121246   Fts3Table *pTab, 
121247   char cArg,
121248   char **pzErr
121249 ){
121250   if( (cArg==FTS3_MATCHINFO_NPHRASE)
121251    || (cArg==FTS3_MATCHINFO_NCOL)
121252    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
121253    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
121254    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
121255    || (cArg==FTS3_MATCHINFO_LCS)
121256    || (cArg==FTS3_MATCHINFO_HITS)
121257   ){
121258     return SQLITE_OK;
121259   }
121260   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
121261   return SQLITE_ERROR;
121262 }
121263
121264 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
121265   int nVal;                       /* Number of integers output by cArg */
121266
121267   switch( cArg ){
121268     case FTS3_MATCHINFO_NDOC:
121269     case FTS3_MATCHINFO_NPHRASE: 
121270     case FTS3_MATCHINFO_NCOL: 
121271       nVal = 1;
121272       break;
121273
121274     case FTS3_MATCHINFO_AVGLENGTH:
121275     case FTS3_MATCHINFO_LENGTH:
121276     case FTS3_MATCHINFO_LCS:
121277       nVal = pInfo->nCol;
121278       break;
121279
121280     default:
121281       assert( cArg==FTS3_MATCHINFO_HITS );
121282       nVal = pInfo->nCol * pInfo->nPhrase * 3;
121283       break;
121284   }
121285
121286   return nVal;
121287 }
121288
121289 static int fts3MatchinfoSelectDoctotal(
121290   Fts3Table *pTab,
121291   sqlite3_stmt **ppStmt,
121292   sqlite3_int64 *pnDoc,
121293   const char **paLen
121294 ){
121295   sqlite3_stmt *pStmt;
121296   const char *a;
121297   sqlite3_int64 nDoc;
121298
121299   if( !*ppStmt ){
121300     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
121301     if( rc!=SQLITE_OK ) return rc;
121302   }
121303   pStmt = *ppStmt;
121304   assert( sqlite3_data_count(pStmt)==1 );
121305
121306   a = sqlite3_column_blob(pStmt, 0);
121307   a += sqlite3Fts3GetVarint(a, &nDoc);
121308   if( nDoc==0 ) return SQLITE_CORRUPT;
121309   *pnDoc = (u32)nDoc;
121310
121311   if( paLen ) *paLen = a;
121312   return SQLITE_OK;
121313 }
121314
121315 /*
121316 ** An instance of the following structure is used to store state while 
121317 ** iterating through a multi-column position-list corresponding to the
121318 ** hits for a single phrase on a single row in order to calculate the
121319 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
121320 */
121321 typedef struct LcsIterator LcsIterator;
121322 struct LcsIterator {
121323   Fts3Expr *pExpr;                /* Pointer to phrase expression */
121324   char *pRead;                    /* Cursor used to iterate through aDoclist */
121325   int iPosOffset;                 /* Tokens count up to end of this phrase */
121326   int iCol;                       /* Current column number */
121327   int iPos;                       /* Current position */
121328 };
121329
121330 /* 
121331 ** If LcsIterator.iCol is set to the following value, the iterator has
121332 ** finished iterating through all offsets for all columns.
121333 */
121334 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
121335
121336 static int fts3MatchinfoLcsCb(
121337   Fts3Expr *pExpr,                /* Phrase expression node */
121338   int iPhrase,                    /* Phrase number (numbered from zero) */
121339   void *pCtx                      /* Pointer to MatchInfo structure */
121340 ){
121341   LcsIterator *aIter = (LcsIterator *)pCtx;
121342   aIter[iPhrase].pExpr = pExpr;
121343   return SQLITE_OK;
121344 }
121345
121346 /*
121347 ** Advance the iterator passed as an argument to the next position. Return
121348 ** 1 if the iterator is at EOF or if it now points to the start of the
121349 ** position list for the next column.
121350 */
121351 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
121352   char *pRead = pIter->pRead;
121353   sqlite3_int64 iRead;
121354   int rc = 0;
121355
121356   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121357   if( iRead==0 ){
121358     pIter->iCol = LCS_ITERATOR_FINISHED;
121359     rc = 1;
121360   }else{
121361     if( iRead==1 ){
121362       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121363       pIter->iCol = (int)iRead;
121364       pIter->iPos = pIter->iPosOffset;
121365       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
121366       rc = 1;
121367     }
121368     pIter->iPos += (int)(iRead-2);
121369   }
121370
121371   pIter->pRead = pRead;
121372   return rc;
121373 }
121374   
121375 /*
121376 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
121377 **
121378 ** If the call is successful, the longest-common-substring lengths for each
121379 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
121380 ** array before returning. SQLITE_OK is returned in this case.
121381 **
121382 ** Otherwise, if an error occurs, an SQLite error code is returned and the
121383 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
121384 ** undefined.
121385 */
121386 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
121387   LcsIterator *aIter;
121388   int i;
121389   int iCol;
121390   int nToken = 0;
121391
121392   /* Allocate and populate the array of LcsIterator objects. The array
121393   ** contains one element for each matchable phrase in the query.
121394   **/
121395   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
121396   if( !aIter ) return SQLITE_NOMEM;
121397   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
121398   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
121399   for(i=0; i<pInfo->nPhrase; i++){
121400     LcsIterator *pIter = &aIter[i];
121401     nToken -= pIter->pExpr->pPhrase->nToken;
121402     pIter->iPosOffset = nToken;
121403     pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
121404     if( pIter->pRead ){
121405       pIter->iPos = pIter->iPosOffset;
121406       fts3LcsIteratorAdvance(&aIter[i]);
121407     }else{
121408       pIter->iCol = LCS_ITERATOR_FINISHED;
121409     }
121410   }
121411
121412   for(iCol=0; iCol<pInfo->nCol; iCol++){
121413     int nLcs = 0;                 /* LCS value for this column */
121414     int nLive = 0;                /* Number of iterators in aIter not at EOF */
121415
121416     /* Loop through the iterators in aIter[]. Set nLive to the number of
121417     ** iterators that point to a position-list corresponding to column iCol.
121418     */
121419     for(i=0; i<pInfo->nPhrase; i++){
121420       assert( aIter[i].iCol>=iCol );
121421       if( aIter[i].iCol==iCol ) nLive++;
121422     }
121423
121424     /* The following loop runs until all iterators in aIter[] have finished
121425     ** iterating through positions in column iCol. Exactly one of the 
121426     ** iterators is advanced each time the body of the loop is run.
121427     */
121428     while( nLive>0 ){
121429       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
121430       int nThisLcs = 0;           /* LCS for the current iterator positions */
121431
121432       for(i=0; i<pInfo->nPhrase; i++){
121433         LcsIterator *pIter = &aIter[i];
121434         if( iCol!=pIter->iCol ){  
121435           /* This iterator is already at EOF for this column. */
121436           nThisLcs = 0;
121437         }else{
121438           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
121439             pAdv = pIter;
121440           }
121441           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
121442             nThisLcs++;
121443           }else{
121444             nThisLcs = 1;
121445           }
121446           if( nThisLcs>nLcs ) nLcs = nThisLcs;
121447         }
121448       }
121449       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
121450     }
121451
121452     pInfo->aMatchinfo[iCol] = nLcs;
121453   }
121454
121455   sqlite3_free(aIter);
121456   return SQLITE_OK;
121457 }
121458
121459 /*
121460 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
121461 ** be returned by the matchinfo() function. Argument zArg contains the 
121462 ** format string passed as the second argument to matchinfo (or the
121463 ** default value "pcx" if no second argument was specified). The format
121464 ** string has already been validated and the pInfo->aMatchinfo[] array
121465 ** is guaranteed to be large enough for the output.
121466 **
121467 ** If bGlobal is true, then populate all fields of the matchinfo() output.
121468 ** If it is false, then assume that those fields that do not change between
121469 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
121470 ** have already been populated.
121471 **
121472 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
121473 ** occurs. If a value other than SQLITE_OK is returned, the state the
121474 ** pInfo->aMatchinfo[] buffer is left in is undefined.
121475 */
121476 static int fts3MatchinfoValues(
121477   Fts3Cursor *pCsr,               /* FTS3 cursor object */
121478   int bGlobal,                    /* True to grab the global stats */
121479   MatchInfo *pInfo,               /* Matchinfo context object */
121480   const char *zArg                /* Matchinfo format string */
121481 ){
121482   int rc = SQLITE_OK;
121483   int i;
121484   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121485   sqlite3_stmt *pSelect = 0;
121486
121487   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
121488
121489     switch( zArg[i] ){
121490       case FTS3_MATCHINFO_NPHRASE:
121491         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
121492         break;
121493
121494       case FTS3_MATCHINFO_NCOL:
121495         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
121496         break;
121497         
121498       case FTS3_MATCHINFO_NDOC:
121499         if( bGlobal ){
121500           sqlite3_int64 nDoc;
121501           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
121502           pInfo->aMatchinfo[0] = (u32)nDoc;
121503         }
121504         break;
121505
121506       case FTS3_MATCHINFO_AVGLENGTH: 
121507         if( bGlobal ){
121508           sqlite3_int64 nDoc;     /* Number of rows in table */
121509           const char *a;          /* Aggregate column length array */
121510
121511           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
121512           if( rc==SQLITE_OK ){
121513             int iCol;
121514             for(iCol=0; iCol<pInfo->nCol; iCol++){
121515               u32 iVal;
121516               sqlite3_int64 nToken;
121517               a += sqlite3Fts3GetVarint(a, &nToken);
121518               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
121519               pInfo->aMatchinfo[iCol] = iVal;
121520             }
121521           }
121522         }
121523         break;
121524
121525       case FTS3_MATCHINFO_LENGTH: {
121526         sqlite3_stmt *pSelectDocsize = 0;
121527         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
121528         if( rc==SQLITE_OK ){
121529           int iCol;
121530           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
121531           for(iCol=0; iCol<pInfo->nCol; iCol++){
121532             sqlite3_int64 nToken;
121533             a += sqlite3Fts3GetVarint(a, &nToken);
121534             pInfo->aMatchinfo[iCol] = (u32)nToken;
121535           }
121536         }
121537         sqlite3_reset(pSelectDocsize);
121538         break;
121539       }
121540
121541       case FTS3_MATCHINFO_LCS:
121542         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121543         if( rc==SQLITE_OK ){
121544           rc = fts3MatchinfoLcs(pCsr, pInfo);
121545         }
121546         break;
121547
121548       default: {
121549         Fts3Expr *pExpr;
121550         assert( zArg[i]==FTS3_MATCHINFO_HITS );
121551         pExpr = pCsr->pExpr;
121552         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
121553         if( rc!=SQLITE_OK ) break;
121554         if( bGlobal ){
121555           if( pCsr->pDeferred ){
121556             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
121557             if( rc!=SQLITE_OK ) break;
121558           }
121559           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
121560           if( rc!=SQLITE_OK ) break;
121561         }
121562         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
121563         break;
121564       }
121565     }
121566
121567     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
121568   }
121569
121570   sqlite3_reset(pSelect);
121571   return rc;
121572 }
121573
121574
121575 /*
121576 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
121577 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
121578 */
121579 static int fts3GetMatchinfo(
121580   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
121581   const char *zArg                /* Second argument to matchinfo() function */
121582 ){
121583   MatchInfo sInfo;
121584   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121585   int rc = SQLITE_OK;
121586   int bGlobal = 0;                /* Collect 'global' stats as well as local */
121587
121588   memset(&sInfo, 0, sizeof(MatchInfo));
121589   sInfo.pCursor = pCsr;
121590   sInfo.nCol = pTab->nColumn;
121591
121592   /* If there is cached matchinfo() data, but the format string for the 
121593   ** cache does not match the format string for this request, discard 
121594   ** the cached data. */
121595   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
121596     assert( pCsr->aMatchinfo );
121597     sqlite3_free(pCsr->aMatchinfo);
121598     pCsr->zMatchinfo = 0;
121599     pCsr->aMatchinfo = 0;
121600   }
121601
121602   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
121603   ** matchinfo function has been called for this query. In this case 
121604   ** allocate the array used to accumulate the matchinfo data and
121605   ** initialize those elements that are constant for every row.
121606   */
121607   if( pCsr->aMatchinfo==0 ){
121608     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
121609     int nArg;                     /* Bytes in zArg */
121610     int i;                        /* Used to iterate through zArg */
121611
121612     /* Determine the number of phrases in the query */
121613     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
121614     sInfo.nPhrase = pCsr->nPhrase;
121615
121616     /* Determine the number of integers in the buffer returned by this call. */
121617     for(i=0; zArg[i]; i++){
121618       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
121619     }
121620
121621     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
121622     nArg = (int)strlen(zArg);
121623     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
121624     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
121625
121626     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
121627     pCsr->nMatchinfo = nMatchinfo;
121628     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
121629     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
121630     pCsr->isMatchinfoNeeded = 1;
121631     bGlobal = 1;
121632   }
121633
121634   sInfo.aMatchinfo = pCsr->aMatchinfo;
121635   sInfo.nPhrase = pCsr->nPhrase;
121636   if( pCsr->isMatchinfoNeeded ){
121637     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
121638     pCsr->isMatchinfoNeeded = 0;
121639   }
121640
121641   return rc;
121642 }
121643
121644 /*
121645 ** Implementation of snippet() function.
121646 */
121647 SQLITE_PRIVATE void sqlite3Fts3Snippet(
121648   sqlite3_context *pCtx,          /* SQLite function call context */
121649   Fts3Cursor *pCsr,               /* Cursor object */
121650   const char *zStart,             /* Snippet start text - "<b>" */
121651   const char *zEnd,               /* Snippet end text - "</b>" */
121652   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
121653   int iCol,                       /* Extract snippet from this column */
121654   int nToken                      /* Approximate number of tokens in snippet */
121655 ){
121656   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121657   int rc = SQLITE_OK;
121658   int i;
121659   StrBuffer res = {0, 0, 0};
121660
121661   /* The returned text includes up to four fragments of text extracted from
121662   ** the data in the current row. The first iteration of the for(...) loop
121663   ** below attempts to locate a single fragment of text nToken tokens in 
121664   ** size that contains at least one instance of all phrases in the query
121665   ** expression that appear in the current row. If such a fragment of text
121666   ** cannot be found, the second iteration of the loop attempts to locate
121667   ** a pair of fragments, and so on.
121668   */
121669   int nSnippet = 0;               /* Number of fragments in this snippet */
121670   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
121671   int nFToken = -1;               /* Number of tokens in each fragment */
121672
121673   if( !pCsr->pExpr ){
121674     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
121675     return;
121676   }
121677
121678   for(nSnippet=1; 1; nSnippet++){
121679
121680     int iSnip;                    /* Loop counter 0..nSnippet-1 */
121681     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
121682     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
121683
121684     if( nToken>=0 ){
121685       nFToken = (nToken+nSnippet-1) / nSnippet;
121686     }else{
121687       nFToken = -1 * nToken;
121688     }
121689
121690     for(iSnip=0; iSnip<nSnippet; iSnip++){
121691       int iBestScore = -1;        /* Best score of columns checked so far */
121692       int iRead;                  /* Used to iterate through columns */
121693       SnippetFragment *pFragment = &aSnippet[iSnip];
121694
121695       memset(pFragment, 0, sizeof(*pFragment));
121696
121697       /* Loop through all columns of the table being considered for snippets.
121698       ** If the iCol argument to this function was negative, this means all
121699       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
121700       */
121701       for(iRead=0; iRead<pTab->nColumn; iRead++){
121702         SnippetFragment sF = {0, 0, 0, 0};
121703         int iS;
121704         if( iCol>=0 && iRead!=iCol ) continue;
121705
121706         /* Find the best snippet of nFToken tokens in column iRead. */
121707         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
121708         if( rc!=SQLITE_OK ){
121709           goto snippet_out;
121710         }
121711         if( iS>iBestScore ){
121712           *pFragment = sF;
121713           iBestScore = iS;
121714         }
121715       }
121716
121717       mCovered |= pFragment->covered;
121718     }
121719
121720     /* If all query phrases seen by fts3BestSnippet() are present in at least
121721     ** one of the nSnippet snippet fragments, break out of the loop.
121722     */
121723     assert( (mCovered&mSeen)==mCovered );
121724     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
121725   }
121726
121727   assert( nFToken>0 );
121728
121729   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
121730     rc = fts3SnippetText(pCsr, &aSnippet[i], 
121731         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
121732     );
121733   }
121734
121735  snippet_out:
121736   sqlite3Fts3SegmentsClose(pTab);
121737   if( rc!=SQLITE_OK ){
121738     sqlite3_result_error_code(pCtx, rc);
121739     sqlite3_free(res.z);
121740   }else{
121741     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
121742   }
121743 }
121744
121745
121746 typedef struct TermOffset TermOffset;
121747 typedef struct TermOffsetCtx TermOffsetCtx;
121748
121749 struct TermOffset {
121750   char *pList;                    /* Position-list */
121751   int iPos;                       /* Position just read from pList */
121752   int iOff;                       /* Offset of this term from read positions */
121753 };
121754
121755 struct TermOffsetCtx {
121756   int iCol;                       /* Column of table to populate aTerm for */
121757   int iTerm;
121758   sqlite3_int64 iDocid;
121759   TermOffset *aTerm;
121760 };
121761
121762 /*
121763 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
121764 */
121765 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
121766   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
121767   int nTerm;                      /* Number of tokens in phrase */
121768   int iTerm;                      /* For looping through nTerm phrase terms */
121769   char *pList;                    /* Pointer to position list for phrase */
121770   int iPos = 0;                   /* First position in position-list */
121771
121772   UNUSED_PARAMETER(iPhrase);
121773   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
121774   nTerm = pExpr->pPhrase->nToken;
121775   if( pList ){
121776     fts3GetDeltaPosition(&pList, &iPos);
121777     assert( iPos>=0 );
121778   }
121779
121780   for(iTerm=0; iTerm<nTerm; iTerm++){
121781     TermOffset *pT = &p->aTerm[p->iTerm++];
121782     pT->iOff = nTerm-iTerm-1;
121783     pT->pList = pList;
121784     pT->iPos = iPos;
121785   }
121786
121787   return SQLITE_OK;
121788 }
121789
121790 /*
121791 ** Implementation of offsets() function.
121792 */
121793 SQLITE_PRIVATE void sqlite3Fts3Offsets(
121794   sqlite3_context *pCtx,          /* SQLite function call context */
121795   Fts3Cursor *pCsr                /* Cursor object */
121796 ){
121797   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121798   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
121799   const char *ZDUMMY;             /* Dummy argument used with xNext() */
121800   int NDUMMY;                     /* Dummy argument used with xNext() */
121801   int rc;                         /* Return Code */
121802   int nToken;                     /* Number of tokens in query */
121803   int iCol;                       /* Column currently being processed */
121804   StrBuffer res = {0, 0, 0};      /* Result string */
121805   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
121806
121807   if( !pCsr->pExpr ){
121808     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
121809     return;
121810   }
121811
121812   memset(&sCtx, 0, sizeof(sCtx));
121813   assert( pCsr->isRequireSeek==0 );
121814
121815   /* Count the number of terms in the query */
121816   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
121817   if( rc!=SQLITE_OK ) goto offsets_out;
121818
121819   /* Allocate the array of TermOffset iterators. */
121820   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
121821   if( 0==sCtx.aTerm ){
121822     rc = SQLITE_NOMEM;
121823     goto offsets_out;
121824   }
121825   sCtx.iDocid = pCsr->iPrevId;
121826
121827   /* Loop through the table columns, appending offset information to 
121828   ** string-buffer res for each column.
121829   */
121830   for(iCol=0; iCol<pTab->nColumn; iCol++){
121831     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
121832     int iStart;
121833     int iEnd;
121834     int iCurrent;
121835     const char *zDoc;
121836     int nDoc;
121837
121838     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
121839     ** no way that this operation can fail, so the return code from
121840     ** fts3ExprIterate() can be discarded.
121841     */
121842     sCtx.iCol = iCol;
121843     sCtx.iTerm = 0;
121844     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
121845
121846     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
121847     ** in column iCol, jump immediately to the next iteration of the loop.
121848     ** If an OOM occurs while retrieving the data (this can happen if SQLite
121849     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
121850     ** to the caller. 
121851     */
121852     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
121853     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
121854     if( zDoc==0 ){
121855       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
121856         continue;
121857       }
121858       rc = SQLITE_NOMEM;
121859       goto offsets_out;
121860     }
121861
121862     /* Initialize a tokenizer iterator to iterate through column iCol. */
121863     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
121864     if( rc!=SQLITE_OK ) goto offsets_out;
121865     pC->pTokenizer = pTab->pTokenizer;
121866
121867     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
121868     while( rc==SQLITE_OK ){
121869       int i;                      /* Used to loop through terms */
121870       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
121871       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
121872
121873       for(i=0; i<nToken; i++){
121874         TermOffset *pT = &sCtx.aTerm[i];
121875         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
121876           iMinPos = pT->iPos-pT->iOff;
121877           pTerm = pT;
121878         }
121879       }
121880
121881       if( !pTerm ){
121882         /* All offsets for this column have been gathered. */
121883         break;
121884       }else{
121885         assert( iCurrent<=iMinPos );
121886         if( 0==(0xFE&*pTerm->pList) ){
121887           pTerm->pList = 0;
121888         }else{
121889           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
121890         }
121891         while( rc==SQLITE_OK && iCurrent<iMinPos ){
121892           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
121893         }
121894         if( rc==SQLITE_OK ){
121895           char aBuffer[64];
121896           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
121897               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
121898           );
121899           rc = fts3StringAppend(&res, aBuffer, -1);
121900         }else if( rc==SQLITE_DONE ){
121901           rc = SQLITE_CORRUPT;
121902         }
121903       }
121904     }
121905     if( rc==SQLITE_DONE ){
121906       rc = SQLITE_OK;
121907     }
121908
121909     pMod->xClose(pC);
121910     if( rc!=SQLITE_OK ) goto offsets_out;
121911   }
121912
121913  offsets_out:
121914   sqlite3_free(sCtx.aTerm);
121915   assert( rc!=SQLITE_DONE );
121916   sqlite3Fts3SegmentsClose(pTab);
121917   if( rc!=SQLITE_OK ){
121918     sqlite3_result_error_code(pCtx,  rc);
121919     sqlite3_free(res.z);
121920   }else{
121921     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
121922   }
121923   return;
121924 }
121925
121926 /*
121927 ** Implementation of matchinfo() function.
121928 */
121929 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
121930   sqlite3_context *pContext,      /* Function call context */
121931   Fts3Cursor *pCsr,               /* FTS3 table cursor */
121932   const char *zArg                /* Second arg to matchinfo() function */
121933 ){
121934   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121935   int rc;
121936   int i;
121937   const char *zFormat;
121938
121939   if( zArg ){
121940     for(i=0; zArg[i]; i++){
121941       char *zErr = 0;
121942       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
121943         sqlite3_result_error(pContext, zErr, -1);
121944         sqlite3_free(zErr);
121945         return;
121946       }
121947     }
121948     zFormat = zArg;
121949   }else{
121950     zFormat = FTS3_MATCHINFO_DEFAULT;
121951   }
121952
121953   if( !pCsr->pExpr ){
121954     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
121955     return;
121956   }
121957
121958   /* Retrieve matchinfo() data. */
121959   rc = fts3GetMatchinfo(pCsr, zFormat);
121960   sqlite3Fts3SegmentsClose(pTab);
121961
121962   if( rc!=SQLITE_OK ){
121963     sqlite3_result_error_code(pContext, rc);
121964   }else{
121965     int n = pCsr->nMatchinfo * sizeof(u32);
121966     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
121967   }
121968 }
121969
121970 #endif
121971
121972 /************** End of fts3_snippet.c ****************************************/
121973 /************** Begin file rtree.c *******************************************/
121974 /*
121975 ** 2001 September 15
121976 **
121977 ** The author disclaims copyright to this source code.  In place of
121978 ** a legal notice, here is a blessing:
121979 **
121980 **    May you do good and not evil.
121981 **    May you find forgiveness for yourself and forgive others.
121982 **    May you share freely, never taking more than you give.
121983 **
121984 *************************************************************************
121985 ** This file contains code for implementations of the r-tree and r*-tree
121986 ** algorithms packaged as an SQLite virtual table module.
121987 */
121988
121989 /*
121990 ** Database Format of R-Tree Tables
121991 ** --------------------------------
121992 **
121993 ** The data structure for a single virtual r-tree table is stored in three 
121994 ** native SQLite tables declared as follows. In each case, the '%' character
121995 ** in the table name is replaced with the user-supplied name of the r-tree
121996 ** table.
121997 **
121998 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
121999 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
122000 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
122001 **
122002 ** The data for each node of the r-tree structure is stored in the %_node
122003 ** table. For each node that is not the root node of the r-tree, there is
122004 ** an entry in the %_parent table associating the node with its parent.
122005 ** And for each row of data in the table, there is an entry in the %_rowid
122006 ** table that maps from the entries rowid to the id of the node that it
122007 ** is stored on.
122008 **
122009 ** The root node of an r-tree always exists, even if the r-tree table is
122010 ** empty. The nodeno of the root node is always 1. All other nodes in the
122011 ** table must be the same size as the root node. The content of each node
122012 ** is formatted as follows:
122013 **
122014 **   1. If the node is the root node (node 1), then the first 2 bytes
122015 **      of the node contain the tree depth as a big-endian integer.
122016 **      For non-root nodes, the first 2 bytes are left unused.
122017 **
122018 **   2. The next 2 bytes contain the number of entries currently 
122019 **      stored in the node.
122020 **
122021 **   3. The remainder of the node contains the node entries. Each entry
122022 **      consists of a single 8-byte integer followed by an even number
122023 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
122024 **      of a record. For internal nodes it is the node number of a
122025 **      child page.
122026 */
122027
122028 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
122029
122030 /*
122031 ** This file contains an implementation of a couple of different variants
122032 ** of the r-tree algorithm. See the README file for further details. The 
122033 ** same data-structure is used for all, but the algorithms for insert and
122034 ** delete operations vary. The variants used are selected at compile time 
122035 ** by defining the following symbols:
122036 */
122037
122038 /* Either, both or none of the following may be set to activate 
122039 ** r*tree variant algorithms.
122040 */
122041 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
122042 #define VARIANT_RSTARTREE_REINSERT      1
122043
122044 /* 
122045 ** Exactly one of the following must be set to 1.
122046 */
122047 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
122048 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
122049 #define VARIANT_RSTARTREE_SPLIT         1
122050
122051 #define VARIANT_GUTTMAN_SPLIT \
122052         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
122053
122054 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
122055   #define PickNext QuadraticPickNext
122056   #define PickSeeds QuadraticPickSeeds
122057   #define AssignCells splitNodeGuttman
122058 #endif
122059 #if VARIANT_GUTTMAN_LINEAR_SPLIT
122060   #define PickNext LinearPickNext
122061   #define PickSeeds LinearPickSeeds
122062   #define AssignCells splitNodeGuttman
122063 #endif
122064 #if VARIANT_RSTARTREE_SPLIT
122065   #define AssignCells splitNodeStartree
122066 #endif
122067
122068 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
122069 # define NDEBUG 1
122070 #endif
122071
122072 #ifndef SQLITE_CORE
122073   SQLITE_EXTENSION_INIT1
122074 #else
122075 #endif
122076
122077
122078 #ifndef SQLITE_AMALGAMATION
122079 #include "sqlite3rtree.h"
122080 typedef sqlite3_int64 i64;
122081 typedef unsigned char u8;
122082 typedef unsigned int u32;
122083 #endif
122084
122085 /*  The following macro is used to suppress compiler warnings.
122086 */
122087 #ifndef UNUSED_PARAMETER
122088 # define UNUSED_PARAMETER(x) (void)(x)
122089 #endif
122090
122091 typedef struct Rtree Rtree;
122092 typedef struct RtreeCursor RtreeCursor;
122093 typedef struct RtreeNode RtreeNode;
122094 typedef struct RtreeCell RtreeCell;
122095 typedef struct RtreeConstraint RtreeConstraint;
122096 typedef struct RtreeMatchArg RtreeMatchArg;
122097 typedef struct RtreeGeomCallback RtreeGeomCallback;
122098 typedef union RtreeCoord RtreeCoord;
122099
122100 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
122101 #define RTREE_MAX_DIMENSIONS 5
122102
122103 /* Size of hash table Rtree.aHash. This hash table is not expected to
122104 ** ever contain very many entries, so a fixed number of buckets is 
122105 ** used.
122106 */
122107 #define HASHSIZE 128
122108
122109 /* 
122110 ** An rtree virtual-table object.
122111 */
122112 struct Rtree {
122113   sqlite3_vtab base;
122114   sqlite3 *db;                /* Host database connection */
122115   int iNodeSize;              /* Size in bytes of each node in the node table */
122116   int nDim;                   /* Number of dimensions */
122117   int nBytesPerCell;          /* Bytes consumed per cell */
122118   int iDepth;                 /* Current depth of the r-tree structure */
122119   char *zDb;                  /* Name of database containing r-tree table */
122120   char *zName;                /* Name of r-tree table */ 
122121   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
122122   int nBusy;                  /* Current number of users of this structure */
122123
122124   /* List of nodes removed during a CondenseTree operation. List is
122125   ** linked together via the pointer normally used for hash chains -
122126   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
122127   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
122128   */
122129   RtreeNode *pDeleted;
122130   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
122131
122132   /* Statements to read/write/delete a record from xxx_node */
122133   sqlite3_stmt *pReadNode;
122134   sqlite3_stmt *pWriteNode;
122135   sqlite3_stmt *pDeleteNode;
122136
122137   /* Statements to read/write/delete a record from xxx_rowid */
122138   sqlite3_stmt *pReadRowid;
122139   sqlite3_stmt *pWriteRowid;
122140   sqlite3_stmt *pDeleteRowid;
122141
122142   /* Statements to read/write/delete a record from xxx_parent */
122143   sqlite3_stmt *pReadParent;
122144   sqlite3_stmt *pWriteParent;
122145   sqlite3_stmt *pDeleteParent;
122146
122147   int eCoordType;
122148 };
122149
122150 /* Possible values for eCoordType: */
122151 #define RTREE_COORD_REAL32 0
122152 #define RTREE_COORD_INT32  1
122153
122154 /*
122155 ** The minimum number of cells allowed for a node is a third of the 
122156 ** maximum. In Gutman's notation:
122157 **
122158 **     m = M/3
122159 **
122160 ** If an R*-tree "Reinsert" operation is required, the same number of
122161 ** cells are removed from the overfull node and reinserted into the tree.
122162 */
122163 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
122164 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
122165 #define RTREE_MAXCELLS 51
122166
122167 /*
122168 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
122169 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
122170 ** Therefore all non-root nodes must contain at least 3 entries. Since 
122171 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
122172 ** 40 or less.
122173 */
122174 #define RTREE_MAX_DEPTH 40
122175
122176 /* 
122177 ** An rtree cursor object.
122178 */
122179 struct RtreeCursor {
122180   sqlite3_vtab_cursor base;
122181   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
122182   int iCell;                        /* Index of current cell in pNode */
122183   int iStrategy;                    /* Copy of idxNum search parameter */
122184   int nConstraint;                  /* Number of entries in aConstraint */
122185   RtreeConstraint *aConstraint;     /* Search constraints. */
122186 };
122187
122188 union RtreeCoord {
122189   float f;
122190   int i;
122191 };
122192
122193 /*
122194 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
122195 ** formatted as a double. This macro assumes that local variable pRtree points
122196 ** to the Rtree structure associated with the RtreeCoord.
122197 */
122198 #define DCOORD(coord) (                           \
122199   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
122200     ((double)coord.f) :                           \
122201     ((double)coord.i)                             \
122202 )
122203
122204 /*
122205 ** A search constraint.
122206 */
122207 struct RtreeConstraint {
122208   int iCoord;                     /* Index of constrained coordinate */
122209   int op;                         /* Constraining operation */
122210   double rValue;                  /* Constraint value. */
122211   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122212   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
122213 };
122214
122215 /* Possible values for RtreeConstraint.op */
122216 #define RTREE_EQ    0x41
122217 #define RTREE_LE    0x42
122218 #define RTREE_LT    0x43
122219 #define RTREE_GE    0x44
122220 #define RTREE_GT    0x45
122221 #define RTREE_MATCH 0x46
122222
122223 /* 
122224 ** An rtree structure node.
122225 */
122226 struct RtreeNode {
122227   RtreeNode *pParent;               /* Parent node */
122228   i64 iNode;
122229   int nRef;
122230   int isDirty;
122231   u8 *zData;
122232   RtreeNode *pNext;                 /* Next node in this hash chain */
122233 };
122234 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
122235
122236 /* 
122237 ** Structure to store a deserialized rtree record.
122238 */
122239 struct RtreeCell {
122240   i64 iRowid;
122241   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
122242 };
122243
122244
122245 /*
122246 ** Value for the first field of every RtreeMatchArg object. The MATCH
122247 ** operator tests that the first field of a blob operand matches this
122248 ** value to avoid operating on invalid blobs (which could cause a segfault).
122249 */
122250 #define RTREE_GEOMETRY_MAGIC 0x891245AB
122251
122252 /*
122253 ** An instance of this structure must be supplied as a blob argument to
122254 ** the right-hand-side of an SQL MATCH operator used to constrain an
122255 ** r-tree query.
122256 */
122257 struct RtreeMatchArg {
122258   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
122259   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122260   void *pContext;
122261   int nParam;
122262   double aParam[1];
122263 };
122264
122265 /*
122266 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
122267 ** a single instance of the following structure is allocated. It is used
122268 ** as the context for the user-function created by by s_r_g_c(). The object
122269 ** is eventually deleted by the destructor mechanism provided by
122270 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
122271 ** the geometry callback function).
122272 */
122273 struct RtreeGeomCallback {
122274   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
122275   void *pContext;
122276 };
122277
122278 #ifndef MAX
122279 # define MAX(x,y) ((x) < (y) ? (y) : (x))
122280 #endif
122281 #ifndef MIN
122282 # define MIN(x,y) ((x) > (y) ? (y) : (x))
122283 #endif
122284
122285 /*
122286 ** Functions to deserialize a 16 bit integer, 32 bit real number and
122287 ** 64 bit integer. The deserialized value is returned.
122288 */
122289 static int readInt16(u8 *p){
122290   return (p[0]<<8) + p[1];
122291 }
122292 static void readCoord(u8 *p, RtreeCoord *pCoord){
122293   u32 i = (
122294     (((u32)p[0]) << 24) + 
122295     (((u32)p[1]) << 16) + 
122296     (((u32)p[2]) <<  8) + 
122297     (((u32)p[3]) <<  0)
122298   );
122299   *(u32 *)pCoord = i;
122300 }
122301 static i64 readInt64(u8 *p){
122302   return (
122303     (((i64)p[0]) << 56) + 
122304     (((i64)p[1]) << 48) + 
122305     (((i64)p[2]) << 40) + 
122306     (((i64)p[3]) << 32) + 
122307     (((i64)p[4]) << 24) + 
122308     (((i64)p[5]) << 16) + 
122309     (((i64)p[6]) <<  8) + 
122310     (((i64)p[7]) <<  0)
122311   );
122312 }
122313
122314 /*
122315 ** Functions to serialize a 16 bit integer, 32 bit real number and
122316 ** 64 bit integer. The value returned is the number of bytes written
122317 ** to the argument buffer (always 2, 4 and 8 respectively).
122318 */
122319 static int writeInt16(u8 *p, int i){
122320   p[0] = (i>> 8)&0xFF;
122321   p[1] = (i>> 0)&0xFF;
122322   return 2;
122323 }
122324 static int writeCoord(u8 *p, RtreeCoord *pCoord){
122325   u32 i;
122326   assert( sizeof(RtreeCoord)==4 );
122327   assert( sizeof(u32)==4 );
122328   i = *(u32 *)pCoord;
122329   p[0] = (i>>24)&0xFF;
122330   p[1] = (i>>16)&0xFF;
122331   p[2] = (i>> 8)&0xFF;
122332   p[3] = (i>> 0)&0xFF;
122333   return 4;
122334 }
122335 static int writeInt64(u8 *p, i64 i){
122336   p[0] = (i>>56)&0xFF;
122337   p[1] = (i>>48)&0xFF;
122338   p[2] = (i>>40)&0xFF;
122339   p[3] = (i>>32)&0xFF;
122340   p[4] = (i>>24)&0xFF;
122341   p[5] = (i>>16)&0xFF;
122342   p[6] = (i>> 8)&0xFF;
122343   p[7] = (i>> 0)&0xFF;
122344   return 8;
122345 }
122346
122347 /*
122348 ** Increment the reference count of node p.
122349 */
122350 static void nodeReference(RtreeNode *p){
122351   if( p ){
122352     p->nRef++;
122353   }
122354 }
122355
122356 /*
122357 ** Clear the content of node p (set all bytes to 0x00).
122358 */
122359 static void nodeZero(Rtree *pRtree, RtreeNode *p){
122360   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
122361   p->isDirty = 1;
122362 }
122363
122364 /*
122365 ** Given a node number iNode, return the corresponding key to use
122366 ** in the Rtree.aHash table.
122367 */
122368 static int nodeHash(i64 iNode){
122369   return (
122370     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
122371     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
122372   ) % HASHSIZE;
122373 }
122374
122375 /*
122376 ** Search the node hash table for node iNode. If found, return a pointer
122377 ** to it. Otherwise, return 0.
122378 */
122379 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
122380   RtreeNode *p;
122381   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
122382   return p;
122383 }
122384
122385 /*
122386 ** Add node pNode to the node hash table.
122387 */
122388 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
122389   int iHash;
122390   assert( pNode->pNext==0 );
122391   iHash = nodeHash(pNode->iNode);
122392   pNode->pNext = pRtree->aHash[iHash];
122393   pRtree->aHash[iHash] = pNode;
122394 }
122395
122396 /*
122397 ** Remove node pNode from the node hash table.
122398 */
122399 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
122400   RtreeNode **pp;
122401   if( pNode->iNode!=0 ){
122402     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
122403     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
122404     *pp = pNode->pNext;
122405     pNode->pNext = 0;
122406   }
122407 }
122408
122409 /*
122410 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
122411 ** indicating that node has not yet been assigned a node number. It is
122412 ** assigned a node number when nodeWrite() is called to write the
122413 ** node contents out to the database.
122414 */
122415 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
122416   RtreeNode *pNode;
122417   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
122418   if( pNode ){
122419     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
122420     pNode->zData = (u8 *)&pNode[1];
122421     pNode->nRef = 1;
122422     pNode->pParent = pParent;
122423     pNode->isDirty = 1;
122424     nodeReference(pParent);
122425   }
122426   return pNode;
122427 }
122428
122429 /*
122430 ** Obtain a reference to an r-tree node.
122431 */
122432 static int
122433 nodeAcquire(
122434   Rtree *pRtree,             /* R-tree structure */
122435   i64 iNode,                 /* Node number to load */
122436   RtreeNode *pParent,        /* Either the parent node or NULL */
122437   RtreeNode **ppNode         /* OUT: Acquired node */
122438 ){
122439   int rc;
122440   int rc2 = SQLITE_OK;
122441   RtreeNode *pNode;
122442
122443   /* Check if the requested node is already in the hash table. If so,
122444   ** increase its reference count and return it.
122445   */
122446   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
122447     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
122448     if( pParent && !pNode->pParent ){
122449       nodeReference(pParent);
122450       pNode->pParent = pParent;
122451     }
122452     pNode->nRef++;
122453     *ppNode = pNode;
122454     return SQLITE_OK;
122455   }
122456
122457   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
122458   rc = sqlite3_step(pRtree->pReadNode);
122459   if( rc==SQLITE_ROW ){
122460     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
122461     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
122462       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
122463       if( !pNode ){
122464         rc2 = SQLITE_NOMEM;
122465       }else{
122466         pNode->pParent = pParent;
122467         pNode->zData = (u8 *)&pNode[1];
122468         pNode->nRef = 1;
122469         pNode->iNode = iNode;
122470         pNode->isDirty = 0;
122471         pNode->pNext = 0;
122472         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
122473         nodeReference(pParent);
122474       }
122475     }
122476   }
122477   rc = sqlite3_reset(pRtree->pReadNode);
122478   if( rc==SQLITE_OK ) rc = rc2;
122479
122480   /* If the root node was just loaded, set pRtree->iDepth to the height
122481   ** of the r-tree structure. A height of zero means all data is stored on
122482   ** the root node. A height of one means the children of the root node
122483   ** are the leaves, and so on. If the depth as specified on the root node
122484   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
122485   */
122486   if( pNode && iNode==1 ){
122487     pRtree->iDepth = readInt16(pNode->zData);
122488     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
122489       rc = SQLITE_CORRUPT;
122490     }
122491   }
122492
122493   /* If no error has occurred so far, check if the "number of entries"
122494   ** field on the node is too large. If so, set the return code to 
122495   ** SQLITE_CORRUPT.
122496   */
122497   if( pNode && rc==SQLITE_OK ){
122498     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
122499       rc = SQLITE_CORRUPT;
122500     }
122501   }
122502
122503   if( rc==SQLITE_OK ){
122504     if( pNode!=0 ){
122505       nodeHashInsert(pRtree, pNode);
122506     }else{
122507       rc = SQLITE_CORRUPT;
122508     }
122509     *ppNode = pNode;
122510   }else{
122511     sqlite3_free(pNode);
122512     *ppNode = 0;
122513   }
122514
122515   return rc;
122516 }
122517
122518 /*
122519 ** Overwrite cell iCell of node pNode with the contents of pCell.
122520 */
122521 static void nodeOverwriteCell(
122522   Rtree *pRtree, 
122523   RtreeNode *pNode,  
122524   RtreeCell *pCell, 
122525   int iCell
122526 ){
122527   int ii;
122528   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122529   p += writeInt64(p, pCell->iRowid);
122530   for(ii=0; ii<(pRtree->nDim*2); ii++){
122531     p += writeCoord(p, &pCell->aCoord[ii]);
122532   }
122533   pNode->isDirty = 1;
122534 }
122535
122536 /*
122537 ** Remove cell the cell with index iCell from node pNode.
122538 */
122539 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
122540   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
122541   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
122542   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
122543   memmove(pDst, pSrc, nByte);
122544   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
122545   pNode->isDirty = 1;
122546 }
122547
122548 /*
122549 ** Insert the contents of cell pCell into node pNode. If the insert
122550 ** is successful, return SQLITE_OK.
122551 **
122552 ** If there is not enough free space in pNode, return SQLITE_FULL.
122553 */
122554 static int
122555 nodeInsertCell(
122556   Rtree *pRtree, 
122557   RtreeNode *pNode, 
122558   RtreeCell *pCell 
122559 ){
122560   int nCell;                    /* Current number of cells in pNode */
122561   int nMaxCell;                 /* Maximum number of cells for pNode */
122562
122563   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
122564   nCell = NCELL(pNode);
122565
122566   assert( nCell<=nMaxCell );
122567   if( nCell<nMaxCell ){
122568     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
122569     writeInt16(&pNode->zData[2], nCell+1);
122570     pNode->isDirty = 1;
122571   }
122572
122573   return (nCell==nMaxCell);
122574 }
122575
122576 /*
122577 ** If the node is dirty, write it out to the database.
122578 */
122579 static int
122580 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
122581   int rc = SQLITE_OK;
122582   if( pNode->isDirty ){
122583     sqlite3_stmt *p = pRtree->pWriteNode;
122584     if( pNode->iNode ){
122585       sqlite3_bind_int64(p, 1, pNode->iNode);
122586     }else{
122587       sqlite3_bind_null(p, 1);
122588     }
122589     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
122590     sqlite3_step(p);
122591     pNode->isDirty = 0;
122592     rc = sqlite3_reset(p);
122593     if( pNode->iNode==0 && rc==SQLITE_OK ){
122594       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
122595       nodeHashInsert(pRtree, pNode);
122596     }
122597   }
122598   return rc;
122599 }
122600
122601 /*
122602 ** Release a reference to a node. If the node is dirty and the reference
122603 ** count drops to zero, the node data is written to the database.
122604 */
122605 static int
122606 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
122607   int rc = SQLITE_OK;
122608   if( pNode ){
122609     assert( pNode->nRef>0 );
122610     pNode->nRef--;
122611     if( pNode->nRef==0 ){
122612       if( pNode->iNode==1 ){
122613         pRtree->iDepth = -1;
122614       }
122615       if( pNode->pParent ){
122616         rc = nodeRelease(pRtree, pNode->pParent);
122617       }
122618       if( rc==SQLITE_OK ){
122619         rc = nodeWrite(pRtree, pNode);
122620       }
122621       nodeHashDelete(pRtree, pNode);
122622       sqlite3_free(pNode);
122623     }
122624   }
122625   return rc;
122626 }
122627
122628 /*
122629 ** Return the 64-bit integer value associated with cell iCell of
122630 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
122631 ** an internal node, then the 64-bit integer is a child page number.
122632 */
122633 static i64 nodeGetRowid(
122634   Rtree *pRtree, 
122635   RtreeNode *pNode, 
122636   int iCell
122637 ){
122638   assert( iCell<NCELL(pNode) );
122639   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
122640 }
122641
122642 /*
122643 ** Return coordinate iCoord from cell iCell in node pNode.
122644 */
122645 static void nodeGetCoord(
122646   Rtree *pRtree, 
122647   RtreeNode *pNode, 
122648   int iCell,
122649   int iCoord,
122650   RtreeCoord *pCoord           /* Space to write result to */
122651 ){
122652   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
122653 }
122654
122655 /*
122656 ** Deserialize cell iCell of node pNode. Populate the structure pointed
122657 ** to by pCell with the results.
122658 */
122659 static void nodeGetCell(
122660   Rtree *pRtree, 
122661   RtreeNode *pNode, 
122662   int iCell,
122663   RtreeCell *pCell
122664 ){
122665   int ii;
122666   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
122667   for(ii=0; ii<pRtree->nDim*2; ii++){
122668     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
122669   }
122670 }
122671
122672
122673 /* Forward declaration for the function that does the work of
122674 ** the virtual table module xCreate() and xConnect() methods.
122675 */
122676 static int rtreeInit(
122677   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
122678 );
122679
122680 /* 
122681 ** Rtree virtual table module xCreate method.
122682 */
122683 static int rtreeCreate(
122684   sqlite3 *db,
122685   void *pAux,
122686   int argc, const char *const*argv,
122687   sqlite3_vtab **ppVtab,
122688   char **pzErr
122689 ){
122690   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
122691 }
122692
122693 /* 
122694 ** Rtree virtual table module xConnect method.
122695 */
122696 static int rtreeConnect(
122697   sqlite3 *db,
122698   void *pAux,
122699   int argc, const char *const*argv,
122700   sqlite3_vtab **ppVtab,
122701   char **pzErr
122702 ){
122703   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
122704 }
122705
122706 /*
122707 ** Increment the r-tree reference count.
122708 */
122709 static void rtreeReference(Rtree *pRtree){
122710   pRtree->nBusy++;
122711 }
122712
122713 /*
122714 ** Decrement the r-tree reference count. When the reference count reaches
122715 ** zero the structure is deleted.
122716 */
122717 static void rtreeRelease(Rtree *pRtree){
122718   pRtree->nBusy--;
122719   if( pRtree->nBusy==0 ){
122720     sqlite3_finalize(pRtree->pReadNode);
122721     sqlite3_finalize(pRtree->pWriteNode);
122722     sqlite3_finalize(pRtree->pDeleteNode);
122723     sqlite3_finalize(pRtree->pReadRowid);
122724     sqlite3_finalize(pRtree->pWriteRowid);
122725     sqlite3_finalize(pRtree->pDeleteRowid);
122726     sqlite3_finalize(pRtree->pReadParent);
122727     sqlite3_finalize(pRtree->pWriteParent);
122728     sqlite3_finalize(pRtree->pDeleteParent);
122729     sqlite3_free(pRtree);
122730   }
122731 }
122732
122733 /* 
122734 ** Rtree virtual table module xDisconnect method.
122735 */
122736 static int rtreeDisconnect(sqlite3_vtab *pVtab){
122737   rtreeRelease((Rtree *)pVtab);
122738   return SQLITE_OK;
122739 }
122740
122741 /* 
122742 ** Rtree virtual table module xDestroy method.
122743 */
122744 static int rtreeDestroy(sqlite3_vtab *pVtab){
122745   Rtree *pRtree = (Rtree *)pVtab;
122746   int rc;
122747   char *zCreate = sqlite3_mprintf(
122748     "DROP TABLE '%q'.'%q_node';"
122749     "DROP TABLE '%q'.'%q_rowid';"
122750     "DROP TABLE '%q'.'%q_parent';",
122751     pRtree->zDb, pRtree->zName, 
122752     pRtree->zDb, pRtree->zName,
122753     pRtree->zDb, pRtree->zName
122754   );
122755   if( !zCreate ){
122756     rc = SQLITE_NOMEM;
122757   }else{
122758     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
122759     sqlite3_free(zCreate);
122760   }
122761   if( rc==SQLITE_OK ){
122762     rtreeRelease(pRtree);
122763   }
122764
122765   return rc;
122766 }
122767
122768 /* 
122769 ** Rtree virtual table module xOpen method.
122770 */
122771 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
122772   int rc = SQLITE_NOMEM;
122773   RtreeCursor *pCsr;
122774
122775   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
122776   if( pCsr ){
122777     memset(pCsr, 0, sizeof(RtreeCursor));
122778     pCsr->base.pVtab = pVTab;
122779     rc = SQLITE_OK;
122780   }
122781   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
122782
122783   return rc;
122784 }
122785
122786
122787 /*
122788 ** Free the RtreeCursor.aConstraint[] array and its contents.
122789 */
122790 static void freeCursorConstraints(RtreeCursor *pCsr){
122791   if( pCsr->aConstraint ){
122792     int i;                        /* Used to iterate through constraint array */
122793     for(i=0; i<pCsr->nConstraint; i++){
122794       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
122795       if( pGeom ){
122796         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
122797         sqlite3_free(pGeom);
122798       }
122799     }
122800     sqlite3_free(pCsr->aConstraint);
122801     pCsr->aConstraint = 0;
122802   }
122803 }
122804
122805 /* 
122806 ** Rtree virtual table module xClose method.
122807 */
122808 static int rtreeClose(sqlite3_vtab_cursor *cur){
122809   Rtree *pRtree = (Rtree *)(cur->pVtab);
122810   int rc;
122811   RtreeCursor *pCsr = (RtreeCursor *)cur;
122812   freeCursorConstraints(pCsr);
122813   rc = nodeRelease(pRtree, pCsr->pNode);
122814   sqlite3_free(pCsr);
122815   return rc;
122816 }
122817
122818 /*
122819 ** Rtree virtual table module xEof method.
122820 **
122821 ** Return non-zero if the cursor does not currently point to a valid 
122822 ** record (i.e if the scan has finished), or zero otherwise.
122823 */
122824 static int rtreeEof(sqlite3_vtab_cursor *cur){
122825   RtreeCursor *pCsr = (RtreeCursor *)cur;
122826   return (pCsr->pNode==0);
122827 }
122828
122829 /*
122830 ** The r-tree constraint passed as the second argument to this function is
122831 ** guaranteed to be a MATCH constraint.
122832 */
122833 static int testRtreeGeom(
122834   Rtree *pRtree,                  /* R-Tree object */
122835   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
122836   RtreeCell *pCell,               /* Cell to test */
122837   int *pbRes                      /* OUT: Test result */
122838 ){
122839   int i;
122840   double aCoord[RTREE_MAX_DIMENSIONS*2];
122841   int nCoord = pRtree->nDim*2;
122842
122843   assert( pConstraint->op==RTREE_MATCH );
122844   assert( pConstraint->pGeom );
122845
122846   for(i=0; i<nCoord; i++){
122847     aCoord[i] = DCOORD(pCell->aCoord[i]);
122848   }
122849   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
122850 }
122851
122852 /* 
122853 ** Cursor pCursor currently points to a cell in a non-leaf page.
122854 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
122855 ** (excluded) by the constraints in the pCursor->aConstraint[] 
122856 ** array, or false otherwise.
122857 **
122858 ** Return SQLITE_OK if successful or an SQLite error code if an error
122859 ** occurs within a geometry callback.
122860 */
122861 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
122862   RtreeCell cell;
122863   int ii;
122864   int bRes = 0;
122865   int rc = SQLITE_OK;
122866
122867   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
122868   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
122869     RtreeConstraint *p = &pCursor->aConstraint[ii];
122870     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
122871     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
122872
122873     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
122874         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
122875     );
122876
122877     switch( p->op ){
122878       case RTREE_LE: case RTREE_LT: 
122879         bRes = p->rValue<cell_min; 
122880         break;
122881
122882       case RTREE_GE: case RTREE_GT: 
122883         bRes = p->rValue>cell_max; 
122884         break;
122885
122886       case RTREE_EQ:
122887         bRes = (p->rValue>cell_max || p->rValue<cell_min);
122888         break;
122889
122890       default: {
122891         assert( p->op==RTREE_MATCH );
122892         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
122893         bRes = !bRes;
122894         break;
122895       }
122896     }
122897   }
122898
122899   *pbEof = bRes;
122900   return rc;
122901 }
122902
122903 /* 
122904 ** Test if the cell that cursor pCursor currently points to
122905 ** would be filtered (excluded) by the constraints in the 
122906 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
122907 ** returning. If the cell is not filtered (excluded) by the constraints,
122908 ** set pbEof to zero.
122909 **
122910 ** Return SQLITE_OK if successful or an SQLite error code if an error
122911 ** occurs within a geometry callback.
122912 **
122913 ** This function assumes that the cell is part of a leaf node.
122914 */
122915 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
122916   RtreeCell cell;
122917   int ii;
122918   *pbEof = 0;
122919
122920   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
122921   for(ii=0; ii<pCursor->nConstraint; ii++){
122922     RtreeConstraint *p = &pCursor->aConstraint[ii];
122923     double coord = DCOORD(cell.aCoord[p->iCoord]);
122924     int res;
122925     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
122926         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
122927     );
122928     switch( p->op ){
122929       case RTREE_LE: res = (coord<=p->rValue); break;
122930       case RTREE_LT: res = (coord<p->rValue);  break;
122931       case RTREE_GE: res = (coord>=p->rValue); break;
122932       case RTREE_GT: res = (coord>p->rValue);  break;
122933       case RTREE_EQ: res = (coord==p->rValue); break;
122934       default: {
122935         int rc;
122936         assert( p->op==RTREE_MATCH );
122937         rc = testRtreeGeom(pRtree, p, &cell, &res);
122938         if( rc!=SQLITE_OK ){
122939           return rc;
122940         }
122941         break;
122942       }
122943     }
122944
122945     if( !res ){
122946       *pbEof = 1;
122947       return SQLITE_OK;
122948     }
122949   }
122950
122951   return SQLITE_OK;
122952 }
122953
122954 /*
122955 ** Cursor pCursor currently points at a node that heads a sub-tree of
122956 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
122957 ** to point to the left-most cell of the sub-tree that matches the 
122958 ** configured constraints.
122959 */
122960 static int descendToCell(
122961   Rtree *pRtree, 
122962   RtreeCursor *pCursor, 
122963   int iHeight,
122964   int *pEof                 /* OUT: Set to true if cannot descend */
122965 ){
122966   int isEof;
122967   int rc;
122968   int ii;
122969   RtreeNode *pChild;
122970   sqlite3_int64 iRowid;
122971
122972   RtreeNode *pSavedNode = pCursor->pNode;
122973   int iSavedCell = pCursor->iCell;
122974
122975   assert( iHeight>=0 );
122976
122977   if( iHeight==0 ){
122978     rc = testRtreeEntry(pRtree, pCursor, &isEof);
122979   }else{
122980     rc = testRtreeCell(pRtree, pCursor, &isEof);
122981   }
122982   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
122983     goto descend_to_cell_out;
122984   }
122985
122986   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
122987   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
122988   if( rc!=SQLITE_OK ){
122989     goto descend_to_cell_out;
122990   }
122991
122992   nodeRelease(pRtree, pCursor->pNode);
122993   pCursor->pNode = pChild;
122994   isEof = 1;
122995   for(ii=0; isEof && ii<NCELL(pChild); ii++){
122996     pCursor->iCell = ii;
122997     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
122998     if( rc!=SQLITE_OK ){
122999       goto descend_to_cell_out;
123000     }
123001   }
123002
123003   if( isEof ){
123004     assert( pCursor->pNode==pChild );
123005     nodeReference(pSavedNode);
123006     nodeRelease(pRtree, pChild);
123007     pCursor->pNode = pSavedNode;
123008     pCursor->iCell = iSavedCell;
123009   }
123010
123011 descend_to_cell_out:
123012   *pEof = isEof;
123013   return rc;
123014 }
123015
123016 /*
123017 ** One of the cells in node pNode is guaranteed to have a 64-bit 
123018 ** integer value equal to iRowid. Return the index of this cell.
123019 */
123020 static int nodeRowidIndex(
123021   Rtree *pRtree, 
123022   RtreeNode *pNode, 
123023   i64 iRowid,
123024   int *piIndex
123025 ){
123026   int ii;
123027   int nCell = NCELL(pNode);
123028   for(ii=0; ii<nCell; ii++){
123029     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
123030       *piIndex = ii;
123031       return SQLITE_OK;
123032     }
123033   }
123034   return SQLITE_CORRUPT;
123035 }
123036
123037 /*
123038 ** Return the index of the cell containing a pointer to node pNode
123039 ** in its parent. If pNode is the root node, return -1.
123040 */
123041 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
123042   RtreeNode *pParent = pNode->pParent;
123043   if( pParent ){
123044     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
123045   }
123046   *piIndex = -1;
123047   return SQLITE_OK;
123048 }
123049
123050 /* 
123051 ** Rtree virtual table module xNext method.
123052 */
123053 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
123054   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
123055   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123056   int rc = SQLITE_OK;
123057
123058   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
123059   ** already at EOF. It is against the rules to call the xNext() method of
123060   ** a cursor that has already reached EOF.
123061   */
123062   assert( pCsr->pNode );
123063
123064   if( pCsr->iStrategy==1 ){
123065     /* This "scan" is a direct lookup by rowid. There is no next entry. */
123066     nodeRelease(pRtree, pCsr->pNode);
123067     pCsr->pNode = 0;
123068   }else{
123069     /* Move to the next entry that matches the configured constraints. */
123070     int iHeight = 0;
123071     while( pCsr->pNode ){
123072       RtreeNode *pNode = pCsr->pNode;
123073       int nCell = NCELL(pNode);
123074       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
123075         int isEof;
123076         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
123077         if( rc!=SQLITE_OK || !isEof ){
123078           return rc;
123079         }
123080       }
123081       pCsr->pNode = pNode->pParent;
123082       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
123083       if( rc!=SQLITE_OK ){
123084         return rc;
123085       }
123086       nodeReference(pCsr->pNode);
123087       nodeRelease(pRtree, pNode);
123088       iHeight++;
123089     }
123090   }
123091
123092   return rc;
123093 }
123094
123095 /* 
123096 ** Rtree virtual table module xRowid method.
123097 */
123098 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
123099   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123100   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123101
123102   assert(pCsr->pNode);
123103   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123104
123105   return SQLITE_OK;
123106 }
123107
123108 /* 
123109 ** Rtree virtual table module xColumn method.
123110 */
123111 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
123112   Rtree *pRtree = (Rtree *)cur->pVtab;
123113   RtreeCursor *pCsr = (RtreeCursor *)cur;
123114
123115   if( i==0 ){
123116     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
123117     sqlite3_result_int64(ctx, iRowid);
123118   }else{
123119     RtreeCoord c;
123120     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
123121     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123122       sqlite3_result_double(ctx, c.f);
123123     }else{
123124       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
123125       sqlite3_result_int(ctx, c.i);
123126     }
123127   }
123128
123129   return SQLITE_OK;
123130 }
123131
123132 /* 
123133 ** Use nodeAcquire() to obtain the leaf node containing the record with 
123134 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
123135 ** return SQLITE_OK. If there is no such record in the table, set
123136 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
123137 ** to zero and return an SQLite error code.
123138 */
123139 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
123140   int rc;
123141   *ppLeaf = 0;
123142   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
123143   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
123144     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
123145     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
123146     sqlite3_reset(pRtree->pReadRowid);
123147   }else{
123148     rc = sqlite3_reset(pRtree->pReadRowid);
123149   }
123150   return rc;
123151 }
123152
123153 /*
123154 ** This function is called to configure the RtreeConstraint object passed
123155 ** as the second argument for a MATCH constraint. The value passed as the
123156 ** first argument to this function is the right-hand operand to the MATCH
123157 ** operator.
123158 */
123159 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
123160   RtreeMatchArg *p;
123161   sqlite3_rtree_geometry *pGeom;
123162   int nBlob;
123163
123164   /* Check that value is actually a blob. */
123165   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
123166
123167   /* Check that the blob is roughly the right size. */
123168   nBlob = sqlite3_value_bytes(pValue);
123169   if( nBlob<(int)sizeof(RtreeMatchArg) 
123170    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
123171   ){
123172     return SQLITE_ERROR;
123173   }
123174
123175   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
123176       sizeof(sqlite3_rtree_geometry) + nBlob
123177   );
123178   if( !pGeom ) return SQLITE_NOMEM;
123179   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
123180   p = (RtreeMatchArg *)&pGeom[1];
123181
123182   memcpy(p, sqlite3_value_blob(pValue), nBlob);
123183   if( p->magic!=RTREE_GEOMETRY_MAGIC 
123184    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
123185   ){
123186     sqlite3_free(pGeom);
123187     return SQLITE_ERROR;
123188   }
123189
123190   pGeom->pContext = p->pContext;
123191   pGeom->nParam = p->nParam;
123192   pGeom->aParam = p->aParam;
123193
123194   pCons->xGeom = p->xGeom;
123195   pCons->pGeom = pGeom;
123196   return SQLITE_OK;
123197 }
123198
123199 /* 
123200 ** Rtree virtual table module xFilter method.
123201 */
123202 static int rtreeFilter(
123203   sqlite3_vtab_cursor *pVtabCursor, 
123204   int idxNum, const char *idxStr,
123205   int argc, sqlite3_value **argv
123206 ){
123207   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
123208   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
123209
123210   RtreeNode *pRoot = 0;
123211   int ii;
123212   int rc = SQLITE_OK;
123213
123214   rtreeReference(pRtree);
123215
123216   freeCursorConstraints(pCsr);
123217   pCsr->iStrategy = idxNum;
123218
123219   if( idxNum==1 ){
123220     /* Special case - lookup by rowid. */
123221     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
123222     i64 iRowid = sqlite3_value_int64(argv[0]);
123223     rc = findLeafNode(pRtree, iRowid, &pLeaf);
123224     pCsr->pNode = pLeaf; 
123225     if( pLeaf ){
123226       assert( rc==SQLITE_OK );
123227       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
123228     }
123229   }else{
123230     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
123231     ** with the configured constraints. 
123232     */
123233     if( argc>0 ){
123234       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
123235       pCsr->nConstraint = argc;
123236       if( !pCsr->aConstraint ){
123237         rc = SQLITE_NOMEM;
123238       }else{
123239         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
123240         assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
123241         for(ii=0; ii<argc; ii++){
123242           RtreeConstraint *p = &pCsr->aConstraint[ii];
123243           p->op = idxStr[ii*2];
123244           p->iCoord = idxStr[ii*2+1]-'a';
123245           if( p->op==RTREE_MATCH ){
123246             /* A MATCH operator. The right-hand-side must be a blob that
123247             ** can be cast into an RtreeMatchArg object. One created using
123248             ** an sqlite3_rtree_geometry_callback() SQL user function.
123249             */
123250             rc = deserializeGeometry(argv[ii], p);
123251             if( rc!=SQLITE_OK ){
123252               break;
123253             }
123254           }else{
123255             p->rValue = sqlite3_value_double(argv[ii]);
123256           }
123257         }
123258       }
123259     }
123260   
123261     if( rc==SQLITE_OK ){
123262       pCsr->pNode = 0;
123263       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
123264     }
123265     if( rc==SQLITE_OK ){
123266       int isEof = 1;
123267       int nCell = NCELL(pRoot);
123268       pCsr->pNode = pRoot;
123269       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
123270         assert( pCsr->pNode==pRoot );
123271         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
123272         if( !isEof ){
123273           break;
123274         }
123275       }
123276       if( rc==SQLITE_OK && isEof ){
123277         assert( pCsr->pNode==pRoot );
123278         nodeRelease(pRtree, pRoot);
123279         pCsr->pNode = 0;
123280       }
123281       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
123282     }
123283   }
123284
123285   rtreeRelease(pRtree);
123286   return rc;
123287 }
123288
123289 /*
123290 ** Rtree virtual table module xBestIndex method. There are three
123291 ** table scan strategies to choose from (in order from most to 
123292 ** least desirable):
123293 **
123294 **   idxNum     idxStr        Strategy
123295 **   ------------------------------------------------
123296 **     1        Unused        Direct lookup by rowid.
123297 **     2        See below     R-tree query or full-table scan.
123298 **   ------------------------------------------------
123299 **
123300 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
123301 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
123302 ** constraint used. The first two bytes of idxStr correspond to 
123303 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
123304 ** (argvIndex==1) etc.
123305 **
123306 ** The first of each pair of bytes in idxStr identifies the constraint
123307 ** operator as follows:
123308 **
123309 **   Operator    Byte Value
123310 **   ----------------------
123311 **      =        0x41 ('A')
123312 **     <=        0x42 ('B')
123313 **      <        0x43 ('C')
123314 **     >=        0x44 ('D')
123315 **      >        0x45 ('E')
123316 **   MATCH       0x46 ('F')
123317 **   ----------------------
123318 **
123319 ** The second of each pair of bytes identifies the coordinate column
123320 ** to which the constraint applies. The leftmost coordinate column
123321 ** is 'a', the second from the left 'b' etc.
123322 */
123323 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
123324   int rc = SQLITE_OK;
123325   int ii;
123326
123327   int iIdx = 0;
123328   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
123329   memset(zIdxStr, 0, sizeof(zIdxStr));
123330   UNUSED_PARAMETER(tab);
123331
123332   assert( pIdxInfo->idxStr==0 );
123333   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
123334     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
123335
123336     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
123337       /* We have an equality constraint on the rowid. Use strategy 1. */
123338       int jj;
123339       for(jj=0; jj<ii; jj++){
123340         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
123341         pIdxInfo->aConstraintUsage[jj].omit = 0;
123342       }
123343       pIdxInfo->idxNum = 1;
123344       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
123345       pIdxInfo->aConstraintUsage[jj].omit = 1;
123346
123347       /* This strategy involves a two rowid lookups on an B-Tree structures
123348       ** and then a linear search of an R-Tree node. This should be 
123349       ** considered almost as quick as a direct rowid lookup (for which 
123350       ** sqlite uses an internal cost of 0.0).
123351       */ 
123352       pIdxInfo->estimatedCost = 10.0;
123353       return SQLITE_OK;
123354     }
123355
123356     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
123357       u8 op;
123358       switch( p->op ){
123359         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
123360         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
123361         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
123362         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
123363         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
123364         default:
123365           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
123366           op = RTREE_MATCH; 
123367           break;
123368       }
123369       zIdxStr[iIdx++] = op;
123370       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
123371       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
123372       pIdxInfo->aConstraintUsage[ii].omit = 1;
123373     }
123374   }
123375
123376   pIdxInfo->idxNum = 2;
123377   pIdxInfo->needToFreeIdxStr = 1;
123378   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
123379     return SQLITE_NOMEM;
123380   }
123381   assert( iIdx>=0 );
123382   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
123383   return rc;
123384 }
123385
123386 /*
123387 ** Return the N-dimensional volumn of the cell stored in *p.
123388 */
123389 static float cellArea(Rtree *pRtree, RtreeCell *p){
123390   float area = 1.0;
123391   int ii;
123392   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123393     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123394   }
123395   return area;
123396 }
123397
123398 /*
123399 ** Return the margin length of cell p. The margin length is the sum
123400 ** of the objects size in each dimension.
123401 */
123402 static float cellMargin(Rtree *pRtree, RtreeCell *p){
123403   float margin = 0.0;
123404   int ii;
123405   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123406     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
123407   }
123408   return margin;
123409 }
123410
123411 /*
123412 ** Store the union of cells p1 and p2 in p1.
123413 */
123414 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123415   int ii;
123416   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
123417     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123418       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
123419       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
123420     }
123421   }else{
123422     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123423       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
123424       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
123425     }
123426   }
123427 }
123428
123429 /*
123430 ** Return true if the area covered by p2 is a subset of the area covered
123431 ** by p1. False otherwise.
123432 */
123433 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
123434   int ii;
123435   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
123436   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
123437     RtreeCoord *a1 = &p1->aCoord[ii];
123438     RtreeCoord *a2 = &p2->aCoord[ii];
123439     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
123440      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
123441     ){
123442       return 0;
123443     }
123444   }
123445   return 1;
123446 }
123447
123448 /*
123449 ** Return the amount cell p would grow by if it were unioned with pCell.
123450 */
123451 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
123452   float area;
123453   RtreeCell cell;
123454   memcpy(&cell, p, sizeof(RtreeCell));
123455   area = cellArea(pRtree, &cell);
123456   cellUnion(pRtree, &cell, pCell);
123457   return (cellArea(pRtree, &cell)-area);
123458 }
123459
123460 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
123461 static float cellOverlap(
123462   Rtree *pRtree, 
123463   RtreeCell *p, 
123464   RtreeCell *aCell, 
123465   int nCell, 
123466   int iExclude
123467 ){
123468   int ii;
123469   float overlap = 0.0;
123470   for(ii=0; ii<nCell; ii++){
123471 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123472     if( ii!=iExclude )
123473 #else
123474     assert( iExclude==-1 );
123475     UNUSED_PARAMETER(iExclude);
123476 #endif
123477     {
123478       int jj;
123479       float o = 1.0;
123480       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
123481         double x1;
123482         double x2;
123483
123484         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
123485         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
123486
123487         if( x2<x1 ){
123488           o = 0.0;
123489           break;
123490         }else{
123491           o = o * (x2-x1);
123492         }
123493       }
123494       overlap += o;
123495     }
123496   }
123497   return overlap;
123498 }
123499 #endif
123500
123501 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123502 static float cellOverlapEnlargement(
123503   Rtree *pRtree, 
123504   RtreeCell *p, 
123505   RtreeCell *pInsert, 
123506   RtreeCell *aCell, 
123507   int nCell, 
123508   int iExclude
123509 ){
123510   float before;
123511   float after;
123512   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123513   cellUnion(pRtree, p, pInsert);
123514   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
123515   return after-before;
123516 }
123517 #endif
123518
123519
123520 /*
123521 ** This function implements the ChooseLeaf algorithm from Gutman[84].
123522 ** ChooseSubTree in r*tree terminology.
123523 */
123524 static int ChooseLeaf(
123525   Rtree *pRtree,               /* Rtree table */
123526   RtreeCell *pCell,            /* Cell to insert into rtree */
123527   int iHeight,                 /* Height of sub-tree rooted at pCell */
123528   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
123529 ){
123530   int rc;
123531   int ii;
123532   RtreeNode *pNode;
123533   rc = nodeAcquire(pRtree, 1, 0, &pNode);
123534
123535   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
123536     int iCell;
123537     sqlite3_int64 iBest;
123538
123539     float fMinGrowth;
123540     float fMinArea;
123541     float fMinOverlap;
123542
123543     int nCell = NCELL(pNode);
123544     RtreeCell cell;
123545     RtreeNode *pChild;
123546
123547     RtreeCell *aCell = 0;
123548
123549 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123550     if( ii==(pRtree->iDepth-1) ){
123551       int jj;
123552       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
123553       if( !aCell ){
123554         rc = SQLITE_NOMEM;
123555         nodeRelease(pRtree, pNode);
123556         pNode = 0;
123557         continue;
123558       }
123559       for(jj=0; jj<nCell; jj++){
123560         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
123561       }
123562     }
123563 #endif
123564
123565     /* Select the child node which will be enlarged the least if pCell
123566     ** is inserted into it. Resolve ties by choosing the entry with
123567     ** the smallest area.
123568     */
123569     for(iCell=0; iCell<nCell; iCell++){
123570       int bBest = 0;
123571       float growth;
123572       float area;
123573       float overlap = 0.0;
123574       nodeGetCell(pRtree, pNode, iCell, &cell);
123575       growth = cellGrowth(pRtree, &cell, pCell);
123576       area = cellArea(pRtree, &cell);
123577
123578 #if VARIANT_RSTARTREE_CHOOSESUBTREE
123579       if( ii==(pRtree->iDepth-1) ){
123580         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
123581       }
123582       if( (iCell==0) 
123583        || (overlap<fMinOverlap) 
123584        || (overlap==fMinOverlap && growth<fMinGrowth)
123585        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
123586       ){
123587         bBest = 1;
123588       }
123589 #else
123590       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
123591         bBest = 1;
123592       }
123593 #endif
123594       if( bBest ){
123595         fMinOverlap = overlap;
123596         fMinGrowth = growth;
123597         fMinArea = area;
123598         iBest = cell.iRowid;
123599       }
123600     }
123601
123602     sqlite3_free(aCell);
123603     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
123604     nodeRelease(pRtree, pNode);
123605     pNode = pChild;
123606   }
123607
123608   *ppLeaf = pNode;
123609   return rc;
123610 }
123611
123612 /*
123613 ** A cell with the same content as pCell has just been inserted into
123614 ** the node pNode. This function updates the bounding box cells in
123615 ** all ancestor elements.
123616 */
123617 static int AdjustTree(
123618   Rtree *pRtree,                    /* Rtree table */
123619   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
123620   RtreeCell *pCell                  /* This cell was just inserted */
123621 ){
123622   RtreeNode *p = pNode;
123623   while( p->pParent ){
123624     RtreeNode *pParent = p->pParent;
123625     RtreeCell cell;
123626     int iCell;
123627
123628     if( nodeParentIndex(pRtree, p, &iCell) ){
123629       return SQLITE_CORRUPT;
123630     }
123631
123632     nodeGetCell(pRtree, pParent, iCell, &cell);
123633     if( !cellContains(pRtree, &cell, pCell) ){
123634       cellUnion(pRtree, &cell, pCell);
123635       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
123636     }
123637  
123638     p = pParent;
123639   }
123640   return SQLITE_OK;
123641 }
123642
123643 /*
123644 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
123645 */
123646 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
123647   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
123648   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
123649   sqlite3_step(pRtree->pWriteRowid);
123650   return sqlite3_reset(pRtree->pWriteRowid);
123651 }
123652
123653 /*
123654 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
123655 */
123656 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
123657   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
123658   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
123659   sqlite3_step(pRtree->pWriteParent);
123660   return sqlite3_reset(pRtree->pWriteParent);
123661 }
123662
123663 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
123664
123665 #if VARIANT_GUTTMAN_LINEAR_SPLIT
123666 /*
123667 ** Implementation of the linear variant of the PickNext() function from
123668 ** Guttman[84].
123669 */
123670 static RtreeCell *LinearPickNext(
123671   Rtree *pRtree,
123672   RtreeCell *aCell, 
123673   int nCell, 
123674   RtreeCell *pLeftBox, 
123675   RtreeCell *pRightBox,
123676   int *aiUsed
123677 ){
123678   int ii;
123679   for(ii=0; aiUsed[ii]; ii++);
123680   aiUsed[ii] = 1;
123681   return &aCell[ii];
123682 }
123683
123684 /*
123685 ** Implementation of the linear variant of the PickSeeds() function from
123686 ** Guttman[84].
123687 */
123688 static void LinearPickSeeds(
123689   Rtree *pRtree,
123690   RtreeCell *aCell, 
123691   int nCell, 
123692   int *piLeftSeed, 
123693   int *piRightSeed
123694 ){
123695   int i;
123696   int iLeftSeed = 0;
123697   int iRightSeed = 1;
123698   float maxNormalInnerWidth = 0.0;
123699
123700   /* Pick two "seed" cells from the array of cells. The algorithm used
123701   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
123702   ** indices of the two seed cells in the array are stored in local
123703   ** variables iLeftSeek and iRightSeed.
123704   */
123705   for(i=0; i<pRtree->nDim; i++){
123706     float x1 = DCOORD(aCell[0].aCoord[i*2]);
123707     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
123708     float x3 = x1;
123709     float x4 = x2;
123710     int jj;
123711
123712     int iCellLeft = 0;
123713     int iCellRight = 0;
123714
123715     for(jj=1; jj<nCell; jj++){
123716       float left = DCOORD(aCell[jj].aCoord[i*2]);
123717       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
123718
123719       if( left<x1 ) x1 = left;
123720       if( right>x4 ) x4 = right;
123721       if( left>x3 ){
123722         x3 = left;
123723         iCellRight = jj;
123724       }
123725       if( right<x2 ){
123726         x2 = right;
123727         iCellLeft = jj;
123728       }
123729     }
123730
123731     if( x4!=x1 ){
123732       float normalwidth = (x3 - x2) / (x4 - x1);
123733       if( normalwidth>maxNormalInnerWidth ){
123734         iLeftSeed = iCellLeft;
123735         iRightSeed = iCellRight;
123736       }
123737     }
123738   }
123739
123740   *piLeftSeed = iLeftSeed;
123741   *piRightSeed = iRightSeed;
123742 }
123743 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
123744
123745 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
123746 /*
123747 ** Implementation of the quadratic variant of the PickNext() function from
123748 ** Guttman[84].
123749 */
123750 static RtreeCell *QuadraticPickNext(
123751   Rtree *pRtree,
123752   RtreeCell *aCell, 
123753   int nCell, 
123754   RtreeCell *pLeftBox, 
123755   RtreeCell *pRightBox,
123756   int *aiUsed
123757 ){
123758   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
123759
123760   int iSelect = -1;
123761   float fDiff;
123762   int ii;
123763   for(ii=0; ii<nCell; ii++){
123764     if( aiUsed[ii]==0 ){
123765       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
123766       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
123767       float diff = FABS(right-left);
123768       if( iSelect<0 || diff>fDiff ){
123769         fDiff = diff;
123770         iSelect = ii;
123771       }
123772     }
123773   }
123774   aiUsed[iSelect] = 1;
123775   return &aCell[iSelect];
123776 }
123777
123778 /*
123779 ** Implementation of the quadratic variant of the PickSeeds() function from
123780 ** Guttman[84].
123781 */
123782 static void QuadraticPickSeeds(
123783   Rtree *pRtree,
123784   RtreeCell *aCell, 
123785   int nCell, 
123786   int *piLeftSeed, 
123787   int *piRightSeed
123788 ){
123789   int ii;
123790   int jj;
123791
123792   int iLeftSeed = 0;
123793   int iRightSeed = 1;
123794   float fWaste = 0.0;
123795
123796   for(ii=0; ii<nCell; ii++){
123797     for(jj=ii+1; jj<nCell; jj++){
123798       float right = cellArea(pRtree, &aCell[jj]);
123799       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
123800       float waste = growth - right;
123801
123802       if( waste>fWaste ){
123803         iLeftSeed = ii;
123804         iRightSeed = jj;
123805         fWaste = waste;
123806       }
123807     }
123808   }
123809
123810   *piLeftSeed = iLeftSeed;
123811   *piRightSeed = iRightSeed;
123812 }
123813 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
123814
123815 /*
123816 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
123817 ** nIdx. The aIdx array contains the set of integers from 0 to 
123818 ** (nIdx-1) in no particular order. This function sorts the values
123819 ** in aIdx according to the indexed values in aDistance. For
123820 ** example, assuming the inputs:
123821 **
123822 **   aIdx      = { 0,   1,   2,   3 }
123823 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
123824 **
123825 ** this function sets the aIdx array to contain:
123826 **
123827 **   aIdx      = { 0,   1,   2,   3 }
123828 **
123829 ** The aSpare array is used as temporary working space by the
123830 ** sorting algorithm.
123831 */
123832 static void SortByDistance(
123833   int *aIdx, 
123834   int nIdx, 
123835   float *aDistance, 
123836   int *aSpare
123837 ){
123838   if( nIdx>1 ){
123839     int iLeft = 0;
123840     int iRight = 0;
123841
123842     int nLeft = nIdx/2;
123843     int nRight = nIdx-nLeft;
123844     int *aLeft = aIdx;
123845     int *aRight = &aIdx[nLeft];
123846
123847     SortByDistance(aLeft, nLeft, aDistance, aSpare);
123848     SortByDistance(aRight, nRight, aDistance, aSpare);
123849
123850     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
123851     aLeft = aSpare;
123852
123853     while( iLeft<nLeft || iRight<nRight ){
123854       if( iLeft==nLeft ){
123855         aIdx[iLeft+iRight] = aRight[iRight];
123856         iRight++;
123857       }else if( iRight==nRight ){
123858         aIdx[iLeft+iRight] = aLeft[iLeft];
123859         iLeft++;
123860       }else{
123861         float fLeft = aDistance[aLeft[iLeft]];
123862         float fRight = aDistance[aRight[iRight]];
123863         if( fLeft<fRight ){
123864           aIdx[iLeft+iRight] = aLeft[iLeft];
123865           iLeft++;
123866         }else{
123867           aIdx[iLeft+iRight] = aRight[iRight];
123868           iRight++;
123869         }
123870       }
123871     }
123872
123873 #if 0
123874     /* Check that the sort worked */
123875     {
123876       int jj;
123877       for(jj=1; jj<nIdx; jj++){
123878         float left = aDistance[aIdx[jj-1]];
123879         float right = aDistance[aIdx[jj]];
123880         assert( left<=right );
123881       }
123882     }
123883 #endif
123884   }
123885 }
123886
123887 /*
123888 ** Arguments aIdx, aCell and aSpare all point to arrays of size
123889 ** nIdx. The aIdx array contains the set of integers from 0 to 
123890 ** (nIdx-1) in no particular order. This function sorts the values
123891 ** in aIdx according to dimension iDim of the cells in aCell. The
123892 ** minimum value of dimension iDim is considered first, the
123893 ** maximum used to break ties.
123894 **
123895 ** The aSpare array is used as temporary working space by the
123896 ** sorting algorithm.
123897 */
123898 static void SortByDimension(
123899   Rtree *pRtree,
123900   int *aIdx, 
123901   int nIdx, 
123902   int iDim, 
123903   RtreeCell *aCell, 
123904   int *aSpare
123905 ){
123906   if( nIdx>1 ){
123907
123908     int iLeft = 0;
123909     int iRight = 0;
123910
123911     int nLeft = nIdx/2;
123912     int nRight = nIdx-nLeft;
123913     int *aLeft = aIdx;
123914     int *aRight = &aIdx[nLeft];
123915
123916     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
123917     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
123918
123919     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
123920     aLeft = aSpare;
123921     while( iLeft<nLeft || iRight<nRight ){
123922       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
123923       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
123924       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
123925       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
123926       if( (iLeft!=nLeft) && ((iRight==nRight)
123927        || (xleft1<xright1)
123928        || (xleft1==xright1 && xleft2<xright2)
123929       )){
123930         aIdx[iLeft+iRight] = aLeft[iLeft];
123931         iLeft++;
123932       }else{
123933         aIdx[iLeft+iRight] = aRight[iRight];
123934         iRight++;
123935       }
123936     }
123937
123938 #if 0
123939     /* Check that the sort worked */
123940     {
123941       int jj;
123942       for(jj=1; jj<nIdx; jj++){
123943         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
123944         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
123945         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
123946         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
123947         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
123948       }
123949     }
123950 #endif
123951   }
123952 }
123953
123954 #if VARIANT_RSTARTREE_SPLIT
123955 /*
123956 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
123957 */
123958 static int splitNodeStartree(
123959   Rtree *pRtree,
123960   RtreeCell *aCell,
123961   int nCell,
123962   RtreeNode *pLeft,
123963   RtreeNode *pRight,
123964   RtreeCell *pBboxLeft,
123965   RtreeCell *pBboxRight
123966 ){
123967   int **aaSorted;
123968   int *aSpare;
123969   int ii;
123970
123971   int iBestDim;
123972   int iBestSplit;
123973   float fBestMargin;
123974
123975   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
123976
123977   aaSorted = (int **)sqlite3_malloc(nByte);
123978   if( !aaSorted ){
123979     return SQLITE_NOMEM;
123980   }
123981
123982   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
123983   memset(aaSorted, 0, nByte);
123984   for(ii=0; ii<pRtree->nDim; ii++){
123985     int jj;
123986     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
123987     for(jj=0; jj<nCell; jj++){
123988       aaSorted[ii][jj] = jj;
123989     }
123990     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
123991   }
123992
123993   for(ii=0; ii<pRtree->nDim; ii++){
123994     float margin = 0.0;
123995     float fBestOverlap;
123996     float fBestArea;
123997     int iBestLeft;
123998     int nLeft;
123999
124000     for(
124001       nLeft=RTREE_MINCELLS(pRtree); 
124002       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
124003       nLeft++
124004     ){
124005       RtreeCell left;
124006       RtreeCell right;
124007       int kk;
124008       float overlap;
124009       float area;
124010
124011       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
124012       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
124013       for(kk=1; kk<(nCell-1); kk++){
124014         if( kk<nLeft ){
124015           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
124016         }else{
124017           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
124018         }
124019       }
124020       margin += cellMargin(pRtree, &left);
124021       margin += cellMargin(pRtree, &right);
124022       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
124023       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
124024       if( (nLeft==RTREE_MINCELLS(pRtree))
124025        || (overlap<fBestOverlap)
124026        || (overlap==fBestOverlap && area<fBestArea)
124027       ){
124028         iBestLeft = nLeft;
124029         fBestOverlap = overlap;
124030         fBestArea = area;
124031       }
124032     }
124033
124034     if( ii==0 || margin<fBestMargin ){
124035       iBestDim = ii;
124036       fBestMargin = margin;
124037       iBestSplit = iBestLeft;
124038     }
124039   }
124040
124041   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
124042   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
124043   for(ii=0; ii<nCell; ii++){
124044     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
124045     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
124046     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
124047     nodeInsertCell(pRtree, pTarget, pCell);
124048     cellUnion(pRtree, pBbox, pCell);
124049   }
124050
124051   sqlite3_free(aaSorted);
124052   return SQLITE_OK;
124053 }
124054 #endif
124055
124056 #if VARIANT_GUTTMAN_SPLIT
124057 /*
124058 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
124059 */
124060 static int splitNodeGuttman(
124061   Rtree *pRtree,
124062   RtreeCell *aCell,
124063   int nCell,
124064   RtreeNode *pLeft,
124065   RtreeNode *pRight,
124066   RtreeCell *pBboxLeft,
124067   RtreeCell *pBboxRight
124068 ){
124069   int iLeftSeed = 0;
124070   int iRightSeed = 1;
124071   int *aiUsed;
124072   int i;
124073
124074   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
124075   if( !aiUsed ){
124076     return SQLITE_NOMEM;
124077   }
124078   memset(aiUsed, 0, sizeof(int)*nCell);
124079
124080   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
124081
124082   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
124083   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
124084   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
124085   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
124086   aiUsed[iLeftSeed] = 1;
124087   aiUsed[iRightSeed] = 1;
124088
124089   for(i=nCell-2; i>0; i--){
124090     RtreeCell *pNext;
124091     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
124092     float diff =  
124093       cellGrowth(pRtree, pBboxLeft, pNext) - 
124094       cellGrowth(pRtree, pBboxRight, pNext)
124095     ;
124096     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
124097      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
124098     ){
124099       nodeInsertCell(pRtree, pRight, pNext);
124100       cellUnion(pRtree, pBboxRight, pNext);
124101     }else{
124102       nodeInsertCell(pRtree, pLeft, pNext);
124103       cellUnion(pRtree, pBboxLeft, pNext);
124104     }
124105   }
124106
124107   sqlite3_free(aiUsed);
124108   return SQLITE_OK;
124109 }
124110 #endif
124111
124112 static int updateMapping(
124113   Rtree *pRtree, 
124114   i64 iRowid, 
124115   RtreeNode *pNode, 
124116   int iHeight
124117 ){
124118   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
124119   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
124120   if( iHeight>0 ){
124121     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
124122     if( pChild ){
124123       nodeRelease(pRtree, pChild->pParent);
124124       nodeReference(pNode);
124125       pChild->pParent = pNode;
124126     }
124127   }
124128   return xSetMapping(pRtree, iRowid, pNode->iNode);
124129 }
124130
124131 static int SplitNode(
124132   Rtree *pRtree,
124133   RtreeNode *pNode,
124134   RtreeCell *pCell,
124135   int iHeight
124136 ){
124137   int i;
124138   int newCellIsRight = 0;
124139
124140   int rc = SQLITE_OK;
124141   int nCell = NCELL(pNode);
124142   RtreeCell *aCell;
124143   int *aiUsed;
124144
124145   RtreeNode *pLeft = 0;
124146   RtreeNode *pRight = 0;
124147
124148   RtreeCell leftbbox;
124149   RtreeCell rightbbox;
124150
124151   /* Allocate an array and populate it with a copy of pCell and 
124152   ** all cells from node pLeft. Then zero the original node.
124153   */
124154   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
124155   if( !aCell ){
124156     rc = SQLITE_NOMEM;
124157     goto splitnode_out;
124158   }
124159   aiUsed = (int *)&aCell[nCell+1];
124160   memset(aiUsed, 0, sizeof(int)*(nCell+1));
124161   for(i=0; i<nCell; i++){
124162     nodeGetCell(pRtree, pNode, i, &aCell[i]);
124163   }
124164   nodeZero(pRtree, pNode);
124165   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
124166   nCell++;
124167
124168   if( pNode->iNode==1 ){
124169     pRight = nodeNew(pRtree, pNode);
124170     pLeft = nodeNew(pRtree, pNode);
124171     pRtree->iDepth++;
124172     pNode->isDirty = 1;
124173     writeInt16(pNode->zData, pRtree->iDepth);
124174   }else{
124175     pLeft = pNode;
124176     pRight = nodeNew(pRtree, pLeft->pParent);
124177     nodeReference(pLeft);
124178   }
124179
124180   if( !pLeft || !pRight ){
124181     rc = SQLITE_NOMEM;
124182     goto splitnode_out;
124183   }
124184
124185   memset(pLeft->zData, 0, pRtree->iNodeSize);
124186   memset(pRight->zData, 0, pRtree->iNodeSize);
124187
124188   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
124189   if( rc!=SQLITE_OK ){
124190     goto splitnode_out;
124191   }
124192
124193   /* Ensure both child nodes have node numbers assigned to them by calling
124194   ** nodeWrite(). Node pRight always needs a node number, as it was created
124195   ** by nodeNew() above. But node pLeft sometimes already has a node number.
124196   ** In this case avoid the all to nodeWrite().
124197   */
124198   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
124199    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
124200   ){
124201     goto splitnode_out;
124202   }
124203
124204   rightbbox.iRowid = pRight->iNode;
124205   leftbbox.iRowid = pLeft->iNode;
124206
124207   if( pNode->iNode==1 ){
124208     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
124209     if( rc!=SQLITE_OK ){
124210       goto splitnode_out;
124211     }
124212   }else{
124213     RtreeNode *pParent = pLeft->pParent;
124214     int iCell;
124215     rc = nodeParentIndex(pRtree, pLeft, &iCell);
124216     if( rc==SQLITE_OK ){
124217       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
124218       rc = AdjustTree(pRtree, pParent, &leftbbox);
124219     }
124220     if( rc!=SQLITE_OK ){
124221       goto splitnode_out;
124222     }
124223   }
124224   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
124225     goto splitnode_out;
124226   }
124227
124228   for(i=0; i<NCELL(pRight); i++){
124229     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
124230     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
124231     if( iRowid==pCell->iRowid ){
124232       newCellIsRight = 1;
124233     }
124234     if( rc!=SQLITE_OK ){
124235       goto splitnode_out;
124236     }
124237   }
124238   if( pNode->iNode==1 ){
124239     for(i=0; i<NCELL(pLeft); i++){
124240       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
124241       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
124242       if( rc!=SQLITE_OK ){
124243         goto splitnode_out;
124244       }
124245     }
124246   }else if( newCellIsRight==0 ){
124247     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
124248   }
124249
124250   if( rc==SQLITE_OK ){
124251     rc = nodeRelease(pRtree, pRight);
124252     pRight = 0;
124253   }
124254   if( rc==SQLITE_OK ){
124255     rc = nodeRelease(pRtree, pLeft);
124256     pLeft = 0;
124257   }
124258
124259 splitnode_out:
124260   nodeRelease(pRtree, pRight);
124261   nodeRelease(pRtree, pLeft);
124262   sqlite3_free(aCell);
124263   return rc;
124264 }
124265
124266 /*
124267 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
124268 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
124269 ** the pLeaf->pParent chain all the way up to the root node.
124270 **
124271 ** This operation is required when a row is deleted (or updated - an update
124272 ** is implemented as a delete followed by an insert). SQLite provides the
124273 ** rowid of the row to delete, which can be used to find the leaf on which
124274 ** the entry resides (argument pLeaf). Once the leaf is located, this 
124275 ** function is called to determine its ancestry.
124276 */
124277 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
124278   int rc = SQLITE_OK;
124279   RtreeNode *pChild = pLeaf;
124280   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
124281     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
124282     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
124283     rc = sqlite3_step(pRtree->pReadParent);
124284     if( rc==SQLITE_ROW ){
124285       RtreeNode *pTest;           /* Used to test for reference loops */
124286       i64 iNode;                  /* Node number of parent node */
124287
124288       /* Before setting pChild->pParent, test that we are not creating a
124289       ** loop of references (as we would if, say, pChild==pParent). We don't
124290       ** want to do this as it leads to a memory leak when trying to delete
124291       ** the referenced counted node structures.
124292       */
124293       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
124294       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
124295       if( !pTest ){
124296         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
124297       }
124298     }
124299     rc = sqlite3_reset(pRtree->pReadParent);
124300     if( rc==SQLITE_OK ) rc = rc2;
124301     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
124302     pChild = pChild->pParent;
124303   }
124304   return rc;
124305 }
124306
124307 static int deleteCell(Rtree *, RtreeNode *, int, int);
124308
124309 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
124310   int rc;
124311   int rc2;
124312   RtreeNode *pParent;
124313   int iCell;
124314
124315   assert( pNode->nRef==1 );
124316
124317   /* Remove the entry in the parent cell. */
124318   rc = nodeParentIndex(pRtree, pNode, &iCell);
124319   if( rc==SQLITE_OK ){
124320     pParent = pNode->pParent;
124321     pNode->pParent = 0;
124322     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
124323   }
124324   rc2 = nodeRelease(pRtree, pParent);
124325   if( rc==SQLITE_OK ){
124326     rc = rc2;
124327   }
124328   if( rc!=SQLITE_OK ){
124329     return rc;
124330   }
124331
124332   /* Remove the xxx_node entry. */
124333   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
124334   sqlite3_step(pRtree->pDeleteNode);
124335   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
124336     return rc;
124337   }
124338
124339   /* Remove the xxx_parent entry. */
124340   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
124341   sqlite3_step(pRtree->pDeleteParent);
124342   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
124343     return rc;
124344   }
124345   
124346   /* Remove the node from the in-memory hash table and link it into
124347   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
124348   */
124349   nodeHashDelete(pRtree, pNode);
124350   pNode->iNode = iHeight;
124351   pNode->pNext = pRtree->pDeleted;
124352   pNode->nRef++;
124353   pRtree->pDeleted = pNode;
124354
124355   return SQLITE_OK;
124356 }
124357
124358 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
124359   RtreeNode *pParent = pNode->pParent;
124360   int rc = SQLITE_OK; 
124361   if( pParent ){
124362     int ii; 
124363     int nCell = NCELL(pNode);
124364     RtreeCell box;                            /* Bounding box for pNode */
124365     nodeGetCell(pRtree, pNode, 0, &box);
124366     for(ii=1; ii<nCell; ii++){
124367       RtreeCell cell;
124368       nodeGetCell(pRtree, pNode, ii, &cell);
124369       cellUnion(pRtree, &box, &cell);
124370     }
124371     box.iRowid = pNode->iNode;
124372     rc = nodeParentIndex(pRtree, pNode, &ii);
124373     if( rc==SQLITE_OK ){
124374       nodeOverwriteCell(pRtree, pParent, &box, ii);
124375       rc = fixBoundingBox(pRtree, pParent);
124376     }
124377   }
124378   return rc;
124379 }
124380
124381 /*
124382 ** Delete the cell at index iCell of node pNode. After removing the
124383 ** cell, adjust the r-tree data structure if required.
124384 */
124385 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
124386   RtreeNode *pParent;
124387   int rc;
124388
124389   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
124390     return rc;
124391   }
124392
124393   /* Remove the cell from the node. This call just moves bytes around
124394   ** the in-memory node image, so it cannot fail.
124395   */
124396   nodeDeleteCell(pRtree, pNode, iCell);
124397
124398   /* If the node is not the tree root and now has less than the minimum
124399   ** number of cells, remove it from the tree. Otherwise, update the
124400   ** cell in the parent node so that it tightly contains the updated
124401   ** node.
124402   */
124403   pParent = pNode->pParent;
124404   assert( pParent || pNode->iNode==1 );
124405   if( pParent ){
124406     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
124407       rc = removeNode(pRtree, pNode, iHeight);
124408     }else{
124409       rc = fixBoundingBox(pRtree, pNode);
124410     }
124411   }
124412
124413   return rc;
124414 }
124415
124416 static int Reinsert(
124417   Rtree *pRtree, 
124418   RtreeNode *pNode, 
124419   RtreeCell *pCell, 
124420   int iHeight
124421 ){
124422   int *aOrder;
124423   int *aSpare;
124424   RtreeCell *aCell;
124425   float *aDistance;
124426   int nCell;
124427   float aCenterCoord[RTREE_MAX_DIMENSIONS];
124428   int iDim;
124429   int ii;
124430   int rc = SQLITE_OK;
124431
124432   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
124433
124434   nCell = NCELL(pNode)+1;
124435
124436   /* Allocate the buffers used by this operation. The allocation is
124437   ** relinquished before this function returns.
124438   */
124439   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
124440     sizeof(RtreeCell) +         /* aCell array */
124441     sizeof(int)       +         /* aOrder array */
124442     sizeof(int)       +         /* aSpare array */
124443     sizeof(float)               /* aDistance array */
124444   ));
124445   if( !aCell ){
124446     return SQLITE_NOMEM;
124447   }
124448   aOrder    = (int *)&aCell[nCell];
124449   aSpare    = (int *)&aOrder[nCell];
124450   aDistance = (float *)&aSpare[nCell];
124451
124452   for(ii=0; ii<nCell; ii++){
124453     if( ii==(nCell-1) ){
124454       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
124455     }else{
124456       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
124457     }
124458     aOrder[ii] = ii;
124459     for(iDim=0; iDim<pRtree->nDim; iDim++){
124460       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
124461       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
124462     }
124463   }
124464   for(iDim=0; iDim<pRtree->nDim; iDim++){
124465     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
124466   }
124467
124468   for(ii=0; ii<nCell; ii++){
124469     aDistance[ii] = 0.0;
124470     for(iDim=0; iDim<pRtree->nDim; iDim++){
124471       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
124472           DCOORD(aCell[ii].aCoord[iDim*2]);
124473       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
124474     }
124475   }
124476
124477   SortByDistance(aOrder, nCell, aDistance, aSpare);
124478   nodeZero(pRtree, pNode);
124479
124480   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
124481     RtreeCell *p = &aCell[aOrder[ii]];
124482     nodeInsertCell(pRtree, pNode, p);
124483     if( p->iRowid==pCell->iRowid ){
124484       if( iHeight==0 ){
124485         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
124486       }else{
124487         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
124488       }
124489     }
124490   }
124491   if( rc==SQLITE_OK ){
124492     rc = fixBoundingBox(pRtree, pNode);
124493   }
124494   for(; rc==SQLITE_OK && ii<nCell; ii++){
124495     /* Find a node to store this cell in. pNode->iNode currently contains
124496     ** the height of the sub-tree headed by the cell.
124497     */
124498     RtreeNode *pInsert;
124499     RtreeCell *p = &aCell[aOrder[ii]];
124500     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
124501     if( rc==SQLITE_OK ){
124502       int rc2;
124503       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
124504       rc2 = nodeRelease(pRtree, pInsert);
124505       if( rc==SQLITE_OK ){
124506         rc = rc2;
124507       }
124508     }
124509   }
124510
124511   sqlite3_free(aCell);
124512   return rc;
124513 }
124514
124515 /*
124516 ** Insert cell pCell into node pNode. Node pNode is the head of a 
124517 ** subtree iHeight high (leaf nodes have iHeight==0).
124518 */
124519 static int rtreeInsertCell(
124520   Rtree *pRtree,
124521   RtreeNode *pNode,
124522   RtreeCell *pCell,
124523   int iHeight
124524 ){
124525   int rc = SQLITE_OK;
124526   if( iHeight>0 ){
124527     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
124528     if( pChild ){
124529       nodeRelease(pRtree, pChild->pParent);
124530       nodeReference(pNode);
124531       pChild->pParent = pNode;
124532     }
124533   }
124534   if( nodeInsertCell(pRtree, pNode, pCell) ){
124535 #if VARIANT_RSTARTREE_REINSERT
124536     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
124537       rc = SplitNode(pRtree, pNode, pCell, iHeight);
124538     }else{
124539       pRtree->iReinsertHeight = iHeight;
124540       rc = Reinsert(pRtree, pNode, pCell, iHeight);
124541     }
124542 #else
124543     rc = SplitNode(pRtree, pNode, pCell, iHeight);
124544 #endif
124545   }else{
124546     rc = AdjustTree(pRtree, pNode, pCell);
124547     if( rc==SQLITE_OK ){
124548       if( iHeight==0 ){
124549         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
124550       }else{
124551         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
124552       }
124553     }
124554   }
124555   return rc;
124556 }
124557
124558 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
124559   int ii;
124560   int rc = SQLITE_OK;
124561   int nCell = NCELL(pNode);
124562
124563   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
124564     RtreeNode *pInsert;
124565     RtreeCell cell;
124566     nodeGetCell(pRtree, pNode, ii, &cell);
124567
124568     /* Find a node to store this cell in. pNode->iNode currently contains
124569     ** the height of the sub-tree headed by the cell.
124570     */
124571     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
124572     if( rc==SQLITE_OK ){
124573       int rc2;
124574       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
124575       rc2 = nodeRelease(pRtree, pInsert);
124576       if( rc==SQLITE_OK ){
124577         rc = rc2;
124578       }
124579     }
124580   }
124581   return rc;
124582 }
124583
124584 /*
124585 ** Select a currently unused rowid for a new r-tree record.
124586 */
124587 static int newRowid(Rtree *pRtree, i64 *piRowid){
124588   int rc;
124589   sqlite3_bind_null(pRtree->pWriteRowid, 1);
124590   sqlite3_bind_null(pRtree->pWriteRowid, 2);
124591   sqlite3_step(pRtree->pWriteRowid);
124592   rc = sqlite3_reset(pRtree->pWriteRowid);
124593   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
124594   return rc;
124595 }
124596
124597 /*
124598 ** The xUpdate method for rtree module virtual tables.
124599 */
124600 static int rtreeUpdate(
124601   sqlite3_vtab *pVtab, 
124602   int nData, 
124603   sqlite3_value **azData, 
124604   sqlite_int64 *pRowid
124605 ){
124606   Rtree *pRtree = (Rtree *)pVtab;
124607   int rc = SQLITE_OK;
124608
124609   rtreeReference(pRtree);
124610
124611   assert(nData>=1);
124612
124613   /* If azData[0] is not an SQL NULL value, it is the rowid of a
124614   ** record to delete from the r-tree table. The following block does
124615   ** just that.
124616   */
124617   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
124618     i64 iDelete;                /* The rowid to delete */
124619     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
124620     int iCell;                  /* Index of iDelete cell in pLeaf */
124621     RtreeNode *pRoot;
124622
124623     /* Obtain a reference to the root node to initialise Rtree.iDepth */
124624     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
124625
124626     /* Obtain a reference to the leaf node that contains the entry 
124627     ** about to be deleted. 
124628     */
124629     if( rc==SQLITE_OK ){
124630       iDelete = sqlite3_value_int64(azData[0]);
124631       rc = findLeafNode(pRtree, iDelete, &pLeaf);
124632     }
124633
124634     /* Delete the cell in question from the leaf node. */
124635     if( rc==SQLITE_OK ){
124636       int rc2;
124637       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
124638       if( rc==SQLITE_OK ){
124639         rc = deleteCell(pRtree, pLeaf, iCell, 0);
124640       }
124641       rc2 = nodeRelease(pRtree, pLeaf);
124642       if( rc==SQLITE_OK ){
124643         rc = rc2;
124644       }
124645     }
124646
124647     /* Delete the corresponding entry in the <rtree>_rowid table. */
124648     if( rc==SQLITE_OK ){
124649       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
124650       sqlite3_step(pRtree->pDeleteRowid);
124651       rc = sqlite3_reset(pRtree->pDeleteRowid);
124652     }
124653
124654     /* Check if the root node now has exactly one child. If so, remove
124655     ** it, schedule the contents of the child for reinsertion and 
124656     ** reduce the tree height by one.
124657     **
124658     ** This is equivalent to copying the contents of the child into
124659     ** the root node (the operation that Gutman's paper says to perform 
124660     ** in this scenario).
124661     */
124662     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
124663       int rc2;
124664       RtreeNode *pChild;
124665       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
124666       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
124667       if( rc==SQLITE_OK ){
124668         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
124669       }
124670       rc2 = nodeRelease(pRtree, pChild);
124671       if( rc==SQLITE_OK ) rc = rc2;
124672       if( rc==SQLITE_OK ){
124673         pRtree->iDepth--;
124674         writeInt16(pRoot->zData, pRtree->iDepth);
124675         pRoot->isDirty = 1;
124676       }
124677     }
124678
124679     /* Re-insert the contents of any underfull nodes removed from the tree. */
124680     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
124681       if( rc==SQLITE_OK ){
124682         rc = reinsertNodeContent(pRtree, pLeaf);
124683       }
124684       pRtree->pDeleted = pLeaf->pNext;
124685       sqlite3_free(pLeaf);
124686     }
124687
124688     /* Release the reference to the root node. */
124689     if( rc==SQLITE_OK ){
124690       rc = nodeRelease(pRtree, pRoot);
124691     }else{
124692       nodeRelease(pRtree, pRoot);
124693     }
124694   }
124695
124696   /* If the azData[] array contains more than one element, elements
124697   ** (azData[2]..azData[argc-1]) contain a new record to insert into
124698   ** the r-tree structure.
124699   */
124700   if( rc==SQLITE_OK && nData>1 ){
124701     /* Insert a new record into the r-tree */
124702     RtreeCell cell;
124703     int ii;
124704     RtreeNode *pLeaf;
124705
124706     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
124707     assert( nData==(pRtree->nDim*2 + 3) );
124708     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
124709       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
124710         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
124711         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
124712         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
124713           rc = SQLITE_CONSTRAINT;
124714           goto constraint;
124715         }
124716       }
124717     }else{
124718       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
124719         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
124720         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
124721         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
124722           rc = SQLITE_CONSTRAINT;
124723           goto constraint;
124724         }
124725       }
124726     }
124727
124728     /* Figure out the rowid of the new row. */
124729     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
124730       rc = newRowid(pRtree, &cell.iRowid);
124731     }else{
124732       cell.iRowid = sqlite3_value_int64(azData[2]);
124733       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
124734       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
124735         sqlite3_reset(pRtree->pReadRowid);
124736         rc = SQLITE_CONSTRAINT;
124737         goto constraint;
124738       }
124739       rc = sqlite3_reset(pRtree->pReadRowid);
124740     }
124741     *pRowid = cell.iRowid;
124742
124743     if( rc==SQLITE_OK ){
124744       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
124745     }
124746     if( rc==SQLITE_OK ){
124747       int rc2;
124748       pRtree->iReinsertHeight = -1;
124749       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
124750       rc2 = nodeRelease(pRtree, pLeaf);
124751       if( rc==SQLITE_OK ){
124752         rc = rc2;
124753       }
124754     }
124755   }
124756
124757 constraint:
124758   rtreeRelease(pRtree);
124759   return rc;
124760 }
124761
124762 /*
124763 ** The xRename method for rtree module virtual tables.
124764 */
124765 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
124766   Rtree *pRtree = (Rtree *)pVtab;
124767   int rc = SQLITE_NOMEM;
124768   char *zSql = sqlite3_mprintf(
124769     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
124770     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
124771     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
124772     , pRtree->zDb, pRtree->zName, zNewName 
124773     , pRtree->zDb, pRtree->zName, zNewName 
124774     , pRtree->zDb, pRtree->zName, zNewName
124775   );
124776   if( zSql ){
124777     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
124778     sqlite3_free(zSql);
124779   }
124780   return rc;
124781 }
124782
124783 static sqlite3_module rtreeModule = {
124784   0,                         /* iVersion */
124785   rtreeCreate,                /* xCreate - create a table */
124786   rtreeConnect,               /* xConnect - connect to an existing table */
124787   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
124788   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
124789   rtreeDestroy,               /* xDestroy - Drop a table */
124790   rtreeOpen,                  /* xOpen - open a cursor */
124791   rtreeClose,                 /* xClose - close a cursor */
124792   rtreeFilter,                /* xFilter - configure scan constraints */
124793   rtreeNext,                  /* xNext - advance a cursor */
124794   rtreeEof,                   /* xEof */
124795   rtreeColumn,                /* xColumn - read data */
124796   rtreeRowid,                 /* xRowid - read data */
124797   rtreeUpdate,                /* xUpdate - write data */
124798   0,                          /* xBegin - begin transaction */
124799   0,                          /* xSync - sync transaction */
124800   0,                          /* xCommit - commit transaction */
124801   0,                          /* xRollback - rollback transaction */
124802   0,                          /* xFindFunction - function overloading */
124803   rtreeRename                 /* xRename - rename the table */
124804 };
124805
124806 static int rtreeSqlInit(
124807   Rtree *pRtree, 
124808   sqlite3 *db, 
124809   const char *zDb, 
124810   const char *zPrefix, 
124811   int isCreate
124812 ){
124813   int rc = SQLITE_OK;
124814
124815   #define N_STATEMENT 9
124816   static const char *azSql[N_STATEMENT] = {
124817     /* Read and write the xxx_node table */
124818     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
124819     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
124820     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
124821
124822     /* Read and write the xxx_rowid table */
124823     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
124824     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
124825     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
124826
124827     /* Read and write the xxx_parent table */
124828     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
124829     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
124830     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
124831   };
124832   sqlite3_stmt **appStmt[N_STATEMENT];
124833   int i;
124834
124835   pRtree->db = db;
124836
124837   if( isCreate ){
124838     char *zCreate = sqlite3_mprintf(
124839 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
124840 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
124841 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
124842 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
124843       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
124844     );
124845     if( !zCreate ){
124846       return SQLITE_NOMEM;
124847     }
124848     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
124849     sqlite3_free(zCreate);
124850     if( rc!=SQLITE_OK ){
124851       return rc;
124852     }
124853   }
124854
124855   appStmt[0] = &pRtree->pReadNode;
124856   appStmt[1] = &pRtree->pWriteNode;
124857   appStmt[2] = &pRtree->pDeleteNode;
124858   appStmt[3] = &pRtree->pReadRowid;
124859   appStmt[4] = &pRtree->pWriteRowid;
124860   appStmt[5] = &pRtree->pDeleteRowid;
124861   appStmt[6] = &pRtree->pReadParent;
124862   appStmt[7] = &pRtree->pWriteParent;
124863   appStmt[8] = &pRtree->pDeleteParent;
124864
124865   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
124866     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
124867     if( zSql ){
124868       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
124869     }else{
124870       rc = SQLITE_NOMEM;
124871     }
124872     sqlite3_free(zSql);
124873   }
124874
124875   return rc;
124876 }
124877
124878 /*
124879 ** The second argument to this function contains the text of an SQL statement
124880 ** that returns a single integer value. The statement is compiled and executed
124881 ** using database connection db. If successful, the integer value returned
124882 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
124883 ** code is returned and the value of *piVal after returning is not defined.
124884 */
124885 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
124886   int rc = SQLITE_NOMEM;
124887   if( zSql ){
124888     sqlite3_stmt *pStmt = 0;
124889     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124890     if( rc==SQLITE_OK ){
124891       if( SQLITE_ROW==sqlite3_step(pStmt) ){
124892         *piVal = sqlite3_column_int(pStmt, 0);
124893       }
124894       rc = sqlite3_finalize(pStmt);
124895     }
124896   }
124897   return rc;
124898 }
124899
124900 /*
124901 ** This function is called from within the xConnect() or xCreate() method to
124902 ** determine the node-size used by the rtree table being created or connected
124903 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
124904 ** Otherwise, an SQLite error code is returned.
124905 **
124906 ** If this function is being called as part of an xConnect(), then the rtree
124907 ** table already exists. In this case the node-size is determined by inspecting
124908 ** the root node of the tree.
124909 **
124910 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
124911 ** This ensures that each node is stored on a single database page. If the 
124912 ** database page-size is so large that more than RTREE_MAXCELLS entries 
124913 ** would fit in a single node, use a smaller node-size.
124914 */
124915 static int getNodeSize(
124916   sqlite3 *db,                    /* Database handle */
124917   Rtree *pRtree,                  /* Rtree handle */
124918   int isCreate                    /* True for xCreate, false for xConnect */
124919 ){
124920   int rc;
124921   char *zSql;
124922   if( isCreate ){
124923     int iPageSize;
124924     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
124925     rc = getIntFromStmt(db, zSql, &iPageSize);
124926     if( rc==SQLITE_OK ){
124927       pRtree->iNodeSize = iPageSize-64;
124928       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
124929         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
124930       }
124931     }
124932   }else{
124933     zSql = sqlite3_mprintf(
124934         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
124935         pRtree->zDb, pRtree->zName
124936     );
124937     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
124938   }
124939
124940   sqlite3_free(zSql);
124941   return rc;
124942 }
124943
124944 /* 
124945 ** This function is the implementation of both the xConnect and xCreate
124946 ** methods of the r-tree virtual table.
124947 **
124948 **   argv[0]   -> module name
124949 **   argv[1]   -> database name
124950 **   argv[2]   -> table name
124951 **   argv[...] -> column names...
124952 */
124953 static int rtreeInit(
124954   sqlite3 *db,                        /* Database connection */
124955   void *pAux,                         /* One of the RTREE_COORD_* constants */
124956   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
124957   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
124958   char **pzErr,                       /* OUT: Error message, if any */
124959   int isCreate                        /* True for xCreate, false for xConnect */
124960 ){
124961   int rc = SQLITE_OK;
124962   Rtree *pRtree;
124963   int nDb;              /* Length of string argv[1] */
124964   int nName;            /* Length of string argv[2] */
124965   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
124966
124967   const char *aErrMsg[] = {
124968     0,                                                    /* 0 */
124969     "Wrong number of columns for an rtree table",         /* 1 */
124970     "Too few columns for an rtree table",                 /* 2 */
124971     "Too many columns for an rtree table"                 /* 3 */
124972   };
124973
124974   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
124975   if( aErrMsg[iErr] ){
124976     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
124977     return SQLITE_ERROR;
124978   }
124979
124980   /* Allocate the sqlite3_vtab structure */
124981   nDb = strlen(argv[1]);
124982   nName = strlen(argv[2]);
124983   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
124984   if( !pRtree ){
124985     return SQLITE_NOMEM;
124986   }
124987   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
124988   pRtree->nBusy = 1;
124989   pRtree->base.pModule = &rtreeModule;
124990   pRtree->zDb = (char *)&pRtree[1];
124991   pRtree->zName = &pRtree->zDb[nDb+1];
124992   pRtree->nDim = (argc-4)/2;
124993   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
124994   pRtree->eCoordType = eCoordType;
124995   memcpy(pRtree->zDb, argv[1], nDb);
124996   memcpy(pRtree->zName, argv[2], nName);
124997
124998   /* Figure out the node size to use. */
124999   rc = getNodeSize(db, pRtree, isCreate);
125000
125001   /* Create/Connect to the underlying relational database schema. If
125002   ** that is successful, call sqlite3_declare_vtab() to configure
125003   ** the r-tree table schema.
125004   */
125005   if( rc==SQLITE_OK ){
125006     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
125007       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
125008     }else{
125009       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
125010       char *zTmp;
125011       int ii;
125012       for(ii=4; zSql && ii<argc; ii++){
125013         zTmp = zSql;
125014         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
125015         sqlite3_free(zTmp);
125016       }
125017       if( zSql ){
125018         zTmp = zSql;
125019         zSql = sqlite3_mprintf("%s);", zTmp);
125020         sqlite3_free(zTmp);
125021       }
125022       if( !zSql ){
125023         rc = SQLITE_NOMEM;
125024       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
125025         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
125026       }
125027       sqlite3_free(zSql);
125028     }
125029   }
125030
125031   if( rc==SQLITE_OK ){
125032     *ppVtab = (sqlite3_vtab *)pRtree;
125033   }else{
125034     rtreeRelease(pRtree);
125035   }
125036   return rc;
125037 }
125038
125039
125040 /*
125041 ** Implementation of a scalar function that decodes r-tree nodes to
125042 ** human readable strings. This can be used for debugging and analysis.
125043 **
125044 ** The scalar function takes two arguments, a blob of data containing
125045 ** an r-tree node, and the number of dimensions the r-tree indexes.
125046 ** For a two-dimensional r-tree structure called "rt", to deserialize
125047 ** all nodes, a statement like:
125048 **
125049 **   SELECT rtreenode(2, data) FROM rt_node;
125050 **
125051 ** The human readable string takes the form of a Tcl list with one
125052 ** entry for each cell in the r-tree node. Each entry is itself a
125053 ** list, containing the 8-byte rowid/pageno followed by the 
125054 ** <num-dimension>*2 coordinates.
125055 */
125056 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125057   char *zText = 0;
125058   RtreeNode node;
125059   Rtree tree;
125060   int ii;
125061
125062   UNUSED_PARAMETER(nArg);
125063   memset(&node, 0, sizeof(RtreeNode));
125064   memset(&tree, 0, sizeof(Rtree));
125065   tree.nDim = sqlite3_value_int(apArg[0]);
125066   tree.nBytesPerCell = 8 + 8 * tree.nDim;
125067   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
125068
125069   for(ii=0; ii<NCELL(&node); ii++){
125070     char zCell[512];
125071     int nCell = 0;
125072     RtreeCell cell;
125073     int jj;
125074
125075     nodeGetCell(&tree, &node, ii, &cell);
125076     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
125077     nCell = strlen(zCell);
125078     for(jj=0; jj<tree.nDim*2; jj++){
125079       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
125080       nCell = strlen(zCell);
125081     }
125082
125083     if( zText ){
125084       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
125085       sqlite3_free(zText);
125086       zText = zTextNew;
125087     }else{
125088       zText = sqlite3_mprintf("{%s}", zCell);
125089     }
125090   }
125091   
125092   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
125093 }
125094
125095 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
125096   UNUSED_PARAMETER(nArg);
125097   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
125098    || sqlite3_value_bytes(apArg[0])<2
125099   ){
125100     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
125101   }else{
125102     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
125103     sqlite3_result_int(ctx, readInt16(zBlob));
125104   }
125105 }
125106
125107 /*
125108 ** Register the r-tree module with database handle db. This creates the
125109 ** virtual table module "rtree" and the debugging/analysis scalar 
125110 ** function "rtreenode".
125111 */
125112 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
125113   const int utf8 = SQLITE_UTF8;
125114   int rc;
125115
125116   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
125117   if( rc==SQLITE_OK ){
125118     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
125119   }
125120   if( rc==SQLITE_OK ){
125121     void *c = (void *)RTREE_COORD_REAL32;
125122     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
125123   }
125124   if( rc==SQLITE_OK ){
125125     void *c = (void *)RTREE_COORD_INT32;
125126     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
125127   }
125128
125129   return rc;
125130 }
125131
125132 /*
125133 ** A version of sqlite3_free() that can be used as a callback. This is used
125134 ** in two places - as the destructor for the blob value returned by the
125135 ** invocation of a geometry function, and as the destructor for the geometry
125136 ** functions themselves.
125137 */
125138 static void doSqlite3Free(void *p){
125139   sqlite3_free(p);
125140 }
125141
125142 /*
125143 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
125144 ** scalar user function. This C function is the callback used for all such
125145 ** registered SQL functions.
125146 **
125147 ** The scalar user functions return a blob that is interpreted by r-tree
125148 ** table MATCH operators.
125149 */
125150 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
125151   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
125152   RtreeMatchArg *pBlob;
125153   int nBlob;
125154
125155   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
125156   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
125157   if( !pBlob ){
125158     sqlite3_result_error_nomem(ctx);
125159   }else{
125160     int i;
125161     pBlob->magic = RTREE_GEOMETRY_MAGIC;
125162     pBlob->xGeom = pGeomCtx->xGeom;
125163     pBlob->pContext = pGeomCtx->pContext;
125164     pBlob->nParam = nArg;
125165     for(i=0; i<nArg; i++){
125166       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
125167     }
125168     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
125169   }
125170 }
125171
125172 /*
125173 ** Register a new geometry function for use with the r-tree MATCH operator.
125174 */
125175 SQLITE_API int sqlite3_rtree_geometry_callback(
125176   sqlite3 *db,
125177   const char *zGeom,
125178   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
125179   void *pContext
125180 ){
125181   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
125182
125183   /* Allocate and populate the context object. */
125184   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
125185   if( !pGeomCtx ) return SQLITE_NOMEM;
125186   pGeomCtx->xGeom = xGeom;
125187   pGeomCtx->pContext = pContext;
125188
125189   /* Create the new user-function. Register a destructor function to delete
125190   ** the context object when it is no longer required.  */
125191   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
125192       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
125193   );
125194 }
125195
125196 #if !SQLITE_CORE
125197 SQLITE_API int sqlite3_extension_init(
125198   sqlite3 *db,
125199   char **pzErrMsg,
125200   const sqlite3_api_routines *pApi
125201 ){
125202   SQLITE_EXTENSION_INIT2(pApi)
125203   return sqlite3RtreeInit(db);
125204 }
125205 #endif
125206
125207 #endif
125208
125209 /************** End of rtree.c ***********************************************/
125210 /************** Begin file icu.c *********************************************/
125211 /*
125212 ** 2007 May 6
125213 **
125214 ** The author disclaims copyright to this source code.  In place of
125215 ** a legal notice, here is a blessing:
125216 **
125217 **    May you do good and not evil.
125218 **    May you find forgiveness for yourself and forgive others.
125219 **    May you share freely, never taking more than you give.
125220 **
125221 *************************************************************************
125222 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
125223 **
125224 ** This file implements an integration between the ICU library 
125225 ** ("International Components for Unicode", an open-source library 
125226 ** for handling unicode data) and SQLite. The integration uses 
125227 ** ICU to provide the following to SQLite:
125228 **
125229 **   * An implementation of the SQL regexp() function (and hence REGEXP
125230 **     operator) using the ICU uregex_XX() APIs.
125231 **
125232 **   * Implementations of the SQL scalar upper() and lower() functions
125233 **     for case mapping.
125234 **
125235 **   * Integration of ICU and SQLite collation seqences.
125236 **
125237 **   * An implementation of the LIKE operator that uses ICU to 
125238 **     provide case-independent matching.
125239 */
125240
125241 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
125242
125243 /* Include ICU headers */
125244 #include <unicode/utypes.h>
125245 #include <unicode/uregex.h>
125246 #include <unicode/ustring.h>
125247 #include <unicode/ucol.h>
125248
125249
125250 #ifndef SQLITE_CORE
125251   SQLITE_EXTENSION_INIT1
125252 #else
125253 #endif
125254
125255 /*
125256 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
125257 ** operator.
125258 */
125259 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
125260 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
125261 #endif
125262
125263 /*
125264 ** Version of sqlite3_free() that is always a function, never a macro.
125265 */
125266 static void xFree(void *p){
125267   sqlite3_free(p);
125268 }
125269
125270 /*
125271 ** Compare two UTF-8 strings for equality where the first string is
125272 ** a "LIKE" expression. Return true (1) if they are the same and 
125273 ** false (0) if they are different.
125274 */
125275 static int icuLikeCompare(
125276   const uint8_t *zPattern,   /* LIKE pattern */
125277   const uint8_t *zString,    /* The UTF-8 string to compare against */
125278   const UChar32 uEsc         /* The escape character */
125279 ){
125280   static const int MATCH_ONE = (UChar32)'_';
125281   static const int MATCH_ALL = (UChar32)'%';
125282
125283   int iPattern = 0;       /* Current byte index in zPattern */
125284   int iString = 0;        /* Current byte index in zString */
125285
125286   int prevEscape = 0;     /* True if the previous character was uEsc */
125287
125288   while( zPattern[iPattern]!=0 ){
125289
125290     /* Read (and consume) the next character from the input pattern. */
125291     UChar32 uPattern;
125292     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
125293     assert(uPattern!=0);
125294
125295     /* There are now 4 possibilities:
125296     **
125297     **     1. uPattern is an unescaped match-all character "%",
125298     **     2. uPattern is an unescaped match-one character "_",
125299     **     3. uPattern is an unescaped escape character, or
125300     **     4. uPattern is to be handled as an ordinary character
125301     */
125302     if( !prevEscape && uPattern==MATCH_ALL ){
125303       /* Case 1. */
125304       uint8_t c;
125305
125306       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
125307       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
125308       ** test string.
125309       */
125310       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
125311         if( c==MATCH_ONE ){
125312           if( zString[iString]==0 ) return 0;
125313           U8_FWD_1_UNSAFE(zString, iString);
125314         }
125315         iPattern++;
125316       }
125317
125318       if( zPattern[iPattern]==0 ) return 1;
125319
125320       while( zString[iString] ){
125321         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
125322           return 1;
125323         }
125324         U8_FWD_1_UNSAFE(zString, iString);
125325       }
125326       return 0;
125327
125328     }else if( !prevEscape && uPattern==MATCH_ONE ){
125329       /* Case 2. */
125330       if( zString[iString]==0 ) return 0;
125331       U8_FWD_1_UNSAFE(zString, iString);
125332
125333     }else if( !prevEscape && uPattern==uEsc){
125334       /* Case 3. */
125335       prevEscape = 1;
125336
125337     }else{
125338       /* Case 4. */
125339       UChar32 uString;
125340       U8_NEXT_UNSAFE(zString, iString, uString);
125341       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
125342       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
125343       if( uString!=uPattern ){
125344         return 0;
125345       }
125346       prevEscape = 0;
125347     }
125348   }
125349
125350   return zString[iString]==0;
125351 }
125352
125353 /*
125354 ** Implementation of the like() SQL function.  This function implements
125355 ** the build-in LIKE operator.  The first argument to the function is the
125356 ** pattern and the second argument is the string.  So, the SQL statements:
125357 **
125358 **       A LIKE B
125359 **
125360 ** is implemented as like(B, A). If there is an escape character E, 
125361 **
125362 **       A LIKE B ESCAPE E
125363 **
125364 ** is mapped to like(B, A, E).
125365 */
125366 static void icuLikeFunc(
125367   sqlite3_context *context, 
125368   int argc, 
125369   sqlite3_value **argv
125370 ){
125371   const unsigned char *zA = sqlite3_value_text(argv[0]);
125372   const unsigned char *zB = sqlite3_value_text(argv[1]);
125373   UChar32 uEsc = 0;
125374
125375   /* Limit the length of the LIKE or GLOB pattern to avoid problems
125376   ** of deep recursion and N*N behavior in patternCompare().
125377   */
125378   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
125379     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
125380     return;
125381   }
125382
125383
125384   if( argc==3 ){
125385     /* The escape character string must consist of a single UTF-8 character.
125386     ** Otherwise, return an error.
125387     */
125388     int nE= sqlite3_value_bytes(argv[2]);
125389     const unsigned char *zE = sqlite3_value_text(argv[2]);
125390     int i = 0;
125391     if( zE==0 ) return;
125392     U8_NEXT(zE, i, nE, uEsc);
125393     if( i!=nE){
125394       sqlite3_result_error(context, 
125395           "ESCAPE expression must be a single character", -1);
125396       return;
125397     }
125398   }
125399
125400   if( zA && zB ){
125401     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
125402   }
125403 }
125404
125405 /*
125406 ** This function is called when an ICU function called from within
125407 ** the implementation of an SQL scalar function returns an error.
125408 **
125409 ** The scalar function context passed as the first argument is 
125410 ** loaded with an error message based on the following two args.
125411 */
125412 static void icuFunctionError(
125413   sqlite3_context *pCtx,       /* SQLite scalar function context */
125414   const char *zName,           /* Name of ICU function that failed */
125415   UErrorCode e                 /* Error code returned by ICU function */
125416 ){
125417   char zBuf[128];
125418   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
125419   zBuf[127] = '\0';
125420   sqlite3_result_error(pCtx, zBuf, -1);
125421 }
125422
125423 /*
125424 ** Function to delete compiled regexp objects. Registered as
125425 ** a destructor function with sqlite3_set_auxdata().
125426 */
125427 static void icuRegexpDelete(void *p){
125428   URegularExpression *pExpr = (URegularExpression *)p;
125429   uregex_close(pExpr);
125430 }
125431
125432 /*
125433 ** Implementation of SQLite REGEXP operator. This scalar function takes
125434 ** two arguments. The first is a regular expression pattern to compile
125435 ** the second is a string to match against that pattern. If either 
125436 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
125437 ** is 1 if the string matches the pattern, or 0 otherwise.
125438 **
125439 ** SQLite maps the regexp() function to the regexp() operator such
125440 ** that the following two are equivalent:
125441 **
125442 **     zString REGEXP zPattern
125443 **     regexp(zPattern, zString)
125444 **
125445 ** Uses the following ICU regexp APIs:
125446 **
125447 **     uregex_open()
125448 **     uregex_matches()
125449 **     uregex_close()
125450 */
125451 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125452   UErrorCode status = U_ZERO_ERROR;
125453   URegularExpression *pExpr;
125454   UBool res;
125455   const UChar *zString = sqlite3_value_text16(apArg[1]);
125456
125457   (void)nArg;  /* Unused parameter */
125458
125459   /* If the left hand side of the regexp operator is NULL, 
125460   ** then the result is also NULL. 
125461   */
125462   if( !zString ){
125463     return;
125464   }
125465
125466   pExpr = sqlite3_get_auxdata(p, 0);
125467   if( !pExpr ){
125468     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
125469     if( !zPattern ){
125470       return;
125471     }
125472     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
125473
125474     if( U_SUCCESS(status) ){
125475       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
125476     }else{
125477       assert(!pExpr);
125478       icuFunctionError(p, "uregex_open", status);
125479       return;
125480     }
125481   }
125482
125483   /* Configure the text that the regular expression operates on. */
125484   uregex_setText(pExpr, zString, -1, &status);
125485   if( !U_SUCCESS(status) ){
125486     icuFunctionError(p, "uregex_setText", status);
125487     return;
125488   }
125489
125490   /* Attempt the match */
125491   res = uregex_matches(pExpr, 0, &status);
125492   if( !U_SUCCESS(status) ){
125493     icuFunctionError(p, "uregex_matches", status);
125494     return;
125495   }
125496
125497   /* Set the text that the regular expression operates on to a NULL
125498   ** pointer. This is not really necessary, but it is tidier than 
125499   ** leaving the regular expression object configured with an invalid
125500   ** pointer after this function returns.
125501   */
125502   uregex_setText(pExpr, 0, 0, &status);
125503
125504   /* Return 1 or 0. */
125505   sqlite3_result_int(p, res ? 1 : 0);
125506 }
125507
125508 /*
125509 ** Implementations of scalar functions for case mapping - upper() and 
125510 ** lower(). Function upper() converts its input to upper-case (ABC).
125511 ** Function lower() converts to lower-case (abc).
125512 **
125513 ** ICU provides two types of case mapping, "general" case mapping and
125514 ** "language specific". Refer to ICU documentation for the differences
125515 ** between the two.
125516 **
125517 ** To utilise "general" case mapping, the upper() or lower() scalar 
125518 ** functions are invoked with one argument:
125519 **
125520 **     upper('ABC') -> 'abc'
125521 **     lower('abc') -> 'ABC'
125522 **
125523 ** To access ICU "language specific" case mapping, upper() or lower()
125524 ** should be invoked with two arguments. The second argument is the name
125525 ** of the locale to use. Passing an empty string ("") or SQL NULL value
125526 ** as the second argument is the same as invoking the 1 argument version
125527 ** of upper() or lower().
125528 **
125529 **     lower('I', 'en_us') -> 'i'
125530 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
125531 **
125532 ** http://www.icu-project.org/userguide/posix.html#case_mappings
125533 */
125534 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
125535   const UChar *zInput;
125536   UChar *zOutput;
125537   int nInput;
125538   int nOutput;
125539
125540   UErrorCode status = U_ZERO_ERROR;
125541   const char *zLocale = 0;
125542
125543   assert(nArg==1 || nArg==2);
125544   if( nArg==2 ){
125545     zLocale = (const char *)sqlite3_value_text(apArg[1]);
125546   }
125547
125548   zInput = sqlite3_value_text16(apArg[0]);
125549   if( !zInput ){
125550     return;
125551   }
125552   nInput = sqlite3_value_bytes16(apArg[0]);
125553
125554   nOutput = nInput * 2 + 2;
125555   zOutput = sqlite3_malloc(nOutput);
125556   if( !zOutput ){
125557     return;
125558   }
125559
125560   if( sqlite3_user_data(p) ){
125561     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125562   }else{
125563     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
125564   }
125565
125566   if( !U_SUCCESS(status) ){
125567     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
125568     return;
125569   }
125570
125571   sqlite3_result_text16(p, zOutput, -1, xFree);
125572 }
125573
125574 /*
125575 ** Collation sequence destructor function. The pCtx argument points to
125576 ** a UCollator structure previously allocated using ucol_open().
125577 */
125578 static void icuCollationDel(void *pCtx){
125579   UCollator *p = (UCollator *)pCtx;
125580   ucol_close(p);
125581 }
125582
125583 /*
125584 ** Collation sequence comparison function. The pCtx argument points to
125585 ** a UCollator structure previously allocated using ucol_open().
125586 */
125587 static int icuCollationColl(
125588   void *pCtx,
125589   int nLeft,
125590   const void *zLeft,
125591   int nRight,
125592   const void *zRight
125593 ){
125594   UCollationResult res;
125595   UCollator *p = (UCollator *)pCtx;
125596   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
125597   switch( res ){
125598     case UCOL_LESS:    return -1;
125599     case UCOL_GREATER: return +1;
125600     case UCOL_EQUAL:   return 0;
125601   }
125602   assert(!"Unexpected return value from ucol_strcoll()");
125603   return 0;
125604 }
125605
125606 /*
125607 ** Implementation of the scalar function icu_load_collation().
125608 **
125609 ** This scalar function is used to add ICU collation based collation 
125610 ** types to an SQLite database connection. It is intended to be called
125611 ** as follows:
125612 **
125613 **     SELECT icu_load_collation(<locale>, <collation-name>);
125614 **
125615 ** Where <locale> is a string containing an ICU locale identifier (i.e.
125616 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
125617 ** collation sequence to create.
125618 */
125619 static void icuLoadCollation(
125620   sqlite3_context *p, 
125621   int nArg, 
125622   sqlite3_value **apArg
125623 ){
125624   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
125625   UErrorCode status = U_ZERO_ERROR;
125626   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
125627   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
125628   UCollator *pUCollator;    /* ICU library collation object */
125629   int rc;                   /* Return code from sqlite3_create_collation_x() */
125630
125631   assert(nArg==2);
125632   zLocale = (const char *)sqlite3_value_text(apArg[0]);
125633   zName = (const char *)sqlite3_value_text(apArg[1]);
125634
125635   if( !zLocale || !zName ){
125636     return;
125637   }
125638
125639   pUCollator = ucol_open(zLocale, &status);
125640   if( !U_SUCCESS(status) ){
125641     icuFunctionError(p, "ucol_open", status);
125642     return;
125643   }
125644   assert(p);
125645
125646   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
125647       icuCollationColl, icuCollationDel
125648   );
125649   if( rc!=SQLITE_OK ){
125650     ucol_close(pUCollator);
125651     sqlite3_result_error(p, "Error registering collation function", -1);
125652   }
125653 }
125654
125655 /*
125656 ** Register the ICU extension functions with database db.
125657 */
125658 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
125659   struct IcuScalar {
125660     const char *zName;                        /* Function name */
125661     int nArg;                                 /* Number of arguments */
125662     int enc;                                  /* Optimal text encoding */
125663     void *pContext;                           /* sqlite3_user_data() context */
125664     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
125665   } scalars[] = {
125666     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
125667
125668     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
125669     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
125670     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125671     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
125672
125673     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
125674     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
125675     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
125676     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
125677
125678     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
125679     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
125680
125681     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
125682   };
125683
125684   int rc = SQLITE_OK;
125685   int i;
125686
125687   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
125688     struct IcuScalar *p = &scalars[i];
125689     rc = sqlite3_create_function(
125690         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
125691     );
125692   }
125693
125694   return rc;
125695 }
125696
125697 #if !SQLITE_CORE
125698 SQLITE_API int sqlite3_extension_init(
125699   sqlite3 *db, 
125700   char **pzErrMsg,
125701   const sqlite3_api_routines *pApi
125702 ){
125703   SQLITE_EXTENSION_INIT2(pApi)
125704   return sqlite3IcuInit(db);
125705 }
125706 #endif
125707
125708 #endif
125709
125710 /************** End of icu.c *************************************************/
125711 /************** Begin file fts3_icu.c ****************************************/
125712 /*
125713 ** 2007 June 22
125714 **
125715 ** The author disclaims copyright to this source code.  In place of
125716 ** a legal notice, here is a blessing:
125717 **
125718 **    May you do good and not evil.
125719 **    May you find forgiveness for yourself and forgive others.
125720 **    May you share freely, never taking more than you give.
125721 **
125722 *************************************************************************
125723 ** This file implements a tokenizer for fts3 based on the ICU library.
125724 ** 
125725 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
125726 */
125727
125728 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125729 #ifdef SQLITE_ENABLE_ICU
125730
125731
125732 #include <unicode/ubrk.h>
125733 #include <unicode/utf16.h>
125734
125735 typedef struct IcuTokenizer IcuTokenizer;
125736 typedef struct IcuCursor IcuCursor;
125737
125738 struct IcuTokenizer {
125739   sqlite3_tokenizer base;
125740   char *zLocale;
125741 };
125742
125743 struct IcuCursor {
125744   sqlite3_tokenizer_cursor base;
125745
125746   UBreakIterator *pIter;      /* ICU break-iterator object */
125747   int nChar;                  /* Number of UChar elements in pInput */
125748   UChar *aChar;               /* Copy of input using utf-16 encoding */
125749   int *aOffset;               /* Offsets of each character in utf-8 input */
125750
125751   int nBuffer;
125752   char *zBuffer;
125753
125754   int iToken;
125755 };
125756
125757 /*
125758 ** Create a new tokenizer instance.
125759 */
125760 static int icuCreate(
125761   int argc,                            /* Number of entries in argv[] */
125762   const char * const *argv,            /* Tokenizer creation arguments */
125763   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
125764 ){
125765   IcuTokenizer *p;
125766   int n = 0;
125767
125768   if( argc>0 ){
125769     n = strlen(argv[0])+1;
125770   }
125771   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
125772   if( !p ){
125773     return SQLITE_NOMEM;
125774   }
125775   memset(p, 0, sizeof(IcuTokenizer));
125776
125777   if( n ){
125778     p->zLocale = (char *)&p[1];
125779     memcpy(p->zLocale, argv[0], n);
125780   }
125781
125782   *ppTokenizer = (sqlite3_tokenizer *)p;
125783
125784   return SQLITE_OK;
125785 }
125786
125787 /*
125788 ** Destroy a tokenizer
125789 */
125790 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
125791   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
125792   sqlite3_free(p);
125793   return SQLITE_OK;
125794 }
125795
125796 /*
125797 ** Prepare to begin tokenizing a particular string.  The input
125798 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
125799 ** used to incrementally tokenize this string is returned in 
125800 ** *ppCursor.
125801 */
125802 static int icuOpen(
125803   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125804   const char *zInput,                    /* Input string */
125805   int nInput,                            /* Length of zInput in bytes */
125806   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125807 ){
125808   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
125809   IcuCursor *pCsr;
125810
125811   const int32_t opt = U_FOLD_CASE_DEFAULT;
125812   UErrorCode status = U_ZERO_ERROR;
125813   int nChar;
125814
125815   UChar32 c;
125816   int iInput = 0;
125817   int iOut = 0;
125818
125819   *ppCursor = 0;
125820
125821   if( nInput<0 ){
125822     nInput = strlen(zInput);
125823   }
125824   nChar = nInput+1;
125825   pCsr = (IcuCursor *)sqlite3_malloc(
125826       sizeof(IcuCursor) +                /* IcuCursor */
125827       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
125828       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
125829   );
125830   if( !pCsr ){
125831     return SQLITE_NOMEM;
125832   }
125833   memset(pCsr, 0, sizeof(IcuCursor));
125834   pCsr->aChar = (UChar *)&pCsr[1];
125835   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
125836
125837   pCsr->aOffset[iOut] = iInput;
125838   U8_NEXT(zInput, iInput, nInput, c); 
125839   while( c>0 ){
125840     int isError = 0;
125841     c = u_foldCase(c, opt);
125842     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
125843     if( isError ){
125844       sqlite3_free(pCsr);
125845       return SQLITE_ERROR;
125846     }
125847     pCsr->aOffset[iOut] = iInput;
125848
125849     if( iInput<nInput ){
125850       U8_NEXT(zInput, iInput, nInput, c);
125851     }else{
125852       c = 0;
125853     }
125854   }
125855
125856   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
125857   if( !U_SUCCESS(status) ){
125858     sqlite3_free(pCsr);
125859     return SQLITE_ERROR;
125860   }
125861   pCsr->nChar = iOut;
125862
125863   ubrk_first(pCsr->pIter);
125864   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
125865   return SQLITE_OK;
125866 }
125867
125868 /*
125869 ** Close a tokenization cursor previously opened by a call to icuOpen().
125870 */
125871 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
125872   IcuCursor *pCsr = (IcuCursor *)pCursor;
125873   ubrk_close(pCsr->pIter);
125874   sqlite3_free(pCsr->zBuffer);
125875   sqlite3_free(pCsr);
125876   return SQLITE_OK;
125877 }
125878
125879 /*
125880 ** Extract the next token from a tokenization cursor.
125881 */
125882 static int icuNext(
125883   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
125884   const char **ppToken,               /* OUT: *ppToken is the token text */
125885   int *pnBytes,                       /* OUT: Number of bytes in token */
125886   int *piStartOffset,                 /* OUT: Starting offset of token */
125887   int *piEndOffset,                   /* OUT: Ending offset of token */
125888   int *piPosition                     /* OUT: Position integer of token */
125889 ){
125890   IcuCursor *pCsr = (IcuCursor *)pCursor;
125891
125892   int iStart = 0;
125893   int iEnd = 0;
125894   int nByte = 0;
125895
125896   while( iStart==iEnd ){
125897     UChar32 c;
125898
125899     iStart = ubrk_current(pCsr->pIter);
125900     iEnd = ubrk_next(pCsr->pIter);
125901     if( iEnd==UBRK_DONE ){
125902       return SQLITE_DONE;
125903     }
125904
125905     while( iStart<iEnd ){
125906       int iWhite = iStart;
125907       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
125908       if( u_isspace(c) ){
125909         iStart = iWhite;
125910       }else{
125911         break;
125912       }
125913     }
125914     assert(iStart<=iEnd);
125915   }
125916
125917   do {
125918     UErrorCode status = U_ZERO_ERROR;
125919     if( nByte ){
125920       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
125921       if( !zNew ){
125922         return SQLITE_NOMEM;
125923       }
125924       pCsr->zBuffer = zNew;
125925       pCsr->nBuffer = nByte;
125926     }
125927
125928     u_strToUTF8(
125929         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
125930         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
125931         &status                                  /* Output success/failure */
125932     );
125933   } while( nByte>pCsr->nBuffer );
125934
125935   *ppToken = pCsr->zBuffer;
125936   *pnBytes = nByte;
125937   *piStartOffset = pCsr->aOffset[iStart];
125938   *piEndOffset = pCsr->aOffset[iEnd];
125939   *piPosition = pCsr->iToken++;
125940
125941   return SQLITE_OK;
125942 }
125943
125944 /*
125945 ** The set of routines that implement the simple tokenizer
125946 */
125947 static const sqlite3_tokenizer_module icuTokenizerModule = {
125948   0,                           /* iVersion */
125949   icuCreate,                   /* xCreate  */
125950   icuDestroy,                  /* xCreate  */
125951   icuOpen,                     /* xOpen    */
125952   icuClose,                    /* xClose   */
125953   icuNext,                     /* xNext    */
125954 };
125955
125956 /*
125957 ** Set *ppModule to point at the implementation of the ICU tokenizer.
125958 */
125959 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
125960   sqlite3_tokenizer_module const**ppModule
125961 ){
125962   *ppModule = &icuTokenizerModule;
125963 }
125964
125965 #endif /* defined(SQLITE_ENABLE_ICU) */
125966 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125967
125968 /************** End of fts3_icu.c ********************************************/